ETH Price: $2,155.47 (+5.28%)

Transaction Decoder

Block:
10429057 at Jul-10-2020 02:27:09 AM +UTC
Transaction Fee:
0.01188 ETH $25.61
Gas Used:
396,000 Gas / 30 Gwei

Emitted Events:

177 WETH9.Deposit( dst=OneSplit, wad=123600000000000000000 )
178 WETH9.Transfer( src=OneSplit, dst=UniswapV2Pair, wad=123600000000000000000 )
179 AdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000c5be99a02c6857f9eac67bbce58df5572498f40c, 0x0000000000000000000000009021c84f3900b610ab8625d26d739e3b7bff86ab, 000000000000000000000000000000000000000000000000000009dbb4b2a61e )
180 UniswapV2Pair.Sync( reserve0=24446299314136563286546, reserve1=2139423380814352 )
181 UniswapV2Pair.Swap( sender=OneSplit, amount0In=123600000000000000000, amount1In=0, amount0Out=0, amount1Out=10839234094622, to=OneSplit )
182 AdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000009021c84f3900b610ab8625d26d739e3b7bff86ab, 0x000000000000000000000000ef7c96ac993fa077035c65581253f43b9814e3b4, 000000000000000000000000000000000000000000000000000009dbb4b2a61e )
183 AdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000ef7c96ac993fa077035c65581253f43b9814e3b4, 0x0000000000000000000000005c5b40855fc364b797c1f539f7eb39cdc94a8a91, 000000000000000000000000000000000000000000000000000009dbb4b2a61e )
184 AdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000005c5b40855fc364b797c1f539f7eb39cdc94a8a91, 0x00000000000000000000000011111254369792b2ca5d084ab5eea397ca8fa48b, 000000000000000000000000000000000000000000000000000009dbb4b2a61e )
185 ChiToken.Transfer( from=[Sender] 0xee27c3e800f43e7ee67fce2a0a55dbed7fd302da, to=0x0000000000000000000000000000000000000000, value=0 )
186 ChiToken.Approval( owner=[Sender] 0xee27c3e800f43e7ee67fce2a0a55dbed7fd302da, spender=ChiSpender, value=0 )
187 ChiToken.Transfer( from=0x488B2C2ca3dcd473AF4b05505f3Ba1Ec4bFfDA94, to=0x0000000000000000000000000000000000000000, value=0 )
188 AdminUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000011111254369792b2ca5d084ab5eea397ca8fa48b, 0x000000000000000000000000ee27c3e800f43e7ee67fce2a0a55dbed7fd302da, 000000000000000000000000000000000000000000000000000009dbb4b2a61e )
189 OneInchExchange.History( sender=[Sender] 0xee27c3e800f43e7ee67fce2a0a55dbed7fd302da, fromToken=0xEeeeeEee...eeeeeEEeE, toToken=AdminUpgradeabilityProxy, fromAmount=123600000000000000000, toAmount=10839234094622 )
190 OneInchExchange.Swapped( fromToken=0xEeeeeEee...eeeeeEEeE, toToken=AdminUpgradeabilityProxy, referrer=0x0000000000000000000000000000000000000000, fromAmount=123600000000000000000, toAmount=10839234094622, referrerFee=0, fee=0 )

Account State Difference:

  Address   Before After State Difference Code
(Spark Pool)
77.720680916509697395 Eth77.732560916509697395 Eth0.01188
0xC02aaA39...83C756Cc2 2,579,669.048038767942091596 Eth2,579,792.648038767942091596 Eth123.6
0xc5be99A0...72498F40c
0xD46bA6D9...d5039A161
0xEe27C3e8...d7fD302DA
123.733808947252559844 Eth
Nonce: 213
0.121928947252559844 Eth
Nonce: 214
123.61188

Execution Trace

ETH 123.6 OneInchExchange.swap( fromToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, toToken=0xD46bA6D942050d489DBd938a2C909A5d5039A161, fromTokenAmount=123600000000000000000, minReturnAmount=10779960586320, guaranteedAmount=10888849077091, referrer=0x0000000000000000000000000000000000000000, callAddresses=[0x5c5b40855fc364b797c1F539F7Eb39cDC94a8a91], callDataConcat=0xA832F707000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000D46BA6D942050D489DBD938A2C909A5D5039A161000000000000000000000000000000000000000000000006B34B69239E480000000000000000000000000000000000000000000000000000000009CDE7B8B050000000000000000000000000000000000000000000000000000009E741FB3363000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000072000000000000000000000000000000000000000000000000000000000000007800000000000000000000000000000000000000000000000000000000000000001000000000000000000000000EF7C96AC993FA077035C65581253F43B9814E3B40000000000000000000000000000000000000000000000000000000000000564C785139600000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000000000000000000000000006B34B69239E4800000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000D46BA6D942050D489DBD938A2C909A5D5039A161000000000000000000000000000000000000000000000000000000000000001F0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005640000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000006B34B69239E480000, starts=[0, 1988], gasLimitsAndValues=[123600000000000000000] ) => ( returnAmount=10839234094622 )
  • ETH 123.6 0x5c5b40855fc364b797c1f539f7eb39cdc94a8a91.a832f707( )
    • ChiToken.STATICCALL( )
    • GasToken2.STATICCALL( )
    • ETH 123.6 OneSplitWrap.swapMulti( tokens=[0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0xD46bA6D942050d489DBd938a2C909A5d5039A161], amount=123600000000000000000, minReturn=1, distribution=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], flags=[57896044618658097711785492504343953926634992332820282019728792003956564819968, 0] ) => ( returnAmount=10839234094622 )
      • DmmController.getUnderlyingTokenForDmm( dmmToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( 0x0000000000000000000000000000000000000000 )
      • DmmController.getUnderlyingTokenForDmm( dmmToken=0xD46bA6D942050d489DBd938a2C909A5d5039A161 ) => ( 0x0000000000000000000000000000000000000000 )
      • CompoundRegistry.tokenByCToken( cToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( 0x0000000000000000000000000000000000000000 )
      • CompoundRegistry.tokenByCToken( cToken=0xD46bA6D942050d489DBd938a2C909A5d5039A161 ) => ( 0x0000000000000000000000000000000000000000 )
      • AdminUpgradeabilityProxy.STATICCALL( )
        • UFragments.DELEGATECALL( )
        • AaveRegistry.tokenByAToken( aToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ) => ( 0x0000000000000000000000000000000000000000 )
        • AaveRegistry.tokenByAToken( aToken=0xD46bA6D942050d489DBd938a2C909A5d5039A161 ) => ( 0x0000000000000000000000000000000000000000 )
        • ETH 123.6 OneSplit.swap( fromToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, destToken=0xD46bA6D942050d489DBd938a2C909A5d5039A161, amount=123600000000000000000, minReturn=0, distribution=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], flags=0 ) => ( returnAmount=10839234094622 )
          • ETH 123.6 WETH9.CALL( )
          • UniswapV2Factory.getPair( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0xD46bA6D942050d489DBd938a2C909A5d5039A161 ) => ( 0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c )
          • WETH9.balanceOf( 0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c ) => ( 24322699314136563286546 )
          • AdminUpgradeabilityProxy.70a08231( )
            • UFragments.balanceOf( who=0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c ) => ( 2150262614908974 )
            • WETH9.transfer( dst=0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c, wad=123600000000000000000 ) => ( True )
            • UniswapV2Pair.swap( amount0Out=0, amount1Out=10839234094622, to=0x9021C84f3900B610ab8625d26d739e3B7bFf86aB, data=0x )
              • AdminUpgradeabilityProxy.a9059cbb( )
                • UFragments.transfer( to=0x9021C84f3900B610ab8625d26d739e3B7bFf86aB, value=10839234094622 ) => ( True )
                • WETH9.balanceOf( 0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c ) => ( 24446299314136563286546 )
                • AdminUpgradeabilityProxy.70a08231( )
                  • UFragments.balanceOf( who=0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c ) => ( 2139423380814352 )
                  • AdminUpgradeabilityProxy.70a08231( )
                    • UFragments.balanceOf( who=0x9021C84f3900B610ab8625d26d739e3B7bFf86aB ) => ( 10839234094622 )
                    • AdminUpgradeabilityProxy.a9059cbb( )
                      • UFragments.transfer( to=0xEf7C96AC993fa077035C65581253F43b9814e3b4, value=10839234094622 ) => ( True )
                      • AdminUpgradeabilityProxy.70a08231( )
                        • UFragments.balanceOf( who=0xEf7C96AC993fa077035C65581253F43b9814e3b4 ) => ( 10839234094622 )
                        • AdminUpgradeabilityProxy.a9059cbb( )
                          • UFragments.transfer( to=0x5c5b40855fc364b797c1F539F7Eb39cDC94a8a91, value=10839234094622 ) => ( True )
                          • AdminUpgradeabilityProxy.70a08231( )
                            • UFragments.balanceOf( who=0x5c5b40855fc364b797c1F539F7Eb39cDC94a8a91 ) => ( 10839234094622 )
                            • AdminUpgradeabilityProxy.a9059cbb( )
                              • UFragments.transfer( to=0x11111254369792b2Ca5d084aB5eEA397cA8fa48B, value=10839234094622 ) => ( True )
                              • ChiToken.STATICCALL( )
                              • GasToken2.STATICCALL( )
                              • ChiSpender.burnChi( tokens=10 ) => ( 0 )
                                • ChiToken.freeFromUpTo( from=0xEe27C3e800F43e7ee67FCE2a0a55dBed7fD302DA, value=10 ) => ( 0 )
                                • 0x488b2c2ca3dcd473af4b05505f3ba1ec4bffda94.17484c2e( )
                                  • ChiToken.freeUpTo( value=10 ) => ( 0 )
                                  • AdminUpgradeabilityProxy.70a08231( )
                                    • UFragments.balanceOf( who=0x11111254369792b2Ca5d084aB5eEA397cA8fa48B ) => ( 10839234094622 )
                                    • AdminUpgradeabilityProxy.a9059cbb( )
                                      • UFragments.transfer( to=0xEe27C3e800F43e7ee67FCE2a0a55dBed7fD302DA, value=10839234094622 ) => ( True )
                                      • TokenSpender.burnGasToken( gasSpent=469765 )
                                        • GasToken2.freeUpTo( value=11 ) => ( freed=0 )
                                          File 1 of 15: OneInchExchange
                                          pragma solidity ^0.5.0;
                                          pragma experimental ABIEncoderV2;
                                          
                                          
                                          library ExternalCall {
                                              // Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
                                              // call has been separated into its own function in order to take advantage
                                              // of the Solidity's code generator to produce a loop that copies tx.data into memory.
                                              function externalCall(address destination, uint value, bytes memory data, uint dataOffset, uint dataLength, uint gasLimit) internal returns(bool result) {
                                                  // solium-disable-next-line security/no-inline-assembly
                                                  if (gasLimit == 0) {
                                                      gasLimit = gasleft() - 40000;
                                                  }
                                                  assembly {
                                                      let x := mload(0x40)   // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
                                                      let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
                                                      result := call(
                                                          gasLimit,
                                                          destination,
                                                          value,
                                                          add(d, dataOffset),
                                                          dataLength,        // Size of the input (in bytes) - this is what fixes the padding problem
                                                          x,
                                                          0                  // Output is ignored, therefore the output size is zero
                                                      )
                                                  }
                                              }
                                          }
                                          
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see `ERC20Detailed`.
                                           */
                                          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.
                                               *
                                               * > 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);
                                          }
                                          
                                          
                                          /**
                                           * @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, 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");
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, "SafeMath: division by zero");
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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 Contract module which provides a basic access control mechanism, where
                                           * there is an account (an owner) that can be granted exclusive access to
                                           * specific functions.
                                           *
                                           * This module is used through inheritance. It will make available the modifier
                                           * `onlyOwner`, which can be aplied to your functions to restrict their use to
                                           * the owner.
                                           */
                                          contract Ownable {
                                              address private _owner;
                                          
                                              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                          
                                              /**
                                               * @dev Initializes the contract setting the deployer as the initial owner.
                                               */
                                              constructor () internal {
                                                  _owner = msg.sender;
                                                  emit OwnershipTransferred(address(0), _owner);
                                              }
                                          
                                              /**
                                               * @dev Returns the address of the current owner.
                                               */
                                              function owner() public view returns (address) {
                                                  return _owner;
                                              }
                                          
                                              /**
                                               * @dev Throws if called by any account other than the owner.
                                               */
                                              modifier onlyOwner() {
                                                  require(isOwner(), "Ownable: caller is not the owner");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Returns true if the caller is the current owner.
                                               */
                                              function isOwner() public view returns (bool) {
                                                  return msg.sender == _owner;
                                              }
                                          
                                              /**
                                               * @dev Leaves the contract without owner. It will not be possible to call
                                               * `onlyOwner` functions anymore. Can only be called by the current owner.
                                               *
                                               * > Note: Renouncing ownership will leave the contract without an owner,
                                               * thereby removing any functionality that is only available to the owner.
                                               */
                                              function renounceOwnership() public onlyOwner {
                                                  emit OwnershipTransferred(_owner, address(0));
                                                  _owner = address(0);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               * Can only be called by the current owner.
                                               */
                                              function transferOwnership(address newOwner) public onlyOwner {
                                                  _transferOwnership(newOwner);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               */
                                              function _transferOwnership(address newOwner) internal {
                                                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                                                  emit OwnershipTransferred(_owner, newOwner);
                                                  _owner = newOwner;
                                              }
                                          }
                                          
                                          contract IZrxExchange {
                                          
                                              struct Order {
                                                  address makerAddress;           // Address that created the order.
                                                  address takerAddress;           // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
                                                  address feeRecipientAddress;    // Address that will recieve fees when order is filled.
                                                  address senderAddress;          // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
                                                  uint256 makerAssetAmount;       // Amount of makerAsset being offered by maker. Must be greater than 0.
                                                  uint256 takerAssetAmount;       // Amount of takerAsset being bid on by maker. Must be greater than 0.
                                                  uint256 makerFee;               // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
                                                  uint256 takerFee;               // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
                                                  uint256 expirationTimeSeconds;  // Timestamp in seconds at which order expires.
                                                  uint256 salt;                   // Arbitrary number to facilitate uniqueness of the order's hash.
                                                  bytes makerAssetData;           // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
                                                  bytes takerAssetData;           // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
                                              }
                                          
                                              struct OrderInfo {
                                                  uint8 orderStatus;                    // Status that describes order's validity and fillability.
                                                  bytes32 orderHash;                    // EIP712 hash of the order (see IZrxExchange.getOrderHash).
                                                  uint256 orderTakerAssetFilledAmount;  // Amount of order that has already been filled.
                                              }
                                          
                                              struct FillResults {
                                                  uint256 makerAssetFilledAmount;  // Total amount of makerAsset(s) filled.
                                                  uint256 takerAssetFilledAmount;  // Total amount of takerAsset(s) filled.
                                                  uint256 makerFeePaid;            // Total amount of ZRX paid by maker(s) to feeRecipient(s).
                                                  uint256 takerFeePaid;            // Total amount of ZRX paid by taker to feeRecipients(s).
                                              }
                                          
                                              function getOrderInfo(Order memory order)
                                                  public
                                                  view
                                                  returns (OrderInfo memory orderInfo);
                                          
                                              function getOrdersInfo(Order[] memory orders)
                                                  public
                                                  view
                                                  returns (OrderInfo[] memory ordersInfo);
                                          
                                              function fillOrder(
                                                  Order memory order,
                                                  uint256 takerAssetFillAmount,
                                                  bytes memory signature
                                              )
                                                  public
                                                  returns (FillResults memory fillResults);
                                          
                                              function fillOrderNoThrow(
                                                  Order memory order,
                                                  uint256 takerAssetFillAmount,
                                                  bytes memory signature
                                              )
                                                  public
                                                  returns (FillResults memory fillResults);
                                          }
                                          
                                          
                                          contract IGST2 is IERC20 {
                                          
                                              function freeUpTo(uint256 value) external returns (uint256 freed);
                                          
                                              function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
                                          
                                              function balanceOf(address who) external view returns (uint256);
                                          }
                                          
                                          
                                          /**
                                           * @dev Collection of functions related to the address type,
                                           */
                                          library Address {
                                              /**
                                               * @dev Returns true if `account` is a contract.
                                               *
                                               * This test is non-exhaustive, and there may be false-negatives: during the
                                               * execution of a contract's constructor, its address will be reported as
                                               * not containing a contract.
                                               *
                                               * > It is unsafe to assume that an address for which this function returns
                                               * false is an externally-owned account (EOA) and not a contract.
                                               */
                                              function isContract(address account) internal view returns (bool) {
                                                  // This method relies in 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;
                                              }
                                          }
                                          
                                          
                                          
                                          contract IWETH is IERC20 {
                                          
                                              function deposit() external payable;
                                          
                                              function withdraw(uint256 amount) external;
                                          }
                                          
                                          
                                          
                                          contract Shutdownable is Ownable {
                                          
                                              bool public isShutdown;
                                          
                                              event Shutdown();
                                          
                                              modifier notShutdown {
                                                  require(!isShutdown, "Smart contract is shut down.");
                                                  _;
                                              }
                                          
                                              function shutdown() public onlyOwner {
                                                  isShutdown = true;
                                                  emit Shutdown();
                                              }
                                          }
                                          
                                          contract IERC20NonView {
                                              // Methods are not view to avoid throw on proxy tokens with delegatecall inside
                                              function balanceOf(address user) public returns(uint256);
                                              function allowance(address from, address to) public returns(uint256);
                                          }
                                          
                                          contract ZrxMarketOrder {
                                          
                                              using SafeMath for uint256;
                                          
                                              function marketSellOrdersProportion(
                                                  IERC20 tokenSell,
                                                  address tokenBuy,
                                                  address zrxExchange,
                                                  address zrxTokenProxy,
                                                  IZrxExchange.Order[] calldata orders,
                                                  bytes[] calldata signatures,
                                                  uint256 mul,
                                                  uint256 div
                                              )
                                                  external
                                              {
                                                  uint256 amount = tokenSell.balanceOf(msg.sender).mul(mul).div(div);
                                                  this.marketSellOrders(tokenBuy, zrxExchange, zrxTokenProxy, amount, orders, signatures);
                                              }
                                          
                                              function marketSellOrders(
                                                  address makerAsset,
                                                  address zrxExchange,
                                                  address zrxTokenProxy,
                                                  uint256 takerAssetFillAmount,
                                                  IZrxExchange.Order[] calldata orders,
                                                  bytes[] calldata signatures
                                              )
                                                  external
                                                  returns (IZrxExchange.FillResults memory totalFillResults)
                                              {
                                                  for (uint i = 0; i < orders.length; i++) {
                                          
                                                      // Stop execution if the entire amount of takerAsset has been sold
                                                      if (totalFillResults.takerAssetFilledAmount >= takerAssetFillAmount) {
                                                          break;
                                                      }
                                          
                                                      // Calculate the remaining amount of takerAsset to sell
                                                      uint256 remainingTakerAmount = takerAssetFillAmount.sub(totalFillResults.takerAssetFilledAmount);
                                          
                                                      IZrxExchange.OrderInfo memory orderInfo = IZrxExchange(zrxExchange).getOrderInfo(orders[i]);
                                                      uint256 orderRemainingTakerAmount = orders[i].takerAssetAmount.sub(orderInfo.orderTakerAssetFilledAmount);
                                          
                                                      // Check available balance and allowance and update orderRemainingTakerAmount
                                                      {
                                                          uint256 balance = IERC20NonView(makerAsset).balanceOf(orders[i].makerAddress);
                                                          uint256 allowance = IERC20NonView(makerAsset).allowance(orders[i].makerAddress, zrxTokenProxy);
                                                          uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
                                                          uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
                                          
                                                          if (availableTakerAmount < orderRemainingTakerAmount) {
                                                              orderRemainingTakerAmount = availableTakerAmount;
                                                          }
                                                      }
                                          
                                                      uint256 takerAmount = (orderRemainingTakerAmount < remainingTakerAmount) ? orderRemainingTakerAmount : remainingTakerAmount;
                                          
                                                      IZrxExchange.FillResults memory fillResults = IZrxExchange(zrxExchange).fillOrderNoThrow(
                                                          orders[i],
                                                          takerAmount,
                                                          signatures[i]
                                                      );
                                          
                                                      _addFillResults(totalFillResults, fillResults);
                                                  }
                                          
                                                  return totalFillResults;
                                              }
                                          
                                              function _addFillResults(
                                                  IZrxExchange.FillResults memory totalFillResults,
                                                  IZrxExchange.FillResults memory singleFillResults
                                              )
                                                  internal
                                                  pure
                                              {
                                                  totalFillResults.makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount.add(singleFillResults.makerAssetFilledAmount);
                                                  totalFillResults.takerAssetFilledAmount = totalFillResults.takerAssetFilledAmount.add(singleFillResults.takerAssetFilledAmount);
                                                  totalFillResults.makerFeePaid = totalFillResults.makerFeePaid.add(singleFillResults.makerFeePaid);
                                                  totalFillResults.takerFeePaid = totalFillResults.takerFeePaid.add(singleFillResults.takerFeePaid);
                                              }
                                          
                                              function getOrdersInfoRespectingBalancesAndAllowances(
                                                  IERC20 token,
                                                  IZrxExchange zrx,
                                                  address zrxTokenProxy,
                                                  IZrxExchange.Order[] memory orders
                                              )
                                                  public
                                                  view
                                                  returns (IZrxExchange.OrderInfo[] memory ordersInfo)
                                              {
                                                  ordersInfo = zrx.getOrdersInfo(orders);
                                          
                                                  for (uint i = 0; i < ordersInfo.length; i++) {
                                          
                                                      uint256 balance = token.balanceOf(orders[i].makerAddress);
                                                      uint256 allowance = token.allowance(orders[i].makerAddress, zrxTokenProxy);
                                                      uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
                                                      uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
                                          
                                                      for (uint j = 0; j < i; j++) {
                                          
                                                          if (orders[j].makerAddress == orders[i].makerAddress) {
                                          
                                                              uint256 orderTakerAssetRemainigAmount = orders[j].takerAssetAmount.sub(
                                                                  ordersInfo[j].orderTakerAssetFilledAmount
                                                              );
                                          
                                                              if (availableTakerAmount > orderTakerAssetRemainigAmount) {
                                          
                                                                  availableTakerAmount = availableTakerAmount.sub(orderTakerAssetRemainigAmount);
                                                              } else {
                                          
                                                                  availableTakerAmount = 0;
                                                                  break;
                                                              }
                                                          }
                                                      }
                                          
                                                      uint256 remainingTakerAmount = orders[i].takerAssetAmount.sub(
                                                          ordersInfo[i].orderTakerAssetFilledAmount
                                                      );
                                          
                                                      if (availableTakerAmount < remainingTakerAmount) {
                                          
                                                          ordersInfo[i].orderTakerAssetFilledAmount = orders[i].takerAssetAmount.sub(availableTakerAmount);
                                                      }
                                                  }
                                              }
                                          }
                                          
                                          
                                          
                                          
                                          /**
                                           * @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 ERC20;` 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));
                                              }
                                          
                                              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);
                                                  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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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");
                                                  }
                                              }
                                          }
                                          
                                          
                                          
                                          
                                          
                                          library UniversalERC20 {
                                          
                                              using SafeMath for uint256;
                                              using SafeERC20 for IERC20;
                                          
                                              IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
                                              IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount) internal {
                                                  universalTransfer(token, to, amount, false);
                                              }
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount, bool mayFail) internal returns(bool) {
                                                  if (amount == 0) {
                                                      return true;
                                                  }
                                          
                                                  if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
                                                      if (mayFail) {
                                                          return address(uint160(to)).send(amount);
                                                      } else {
                                                          address(uint160(to)).transfer(amount);
                                                          return true;
                                                      }
                                                  } else {
                                                      token.safeTransfer(to, amount);
                                                      return true;
                                                  }
                                              }
                                          
                                              function universalApprove(IERC20 token, address to, uint256 amount) internal {
                                                  if (token != ZERO_ADDRESS && token != ETH_ADDRESS) {
                                                      token.safeApprove(to, amount);
                                                  }
                                              }
                                          
                                              function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
                                                      require(from == msg.sender && msg.value >= amount, "msg.value is zero");
                                                      if (to != address(this)) {
                                                          address(uint160(to)).transfer(amount);
                                                      }
                                                      if (msg.value > amount) {
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(from, to, amount);
                                                  }
                                              }
                                          
                                              function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
                                                  if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
                                                      return who.balance;
                                                  } else {
                                                      return token.balanceOf(who);
                                                  }
                                              }
                                          }
                                          
                                          
                                          
                                          contract TokenSpender {
                                          
                                              using SafeERC20 for IERC20;
                                          
                                              address public owner;
                                              IGST2 public gasToken;
                                              address public gasTokenOwner;
                                          
                                              constructor(IGST2 _gasToken, address _gasTokenOwner) public {
                                                  owner = msg.sender;
                                                  gasToken = _gasToken;
                                                  gasTokenOwner = _gasTokenOwner;
                                              }
                                          
                                              function claimTokens(IERC20 token, address who, address dest, uint256 amount) external {
                                                  require(msg.sender == owner, "Access restricted");
                                                  token.safeTransferFrom(who, dest, amount);
                                              }
                                          
                                              function burnGasToken(uint gasSpent) external {
                                                  require(msg.sender == owner, "Access restricted");
                                                  uint256 tokens = (gasSpent + 14154) / 41130;
                                                  gasToken.freeUpTo(tokens);
                                              }
                                          
                                              function() external {
                                                  if (msg.sender == gasTokenOwner) {
                                                      gasToken.transfer(msg.sender, gasToken.balanceOf(address(this)));
                                                  }
                                              }
                                          }
                                          
                                          contract OneInchExchange is Shutdownable, ZrxMarketOrder {
                                          
                                              using SafeMath for uint256;
                                              using UniversalERC20 for IERC20;
                                              using ExternalCall for address;
                                          
                                              IERC20 constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              TokenSpender public spender;
                                              uint fee; // 10000 => 100%, 1 => 0.01%
                                          
                                              event History(
                                                  address indexed sender,
                                                  IERC20 fromToken,
                                                  IERC20 toToken,
                                                  uint256 fromAmount,
                                                  uint256 toAmount
                                              );
                                          
                                              event Swapped(
                                                  IERC20 indexed fromToken,
                                                  IERC20 indexed toToken,
                                                  address indexed referrer,
                                                  uint256 fromAmount,
                                                  uint256 toAmount,
                                                  uint256 referrerFee,
                                                  uint256 fee
                                              );
                                          
                                              constructor(address _owner, IGST2 _gasToken, uint _fee) public {
                                                  spender = new TokenSpender(
                                                      _gasToken,
                                                      _owner
                                                  );
                                          
                                                  _transferOwnership(_owner);
                                                  fee = _fee;
                                              }
                                          
                                              function() external payable notShutdown {
                                                  require(msg.sender != tx.origin);
                                              }
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 toToken,
                                                  uint256 fromTokenAmount,
                                                  uint256 minReturnAmount,
                                                  uint256 guaranteedAmount,
                                                  address payable referrer,
                                                  address[] memory callAddresses,
                                                  bytes memory callDataConcat,
                                                  uint256[] memory starts,
                                                  uint256[] memory gasLimitsAndValues
                                              )
                                              public
                                              payable
                                              notShutdown
                                              returns (uint256 returnAmount)
                                              {
                                                  uint256 gasProvided = gasleft();
                                          
                                                  require(minReturnAmount > 0, "Min return should be bigger then 0.");
                                                  require(callAddresses.length > 0, "Call data should exists.");
                                          
                                                  if (fromToken != ETH_ADDRESS) {
                                                      spender.claimTokens(fromToken, msg.sender, address(this), fromTokenAmount);
                                                  }
                                          
                                                  for (uint i = 0; i < callAddresses.length; i++) {
                                                      require(callAddresses[i] != address(spender), "Access denied");
                                                      require(callAddresses[i].externalCall(
                                                          gasLimitsAndValues[i] & ((1 << 128) - 1),
                                                          callDataConcat,
                                                          starts[i],
                                                          starts[i + 1] - starts[i],
                                                          gasLimitsAndValues[i] >> 128
                                                      ));
                                                  }
                                          
                                                  // Return back all unswapped
                                                  fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
                                          
                                                  returnAmount = toToken.universalBalanceOf(address(this));
                                                  (uint256 toTokenAmount, uint256 referrerFee) = _handleFees(toToken, referrer, returnAmount, guaranteedAmount);
                                          
                                                  require(toTokenAmount >= minReturnAmount, "Return amount is not enough");
                                                  toToken.universalTransfer(msg.sender, toTokenAmount);
                                          
                                                  emit History(
                                                      msg.sender,
                                                      fromToken,
                                                      toToken,
                                                      fromTokenAmount,
                                                      toTokenAmount
                                                  );
                                          
                                                  emit Swapped(
                                                      fromToken,
                                                      toToken,
                                                      referrer,
                                                      fromTokenAmount,
                                                      toTokenAmount,
                                                      referrerFee,
                                                      returnAmount.sub(toTokenAmount)
                                                  );
                                          
                                                  spender.burnGasToken(gasProvided.sub(gasleft()));
                                              }
                                          
                                              function _handleFees(
                                                  IERC20 toToken,
                                                  address referrer,
                                                  uint256 returnAmount,
                                                  uint256 guaranteedAmount
                                              )
                                              internal
                                              returns (
                                                  uint256 toTokenAmount,
                                                  uint256 referrerFee
                                              )
                                              {
                                                  if (returnAmount <= guaranteedAmount) {
                                                      return (returnAmount, 0);
                                                  }
                                          
                                                  uint256 feeAmount = returnAmount.sub(guaranteedAmount).mul(fee).div(10000);
                                          
                                                  if (referrer != address(0) && referrer != msg.sender && referrer != tx.origin) {
                                                      referrerFee = feeAmount.div(10);
                                                      if (toToken.universalTransfer(referrer, referrerFee, true)) {
                                                          returnAmount = returnAmount.sub(referrerFee);
                                                          feeAmount = feeAmount.sub(referrerFee);
                                                      } else {
                                                          referrerFee = 0;
                                                      }
                                                  }
                                          
                                                  if (toToken.universalTransfer(owner(), feeAmount, true)) {
                                                      returnAmount = returnAmount.sub(feeAmount);
                                                  }
                                          
                                                  return (returnAmount, referrerFee);
                                              }
                                          
                                              function infiniteApproveIfNeeded(IERC20 token, address to) external notShutdown {
                                                  if (token != ETH_ADDRESS) {
                                                      if ((token.allowance(address(this), to) >> 255) == 0) {
                                                          token.universalApprove(to, uint256(- 1));
                                                      }
                                                  }
                                              }
                                          
                                              function withdrawAllToken(IWETH token) external notShutdown {
                                                  uint256 amount = token.balanceOf(address(this));
                                                  token.withdraw(amount);
                                              }
                                          }

                                          File 2 of 15: WETH9
                                          // Copyright (C) 2015, 2016, 2017 Dapphub
                                          
                                          // This program is free software: you can redistribute it and/or modify
                                          // it under the terms of the GNU General Public License as published by
                                          // the Free Software Foundation, either version 3 of the License, or
                                          // (at your option) any later version.
                                          
                                          // This program is distributed in the hope that it will be useful,
                                          // but WITHOUT ANY WARRANTY; without even the implied warranty of
                                          // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                                          // GNU General Public License for more details.
                                          
                                          // You should have received a copy of the GNU General Public License
                                          // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                                          
                                          pragma solidity ^0.4.18;
                                          
                                          contract WETH9 {
                                              string public name     = "Wrapped Ether";
                                              string public symbol   = "WETH";
                                              uint8  public decimals = 18;
                                          
                                              event  Approval(address indexed src, address indexed guy, uint wad);
                                              event  Transfer(address indexed src, address indexed dst, uint wad);
                                              event  Deposit(address indexed dst, uint wad);
                                              event  Withdrawal(address indexed src, uint wad);
                                          
                                              mapping (address => uint)                       public  balanceOf;
                                              mapping (address => mapping (address => uint))  public  allowance;
                                          
                                              function() public payable {
                                                  deposit();
                                              }
                                              function deposit() public payable {
                                                  balanceOf[msg.sender] += msg.value;
                                                  Deposit(msg.sender, msg.value);
                                              }
                                              function withdraw(uint wad) public {
                                                  require(balanceOf[msg.sender] >= wad);
                                                  balanceOf[msg.sender] -= wad;
                                                  msg.sender.transfer(wad);
                                                  Withdrawal(msg.sender, wad);
                                              }
                                          
                                              function totalSupply() public view returns (uint) {
                                                  return this.balance;
                                              }
                                          
                                              function approve(address guy, uint wad) public returns (bool) {
                                                  allowance[msg.sender][guy] = wad;
                                                  Approval(msg.sender, guy, wad);
                                                  return true;
                                              }
                                          
                                              function transfer(address dst, uint wad) public returns (bool) {
                                                  return transferFrom(msg.sender, dst, wad);
                                              }
                                          
                                              function transferFrom(address src, address dst, uint wad)
                                                  public
                                                  returns (bool)
                                              {
                                                  require(balanceOf[src] >= wad);
                                          
                                                  if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                                                      require(allowance[src][msg.sender] >= wad);
                                                      allowance[src][msg.sender] -= wad;
                                                  }
                                          
                                                  balanceOf[src] -= wad;
                                                  balanceOf[dst] += wad;
                                          
                                                  Transfer(src, dst, wad);
                                          
                                                  return true;
                                              }
                                          }
                                          
                                          
                                          /*
                                                              GNU GENERAL PUBLIC LICENSE
                                                                 Version 3, 29 June 2007
                                          
                                           Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
                                           Everyone is permitted to copy and distribute verbatim copies
                                           of this license document, but changing it is not allowed.
                                          
                                                                      Preamble
                                          
                                            The GNU General Public License is a free, copyleft license for
                                          software and other kinds of works.
                                          
                                            The licenses for most software and other practical works are designed
                                          to take away your freedom to share and change the works.  By contrast,
                                          the GNU General Public License is intended to guarantee your freedom to
                                          share and change all versions of a program--to make sure it remains free
                                          software for all its users.  We, the Free Software Foundation, use the
                                          GNU General Public License for most of our software; it applies also to
                                          any other work released this way by its authors.  You can apply it to
                                          your programs, too.
                                          
                                            When we speak of free software, we are referring to freedom, not
                                          price.  Our General Public Licenses are designed to make sure that you
                                          have the freedom to distribute copies of free software (and charge for
                                          them if you wish), that you receive source code or can get it if you
                                          want it, that you can change the software or use pieces of it in new
                                          free programs, and that you know you can do these things.
                                          
                                            To protect your rights, we need to prevent others from denying you
                                          these rights or asking you to surrender the rights.  Therefore, you have
                                          certain responsibilities if you distribute copies of the software, or if
                                          you modify it: responsibilities to respect the freedom of others.
                                          
                                            For example, if you distribute copies of such a program, whether
                                          gratis or for a fee, you must pass on to the recipients the same
                                          freedoms that you received.  You must make sure that they, too, receive
                                          or can get the source code.  And you must show them these terms so they
                                          know their rights.
                                          
                                            Developers that use the GNU GPL protect your rights with two steps:
                                          (1) assert copyright on the software, and (2) offer you this License
                                          giving you legal permission to copy, distribute and/or modify it.
                                          
                                            For the developers' and authors' protection, the GPL clearly explains
                                          that there is no warranty for this free software.  For both users' and
                                          authors' sake, the GPL requires that modified versions be marked as
                                          changed, so that their problems will not be attributed erroneously to
                                          authors of previous versions.
                                          
                                            Some devices are designed to deny users access to install or run
                                          modified versions of the software inside them, although the manufacturer
                                          can do so.  This is fundamentally incompatible with the aim of
                                          protecting users' freedom to change the software.  The systematic
                                          pattern of such abuse occurs in the area of products for individuals to
                                          use, which is precisely where it is most unacceptable.  Therefore, we
                                          have designed this version of the GPL to prohibit the practice for those
                                          products.  If such problems arise substantially in other domains, we
                                          stand ready to extend this provision to those domains in future versions
                                          of the GPL, as needed to protect the freedom of users.
                                          
                                            Finally, every program is threatened constantly by software patents.
                                          States should not allow patents to restrict development and use of
                                          software on general-purpose computers, but in those that do, we wish to
                                          avoid the special danger that patents applied to a free program could
                                          make it effectively proprietary.  To prevent this, the GPL assures that
                                          patents cannot be used to render the program non-free.
                                          
                                            The precise terms and conditions for copying, distribution and
                                          modification follow.
                                          
                                                                 TERMS AND CONDITIONS
                                          
                                            0. Definitions.
                                          
                                            "This License" refers to version 3 of the GNU General Public License.
                                          
                                            "Copyright" also means copyright-like laws that apply to other kinds of
                                          works, such as semiconductor masks.
                                          
                                            "The Program" refers to any copyrightable work licensed under this
                                          License.  Each licensee is addressed as "you".  "Licensees" and
                                          "recipients" may be individuals or organizations.
                                          
                                            To "modify" a work means to copy from or adapt all or part of the work
                                          in a fashion requiring copyright permission, other than the making of an
                                          exact copy.  The resulting work is called a "modified version" of the
                                          earlier work or a work "based on" the earlier work.
                                          
                                            A "covered work" means either the unmodified Program or a work based
                                          on the Program.
                                          
                                            To "propagate" a work means to do anything with it that, without
                                          permission, would make you directly or secondarily liable for
                                          infringement under applicable copyright law, except executing it on a
                                          computer or modifying a private copy.  Propagation includes copying,
                                          distribution (with or without modification), making available to the
                                          public, and in some countries other activities as well.
                                          
                                            To "convey" a work means any kind of propagation that enables other
                                          parties to make or receive copies.  Mere interaction with a user through
                                          a computer network, with no transfer of a copy, is not conveying.
                                          
                                            An interactive user interface displays "Appropriate Legal Notices"
                                          to the extent that it includes a convenient and prominently visible
                                          feature that (1) displays an appropriate copyright notice, and (2)
                                          tells the user that there is no warranty for the work (except to the
                                          extent that warranties are provided), that licensees may convey the
                                          work under this License, and how to view a copy of this License.  If
                                          the interface presents a list of user commands or options, such as a
                                          menu, a prominent item in the list meets this criterion.
                                          
                                            1. Source Code.
                                          
                                            The "source code" for a work means the preferred form of the work
                                          for making modifications to it.  "Object code" means any non-source
                                          form of a work.
                                          
                                            A "Standard Interface" means an interface that either is an official
                                          standard defined by a recognized standards body, or, in the case of
                                          interfaces specified for a particular programming language, one that
                                          is widely used among developers working in that language.
                                          
                                            The "System Libraries" of an executable work include anything, other
                                          than the work as a whole, that (a) is included in the normal form of
                                          packaging a Major Component, but which is not part of that Major
                                          Component, and (b) serves only to enable use of the work with that
                                          Major Component, or to implement a Standard Interface for which an
                                          implementation is available to the public in source code form.  A
                                          "Major Component", in this context, means a major essential component
                                          (kernel, window system, and so on) of the specific operating system
                                          (if any) on which the executable work runs, or a compiler used to
                                          produce the work, or an object code interpreter used to run it.
                                          
                                            The "Corresponding Source" for a work in object code form means all
                                          the source code needed to generate, install, and (for an executable
                                          work) run the object code and to modify the work, including scripts to
                                          control those activities.  However, it does not include the work's
                                          System Libraries, or general-purpose tools or generally available free
                                          programs which are used unmodified in performing those activities but
                                          which are not part of the work.  For example, Corresponding Source
                                          includes interface definition files associated with source files for
                                          the work, and the source code for shared libraries and dynamically
                                          linked subprograms that the work is specifically designed to require,
                                          such as by intimate data communication or control flow between those
                                          subprograms and other parts of the work.
                                          
                                            The Corresponding Source need not include anything that users
                                          can regenerate automatically from other parts of the Corresponding
                                          Source.
                                          
                                            The Corresponding Source for a work in source code form is that
                                          same work.
                                          
                                            2. Basic Permissions.
                                          
                                            All rights granted under this License are granted for the term of
                                          copyright on the Program, and are irrevocable provided the stated
                                          conditions are met.  This License explicitly affirms your unlimited
                                          permission to run the unmodified Program.  The output from running a
                                          covered work is covered by this License only if the output, given its
                                          content, constitutes a covered work.  This License acknowledges your
                                          rights of fair use or other equivalent, as provided by copyright law.
                                          
                                            You may make, run and propagate covered works that you do not
                                          convey, without conditions so long as your license otherwise remains
                                          in force.  You may convey covered works to others for the sole purpose
                                          of having them make modifications exclusively for you, or provide you
                                          with facilities for running those works, provided that you comply with
                                          the terms of this License in conveying all material for which you do
                                          not control copyright.  Those thus making or running the covered works
                                          for you must do so exclusively on your behalf, under your direction
                                          and control, on terms that prohibit them from making any copies of
                                          your copyrighted material outside their relationship with you.
                                          
                                            Conveying under any other circumstances is permitted solely under
                                          the conditions stated below.  Sublicensing is not allowed; section 10
                                          makes it unnecessary.
                                          
                                            3. Protecting Users' Legal Rights From Anti-Circumvention Law.
                                          
                                            No covered work shall be deemed part of an effective technological
                                          measure under any applicable law fulfilling obligations under article
                                          11 of the WIPO copyright treaty adopted on 20 December 1996, or
                                          similar laws prohibiting or restricting circumvention of such
                                          measures.
                                          
                                            When you convey a covered work, you waive any legal power to forbid
                                          circumvention of technological measures to the extent such circumvention
                                          is effected by exercising rights under this License with respect to
                                          the covered work, and you disclaim any intention to limit operation or
                                          modification of the work as a means of enforcing, against the work's
                                          users, your or third parties' legal rights to forbid circumvention of
                                          technological measures.
                                          
                                            4. Conveying Verbatim Copies.
                                          
                                            You may convey verbatim copies of the Program's source code as you
                                          receive it, in any medium, provided that you conspicuously and
                                          appropriately publish on each copy an appropriate copyright notice;
                                          keep intact all notices stating that this License and any
                                          non-permissive terms added in accord with section 7 apply to the code;
                                          keep intact all notices of the absence of any warranty; and give all
                                          recipients a copy of this License along with the Program.
                                          
                                            You may charge any price or no price for each copy that you convey,
                                          and you may offer support or warranty protection for a fee.
                                          
                                            5. Conveying Modified Source Versions.
                                          
                                            You may convey a work based on the Program, or the modifications to
                                          produce it from the Program, in the form of source code under the
                                          terms of section 4, provided that you also meet all of these conditions:
                                          
                                              a) The work must carry prominent notices stating that you modified
                                              it, and giving a relevant date.
                                          
                                              b) The work must carry prominent notices stating that it is
                                              released under this License and any conditions added under section
                                              7.  This requirement modifies the requirement in section 4 to
                                              "keep intact all notices".
                                          
                                              c) You must license the entire work, as a whole, under this
                                              License to anyone who comes into possession of a copy.  This
                                              License will therefore apply, along with any applicable section 7
                                              additional terms, to the whole of the work, and all its parts,
                                              regardless of how they are packaged.  This License gives no
                                              permission to license the work in any other way, but it does not
                                              invalidate such permission if you have separately received it.
                                          
                                              d) If the work has interactive user interfaces, each must display
                                              Appropriate Legal Notices; however, if the Program has interactive
                                              interfaces that do not display Appropriate Legal Notices, your
                                              work need not make them do so.
                                          
                                            A compilation of a covered work with other separate and independent
                                          works, which are not by their nature extensions of the covered work,
                                          and which are not combined with it such as to form a larger program,
                                          in or on a volume of a storage or distribution medium, is called an
                                          "aggregate" if the compilation and its resulting copyright are not
                                          used to limit the access or legal rights of the compilation's users
                                          beyond what the individual works permit.  Inclusion of a covered work
                                          in an aggregate does not cause this License to apply to the other
                                          parts of the aggregate.
                                          
                                            6. Conveying Non-Source Forms.
                                          
                                            You may convey a covered work in object code form under the terms
                                          of sections 4 and 5, provided that you also convey the
                                          machine-readable Corresponding Source under the terms of this License,
                                          in one of these ways:
                                          
                                              a) Convey the object code in, or embodied in, a physical product
                                              (including a physical distribution medium), accompanied by the
                                              Corresponding Source fixed on a durable physical medium
                                              customarily used for software interchange.
                                          
                                              b) Convey the object code in, or embodied in, a physical product
                                              (including a physical distribution medium), accompanied by a
                                              written offer, valid for at least three years and valid for as
                                              long as you offer spare parts or customer support for that product
                                              model, to give anyone who possesses the object code either (1) a
                                              copy of the Corresponding Source for all the software in the
                                              product that is covered by this License, on a durable physical
                                              medium customarily used for software interchange, for a price no
                                              more than your reasonable cost of physically performing this
                                              conveying of source, or (2) access to copy the
                                              Corresponding Source from a network server at no charge.
                                          
                                              c) Convey individual copies of the object code with a copy of the
                                              written offer to provide the Corresponding Source.  This
                                              alternative is allowed only occasionally and noncommercially, and
                                              only if you received the object code with such an offer, in accord
                                              with subsection 6b.
                                          
                                              d) Convey the object code by offering access from a designated
                                              place (gratis or for a charge), and offer equivalent access to the
                                              Corresponding Source in the same way through the same place at no
                                              further charge.  You need not require recipients to copy the
                                              Corresponding Source along with the object code.  If the place to
                                              copy the object code is a network server, the Corresponding Source
                                              may be on a different server (operated by you or a third party)
                                              that supports equivalent copying facilities, provided you maintain
                                              clear directions next to the object code saying where to find the
                                              Corresponding Source.  Regardless of what server hosts the
                                              Corresponding Source, you remain obligated to ensure that it is
                                              available for as long as needed to satisfy these requirements.
                                          
                                              e) Convey the object code using peer-to-peer transmission, provided
                                              you inform other peers where the object code and Corresponding
                                              Source of the work are being offered to the general public at no
                                              charge under subsection 6d.
                                          
                                            A separable portion of the object code, whose source code is excluded
                                          from the Corresponding Source as a System Library, need not be
                                          included in conveying the object code work.
                                          
                                            A "User Product" is either (1) a "consumer product", which means any
                                          tangible personal property which is normally used for personal, family,
                                          or household purposes, or (2) anything designed or sold for incorporation
                                          into a dwelling.  In determining whether a product is a consumer product,
                                          doubtful cases shall be resolved in favor of coverage.  For a particular
                                          product received by a particular user, "normally used" refers to a
                                          typical or common use of that class of product, regardless of the status
                                          of the particular user or of the way in which the particular user
                                          actually uses, or expects or is expected to use, the product.  A product
                                          is a consumer product regardless of whether the product has substantial
                                          commercial, industrial or non-consumer uses, unless such uses represent
                                          the only significant mode of use of the product.
                                          
                                            "Installation Information" for a User Product means any methods,
                                          procedures, authorization keys, or other information required to install
                                          and execute modified versions of a covered work in that User Product from
                                          a modified version of its Corresponding Source.  The information must
                                          suffice to ensure that the continued functioning of the modified object
                                          code is in no case prevented or interfered with solely because
                                          modification has been made.
                                          
                                            If you convey an object code work under this section in, or with, or
                                          specifically for use in, a User Product, and the conveying occurs as
                                          part of a transaction in which the right of possession and use of the
                                          User Product is transferred to the recipient in perpetuity or for a
                                          fixed term (regardless of how the transaction is characterized), the
                                          Corresponding Source conveyed under this section must be accompanied
                                          by the Installation Information.  But this requirement does not apply
                                          if neither you nor any third party retains the ability to install
                                          modified object code on the User Product (for example, the work has
                                          been installed in ROM).
                                          
                                            The requirement to provide Installation Information does not include a
                                          requirement to continue to provide support service, warranty, or updates
                                          for a work that has been modified or installed by the recipient, or for
                                          the User Product in which it has been modified or installed.  Access to a
                                          network may be denied when the modification itself materially and
                                          adversely affects the operation of the network or violates the rules and
                                          protocols for communication across the network.
                                          
                                            Corresponding Source conveyed, and Installation Information provided,
                                          in accord with this section must be in a format that is publicly
                                          documented (and with an implementation available to the public in
                                          source code form), and must require no special password or key for
                                          unpacking, reading or copying.
                                          
                                            7. Additional Terms.
                                          
                                            "Additional permissions" are terms that supplement the terms of this
                                          License by making exceptions from one or more of its conditions.
                                          Additional permissions that are applicable to the entire Program shall
                                          be treated as though they were included in this License, to the extent
                                          that they are valid under applicable law.  If additional permissions
                                          apply only to part of the Program, that part may be used separately
                                          under those permissions, but the entire Program remains governed by
                                          this License without regard to the additional permissions.
                                          
                                            When you convey a copy of a covered work, you may at your option
                                          remove any additional permissions from that copy, or from any part of
                                          it.  (Additional permissions may be written to require their own
                                          removal in certain cases when you modify the work.)  You may place
                                          additional permissions on material, added by you to a covered work,
                                          for which you have or can give appropriate copyright permission.
                                          
                                            Notwithstanding any other provision of this License, for material you
                                          add to a covered work, you may (if authorized by the copyright holders of
                                          that material) supplement the terms of this License with terms:
                                          
                                              a) Disclaiming warranty or limiting liability differently from the
                                              terms of sections 15 and 16 of this License; or
                                          
                                              b) Requiring preservation of specified reasonable legal notices or
                                              author attributions in that material or in the Appropriate Legal
                                              Notices displayed by works containing it; or
                                          
                                              c) Prohibiting misrepresentation of the origin of that material, or
                                              requiring that modified versions of such material be marked in
                                              reasonable ways as different from the original version; or
                                          
                                              d) Limiting the use for publicity purposes of names of licensors or
                                              authors of the material; or
                                          
                                              e) Declining to grant rights under trademark law for use of some
                                              trade names, trademarks, or service marks; or
                                          
                                              f) Requiring indemnification of licensors and authors of that
                                              material by anyone who conveys the material (or modified versions of
                                              it) with contractual assumptions of liability to the recipient, for
                                              any liability that these contractual assumptions directly impose on
                                              those licensors and authors.
                                          
                                            All other non-permissive additional terms are considered "further
                                          restrictions" within the meaning of section 10.  If the Program as you
                                          received it, or any part of it, contains a notice stating that it is
                                          governed by this License along with a term that is a further
                                          restriction, you may remove that term.  If a license document contains
                                          a further restriction but permits relicensing or conveying under this
                                          License, you may add to a covered work material governed by the terms
                                          of that license document, provided that the further restriction does
                                          not survive such relicensing or conveying.
                                          
                                            If you add terms to a covered work in accord with this section, you
                                          must place, in the relevant source files, a statement of the
                                          additional terms that apply to those files, or a notice indicating
                                          where to find the applicable terms.
                                          
                                            Additional terms, permissive or non-permissive, may be stated in the
                                          form of a separately written license, or stated as exceptions;
                                          the above requirements apply either way.
                                          
                                            8. Termination.
                                          
                                            You may not propagate or modify a covered work except as expressly
                                          provided under this License.  Any attempt otherwise to propagate or
                                          modify it is void, and will automatically terminate your rights under
                                          this License (including any patent licenses granted under the third
                                          paragraph of section 11).
                                          
                                            However, if you cease all violation of this License, then your
                                          license from a particular copyright holder is reinstated (a)
                                          provisionally, unless and until the copyright holder explicitly and
                                          finally terminates your license, and (b) permanently, if the copyright
                                          holder fails to notify you of the violation by some reasonable means
                                          prior to 60 days after the cessation.
                                          
                                            Moreover, your license from a particular copyright holder is
                                          reinstated permanently if the copyright holder notifies you of the
                                          violation by some reasonable means, this is the first time you have
                                          received notice of violation of this License (for any work) from that
                                          copyright holder, and you cure the violation prior to 30 days after
                                          your receipt of the notice.
                                          
                                            Termination of your rights under this section does not terminate the
                                          licenses of parties who have received copies or rights from you under
                                          this License.  If your rights have been terminated and not permanently
                                          reinstated, you do not qualify to receive new licenses for the same
                                          material under section 10.
                                          
                                            9. Acceptance Not Required for Having Copies.
                                          
                                            You are not required to accept this License in order to receive or
                                          run a copy of the Program.  Ancillary propagation of a covered work
                                          occurring solely as a consequence of using peer-to-peer transmission
                                          to receive a copy likewise does not require acceptance.  However,
                                          nothing other than this License grants you permission to propagate or
                                          modify any covered work.  These actions infringe copyright if you do
                                          not accept this License.  Therefore, by modifying or propagating a
                                          covered work, you indicate your acceptance of this License to do so.
                                          
                                            10. Automatic Licensing of Downstream Recipients.
                                          
                                            Each time you convey a covered work, the recipient automatically
                                          receives a license from the original licensors, to run, modify and
                                          propagate that work, subject to this License.  You are not responsible
                                          for enforcing compliance by third parties with this License.
                                          
                                            An "entity transaction" is a transaction transferring control of an
                                          organization, or substantially all assets of one, or subdividing an
                                          organization, or merging organizations.  If propagation of a covered
                                          work results from an entity transaction, each party to that
                                          transaction who receives a copy of the work also receives whatever
                                          licenses to the work the party's predecessor in interest had or could
                                          give under the previous paragraph, plus a right to possession of the
                                          Corresponding Source of the work from the predecessor in interest, if
                                          the predecessor has it or can get it with reasonable efforts.
                                          
                                            You may not impose any further restrictions on the exercise of the
                                          rights granted or affirmed under this License.  For example, you may
                                          not impose a license fee, royalty, or other charge for exercise of
                                          rights granted under this License, and you may not initiate litigation
                                          (including a cross-claim or counterclaim in a lawsuit) alleging that
                                          any patent claim is infringed by making, using, selling, offering for
                                          sale, or importing the Program or any portion of it.
                                          
                                            11. Patents.
                                          
                                            A "contributor" is a copyright holder who authorizes use under this
                                          License of the Program or a work on which the Program is based.  The
                                          work thus licensed is called the contributor's "contributor version".
                                          
                                            A contributor's "essential patent claims" are all patent claims
                                          owned or controlled by the contributor, whether already acquired or
                                          hereafter acquired, that would be infringed by some manner, permitted
                                          by this License, of making, using, or selling its contributor version,
                                          but do not include claims that would be infringed only as a
                                          consequence of further modification of the contributor version.  For
                                          purposes of this definition, "control" includes the right to grant
                                          patent sublicenses in a manner consistent with the requirements of
                                          this License.
                                          
                                            Each contributor grants you a non-exclusive, worldwide, royalty-free
                                          patent license under the contributor's essential patent claims, to
                                          make, use, sell, offer for sale, import and otherwise run, modify and
                                          propagate the contents of its contributor version.
                                          
                                            In the following three paragraphs, a "patent license" is any express
                                          agreement or commitment, however denominated, not to enforce a patent
                                          (such as an express permission to practice a patent or covenant not to
                                          sue for patent infringement).  To "grant" such a patent license to a
                                          party means to make such an agreement or commitment not to enforce a
                                          patent against the party.
                                          
                                            If you convey a covered work, knowingly relying on a patent license,
                                          and the Corresponding Source of the work is not available for anyone
                                          to copy, free of charge and under the terms of this License, through a
                                          publicly available network server or other readily accessible means,
                                          then you must either (1) cause the Corresponding Source to be so
                                          available, or (2) arrange to deprive yourself of the benefit of the
                                          patent license for this particular work, or (3) arrange, in a manner
                                          consistent with the requirements of this License, to extend the patent
                                          license to downstream recipients.  "Knowingly relying" means you have
                                          actual knowledge that, but for the patent license, your conveying the
                                          covered work in a country, or your recipient's use of the covered work
                                          in a country, would infringe one or more identifiable patents in that
                                          country that you have reason to believe are valid.
                                          
                                            If, pursuant to or in connection with a single transaction or
                                          arrangement, you convey, or propagate by procuring conveyance of, a
                                          covered work, and grant a patent license to some of the parties
                                          receiving the covered work authorizing them to use, propagate, modify
                                          or convey a specific copy of the covered work, then the patent license
                                          you grant is automatically extended to all recipients of the covered
                                          work and works based on it.
                                          
                                            A patent license is "discriminatory" if it does not include within
                                          the scope of its coverage, prohibits the exercise of, or is
                                          conditioned on the non-exercise of one or more of the rights that are
                                          specifically granted under this License.  You may not convey a covered
                                          work if you are a party to an arrangement with a third party that is
                                          in the business of distributing software, under which you make payment
                                          to the third party based on the extent of your activity of conveying
                                          the work, and under which the third party grants, to any of the
                                          parties who would receive the covered work from you, a discriminatory
                                          patent license (a) in connection with copies of the covered work
                                          conveyed by you (or copies made from those copies), or (b) primarily
                                          for and in connection with specific products or compilations that
                                          contain the covered work, unless you entered into that arrangement,
                                          or that patent license was granted, prior to 28 March 2007.
                                          
                                            Nothing in this License shall be construed as excluding or limiting
                                          any implied license or other defenses to infringement that may
                                          otherwise be available to you under applicable patent law.
                                          
                                            12. No Surrender of Others' Freedom.
                                          
                                            If conditions are imposed on you (whether by court order, agreement or
                                          otherwise) that contradict the conditions of this License, they do not
                                          excuse you from the conditions of this License.  If you cannot convey a
                                          covered work so as to satisfy simultaneously your obligations under this
                                          License and any other pertinent obligations, then as a consequence you may
                                          not convey it at all.  For example, if you agree to terms that obligate you
                                          to collect a royalty for further conveying from those to whom you convey
                                          the Program, the only way you could satisfy both those terms and this
                                          License would be to refrain entirely from conveying the Program.
                                          
                                            13. Use with the GNU Affero General Public License.
                                          
                                            Notwithstanding any other provision of this License, you have
                                          permission to link or combine any covered work with a work licensed
                                          under version 3 of the GNU Affero General Public License into a single
                                          combined work, and to convey the resulting work.  The terms of this
                                          License will continue to apply to the part which is the covered work,
                                          but the special requirements of the GNU Affero General Public License,
                                          section 13, concerning interaction through a network will apply to the
                                          combination as such.
                                          
                                            14. Revised Versions of this License.
                                          
                                            The Free Software Foundation may publish revised and/or new versions of
                                          the GNU General Public License from time to time.  Such new versions will
                                          be similar in spirit to the present version, but may differ in detail to
                                          address new problems or concerns.
                                          
                                            Each version is given a distinguishing version number.  If the
                                          Program specifies that a certain numbered version of the GNU General
                                          Public License "or any later version" applies to it, you have the
                                          option of following the terms and conditions either of that numbered
                                          version or of any later version published by the Free Software
                                          Foundation.  If the Program does not specify a version number of the
                                          GNU General Public License, you may choose any version ever published
                                          by the Free Software Foundation.
                                          
                                            If the Program specifies that a proxy can decide which future
                                          versions of the GNU General Public License can be used, that proxy's
                                          public statement of acceptance of a version permanently authorizes you
                                          to choose that version for the Program.
                                          
                                            Later license versions may give you additional or different
                                          permissions.  However, no additional obligations are imposed on any
                                          author or copyright holder as a result of your choosing to follow a
                                          later version.
                                          
                                            15. Disclaimer of Warranty.
                                          
                                            THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
                                          APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
                                          HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
                                          OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
                                          THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                                          PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
                                          IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
                                          ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
                                          
                                            16. Limitation of Liability.
                                          
                                            IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                                          WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
                                          THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
                                          GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
                                          USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
                                          DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
                                          PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
                                          EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
                                          SUCH DAMAGES.
                                          
                                            17. Interpretation of Sections 15 and 16.
                                          
                                            If the disclaimer of warranty and limitation of liability provided
                                          above cannot be given local legal effect according to their terms,
                                          reviewing courts shall apply local law that most closely approximates
                                          an absolute waiver of all civil liability in connection with the
                                          Program, unless a warranty or assumption of liability accompanies a
                                          copy of the Program in return for a fee.
                                          
                                                               END OF TERMS AND CONDITIONS
                                          
                                                      How to Apply These Terms to Your New Programs
                                          
                                            If you develop a new program, and you want it to be of the greatest
                                          possible use to the public, the best way to achieve this is to make it
                                          free software which everyone can redistribute and change under these terms.
                                          
                                            To do so, attach the following notices to the program.  It is safest
                                          to attach them to the start of each source file to most effectively
                                          state the exclusion of warranty; and each file should have at least
                                          the "copyright" line and a pointer to where the full notice is found.
                                          
                                              <one line to give the program's name and a brief idea of what it does.>
                                              Copyright (C) <year>  <name of author>
                                          
                                              This program is free software: you can redistribute it and/or modify
                                              it under the terms of the GNU General Public License as published by
                                              the Free Software Foundation, either version 3 of the License, or
                                              (at your option) any later version.
                                          
                                              This program is distributed in the hope that it will be useful,
                                              but WITHOUT ANY WARRANTY; without even the implied warranty of
                                              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                                              GNU General Public License for more details.
                                          
                                              You should have received a copy of the GNU General Public License
                                              along with this program.  If not, see <http://www.gnu.org/licenses/>.
                                          
                                          Also add information on how to contact you by electronic and paper mail.
                                          
                                            If the program does terminal interaction, make it output a short
                                          notice like this when it starts in an interactive mode:
                                          
                                              <program>  Copyright (C) <year>  <name of author>
                                              This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
                                              This is free software, and you are welcome to redistribute it
                                              under certain conditions; type `show c' for details.
                                          
                                          The hypothetical commands `show w' and `show c' should show the appropriate
                                          parts of the General Public License.  Of course, your program's commands
                                          might be different; for a GUI interface, you would use an "about box".
                                          
                                            You should also get your employer (if you work as a programmer) or school,
                                          if any, to sign a "copyright disclaimer" for the program, if necessary.
                                          For more information on this, and how to apply and follow the GNU GPL, see
                                          <http://www.gnu.org/licenses/>.
                                          
                                            The GNU General Public License does not permit incorporating your program
                                          into proprietary programs.  If your program is a subroutine library, you
                                          may consider it more useful to permit linking proprietary applications with
                                          the library.  If this is what you want to do, use the GNU Lesser General
                                          Public License instead of this License.  But first, please read
                                          <http://www.gnu.org/philosophy/why-not-lgpl.html>.
                                          
                                          */

                                          File 3 of 15: OneSplit
                                          // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see {ERC20Detailed}.
                                           */
                                          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: contracts/IOneSplit.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          //
                                          //  [ msg.sender ]
                                          //       | |
                                          //       | |
                                          //       \_/
                                          // +---------------+ ________________________________
                                          // | OneSplitAudit | _______________________________  \
                                          // +---------------+                                 \ \
                                          //       | |                      ______________      | | (staticcall)
                                          //       | |                    /  ____________  \    | |
                                          //       | | (call)            / /              \ \   | |
                                          //       | |                  / /               | |   | |
                                          //       \_/                  | |               \_/   \_/
                                          // +--------------+           | |           +----------------------+
                                          // | OneSplitWrap |           | |           |   OneSplitViewWrap   |
                                          // +--------------+           | |           +----------------------+
                                          //       | |                  | |                     | |
                                          //       | | (delegatecall)   | | (staticcall)        | | (staticcall)
                                          //       \_/                  | |                     \_/
                                          // +--------------+           | |             +------------------+
                                          // |   OneSplit   |           | |             |   OneSplitView   |
                                          // +--------------+           | |             +------------------+
                                          //       | |                  / /
                                          //        \ \________________/ /
                                          //         \__________________/
                                          //
                                          
                                          
                                          contract IOneSplitConsts {
                                              // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
                                              uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
                                              uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
                                              uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
                                              uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
                                              uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
                                              uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
                                              uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
                                              uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
                                              uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
                                              uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
                                              uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
                                              uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
                                              uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
                                              uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
                                              uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
                                              uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
                                              uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
                                              uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
                                              uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
                                              uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
                                              uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
                                              uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
                                          }
                                          
                                          
                                          contract IOneSplit is IOneSplitConsts {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              )
                                                  public
                                                  payable
                                                  returns(uint256 returnAmount);
                                          }
                                          
                                          
                                          contract IOneSplitMulti is IOneSplit {
                                              function getExpectedReturnWithGasMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256[] memory parts,
                                                  uint256[] memory flags,
                                                  uint256[] memory destTokenEthPriceTimesGasPrices
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256[] memory returnAmounts,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function swapMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256[] memory flags
                                              )
                                                  public
                                                  payable
                                                  returns(uint256 returnAmount);
                                          }
                                          
                                          // File: @openzeppelin/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.5.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, 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) {
                                                  return sub(a, b, "SafeMath: subtraction overflow");
                                              }
                                          
                                              /**
                                               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                               * overflow (when the result is negative).
                                               *
                                               * Counterpart to Solidity's `-` operator.
                                               *
                                               * Requirements:
                                               * - Subtraction cannot overflow.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b <= a, errorMessage);
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  return div(a, b, "SafeMath: division by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, errorMessage);
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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) {
                                                  return mod(a, b, "SafeMath: modulo by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b != 0, errorMessage);
                                                  return a % b;
                                              }
                                          }
                                          
                                          // File: contracts/interface/IUniswapExchange.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IUniswapExchange {
                                              function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought);
                                          
                                              function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought);
                                          
                                              function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
                                                  external
                                                  payable
                                                  returns (uint256 tokensBought);
                                          
                                              function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
                                                  external
                                                  returns (uint256 ethBought);
                                          
                                              function tokenToTokenSwapInput(
                                                  uint256 tokensSold,
                                                  uint256 minTokensBought,
                                                  uint256 minEthBought,
                                                  uint256 deadline,
                                                  address tokenAddr
                                              ) external returns (uint256 tokensBought);
                                          }
                                          
                                          // File: contracts/interface/IUniswapFactory.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IUniswapFactory {
                                              function getExchange(IERC20 token) external view returns (IUniswapExchange exchange);
                                          }
                                          
                                          // File: contracts/interface/IKyberNetworkContract.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberNetworkContract {
                                              function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless)
                                                  external
                                                  view
                                                  returns (address reserve, uint256 rate);
                                          }
                                          
                                          // File: contracts/interface/IKyberNetworkProxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberNetworkProxy {
                                              function getExpectedRateAfterFee(
                                                  IERC20 src,
                                                  IERC20 dest,
                                                  uint256 srcQty,
                                                  uint256 platformFeeBps,
                                                  bytes calldata hint
                                              ) external view returns (uint256 expectedRate);
                                          
                                              function tradeWithHintAndFee(
                                                  IERC20 src,
                                                  uint256 srcAmount,
                                                  IERC20 dest,
                                                  address payable destAddress,
                                                  uint256 maxDestAmount,
                                                  uint256 minConversionRate,
                                                  address payable platformWallet,
                                                  uint256 platformFeeBps,
                                                  bytes calldata hint
                                              ) external payable returns (uint256 destAmount);
                                          
                                              function kyberNetworkContract() external view returns (IKyberNetworkContract);
                                          
                                              // TODO: Limit usage by tx.gasPrice
                                              // function maxGasPrice() external view returns (uint256);
                                          
                                              // TODO: Limit usage by user cap
                                              // function getUserCapInWei(address user) external view returns (uint256);
                                              // function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/IKyberStorage.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberStorage {
                                              function getReserveIdsPerTokenSrc(
                                                  IERC20 token
                                              ) external view returns (bytes32[] memory);
                                          }
                                          
                                          // File: contracts/interface/IKyberHintHandler.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberHintHandler {
                                              enum TradeType {
                                                  BestOfAll,
                                                  MaskIn,
                                                  MaskOut,
                                                  Split
                                              }
                                          
                                              function buildTokenToEthHint(
                                                  IERC20 tokenSrc,
                                                  TradeType tokenToEthType,
                                                  bytes32[] calldata tokenToEthReserveIds,
                                                  uint256[] calldata tokenToEthSplits
                                              ) external view returns (bytes memory hint);
                                          
                                              function buildEthToTokenHint(
                                                  IERC20 tokenDest,
                                                  TradeType ethToTokenType,
                                                  bytes32[] calldata ethToTokenReserveIds,
                                                  uint256[] calldata ethToTokenSplits
                                              ) external view returns (bytes memory hint);
                                          }
                                          
                                          // File: contracts/interface/IBancorNetwork.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IBancorNetwork {
                                              function getReturnByPath(address[] calldata path, uint256 amount)
                                                  external
                                                  view
                                                  returns (uint256 returnAmount, uint256 conversionFee);
                                          
                                              function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn)
                                                  external
                                                  returns (uint256);
                                          
                                              function convert(address[] calldata path, uint256 amount, uint256 minReturn)
                                                  external
                                                  payable
                                                  returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/IBancorContractRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          contract IBancorContractRegistry {
                                              function addressOf(bytes32 contractName) external view returns (address);
                                          }
                                          
                                          // File: contracts/interface/IBancorNetworkPathFinder.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBancorNetworkPathFinder {
                                              function generatePath(IERC20 sourceToken, IERC20 targetToken)
                                                  external
                                                  view
                                                  returns (address[] memory);
                                          }
                                          
                                          // File: contracts/interface/IBancorConverterRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBancorConverterRegistry {
                                          
                                              function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken)
                                                  external view returns(uint256);
                                          
                                              function getConvertibleTokenSmartTokens(IERC20 convertibleToken)
                                                  external view returns(address[] memory);
                                          
                                              function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index)
                                                  external view returns(address);
                                          
                                              function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value)
                                                  external view returns(bool);
                                          }
                                          
                                          // File: contracts/interface/IBancorEtherToken.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IBancorEtherToken is IERC20 {
                                              function deposit() external payable;
                                          
                                              function withdraw(uint256 amount) external;
                                          }
                                          
                                          // File: contracts/interface/IBancorFinder.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBancorFinder {
                                              function buildBancorPath(
                                                  IERC20 fromToken,
                                                  IERC20 destToken
                                              )
                                                  external
                                                  view
                                                  returns(address[] memory path);
                                          }
                                          
                                          // File: contracts/interface/IOasisExchange.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IOasisExchange {
                                              function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt)
                                                  external
                                                  view
                                                  returns (uint256 fillAmt);
                                          
                                              function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount)
                                                  external
                                                  returns (uint256 fillAmt);
                                          }
                                          
                                          // File: contracts/interface/IWETH.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IWETH is IERC20 {
                                              function deposit() external payable;
                                          
                                              function withdraw(uint256 amount) external;
                                          }
                                          
                                          // File: contracts/interface/ICurve.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface ICurve {
                                              // solium-disable-next-line mixedcase
                                              function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
                                          
                                              // solium-disable-next-line mixedcase
                                              function get_dy(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
                                          
                                              // solium-disable-next-line mixedcase
                                              function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external;
                                          
                                              // solium-disable-next-line mixedcase
                                              function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external;
                                          }
                                          
                                          
                                          contract ICurveRegistry {
                                              function get_pool_info(address pool)
                                                  external
                                                  view
                                                  returns(
                                                      uint256[8] memory balances,
                                                      uint256[8] memory underlying_balances,
                                                      uint256[8] memory decimals,
                                                      uint256[8] memory underlying_decimals,
                                                      address lp_token,
                                                      uint256 A,
                                                      uint256 fee
                                                  );
                                          }
                                          
                                          
                                          contract ICurveCalculator {
                                              function get_dy(
                                                  int128 nCoins,
                                                  uint256[8] calldata balances,
                                                  uint256 amp,
                                                  uint256 fee,
                                                  uint256[8] calldata rates,
                                                  uint256[8] calldata precisions,
                                                  bool underlying,
                                                  int128 i,
                                                  int128 j,
                                                  uint256[100] calldata dx
                                              ) external view returns(uint256[100] memory dy);
                                          }
                                          
                                          // File: contracts/interface/IChai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IPot {
                                              function dsr() external view returns (uint256);
                                          
                                              function chi() external view returns (uint256);
                                          
                                              function rho() external view returns (uint256);
                                          
                                              function drip() external returns (uint256);
                                          
                                              function join(uint256) external;
                                          
                                              function exit(uint256) external;
                                          }
                                          
                                          
                                          contract IChai is IERC20 {
                                              function POT() public view returns (IPot);
                                          
                                              function join(address dst, uint256 wad) external;
                                          
                                              function exit(address src, uint256 wad) external;
                                          }
                                          
                                          
                                          library ChaiHelper {
                                              IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
                                              uint256 private constant RAY = 10**27;
                                          
                                              function _mul(uint256 x, uint256 y) private pure returns (uint256 z) {
                                                  require(y == 0 || (z = x * y) / y == x);
                                              }
                                          
                                              function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) {
                                                  // always rounds down
                                                  z = _mul(x, y) / RAY;
                                              }
                                          
                                              function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) {
                                                  // always rounds down
                                                  z = _mul(x, RAY) / y;
                                              }
                                          
                                              function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) {
                                                  // solium-disable-next-line security/no-inline-assembly
                                                  assembly {
                                                      switch x
                                                          case 0 {
                                                              switch n
                                                                  case 0 {
                                                                      z := base
                                                                  }
                                                                  default {
                                                                      z := 0
                                                                  }
                                                          }
                                                          default {
                                                              switch mod(n, 2)
                                                                  case 0 {
                                                                      z := base
                                                                  }
                                                                  default {
                                                                      z := x
                                                                  }
                                                              let half := div(base, 2) // for rounding.
                                                              for {
                                                                  n := div(n, 2)
                                                              } n {
                                                                  n := div(n, 2)
                                                              } {
                                                                  let xx := mul(x, x)
                                                                  if iszero(eq(div(xx, x), x)) {
                                                                      revert(0, 0)
                                                                  }
                                                                  let xxRound := add(xx, half)
                                                                  if lt(xxRound, xx) {
                                                                      revert(0, 0)
                                                                  }
                                                                  x := div(xxRound, base)
                                                                  if mod(n, 2) {
                                                                      let zx := mul(z, x)
                                                                      if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
                                                                          revert(0, 0)
                                                                      }
                                                                      let zxRound := add(zx, half)
                                                                      if lt(zxRound, zx) {
                                                                          revert(0, 0)
                                                                      }
                                                                      z := div(zxRound, base)
                                                                  }
                                                              }
                                                          }
                                                  }
                                              }
                                          
                                              function potDrip() private view returns (uint256) {
                                                  return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi());
                                              }
                                          
                                              function chaiPrice(IChai chai) internal view returns(uint256) {
                                                  return chaiToDai(chai, 1e18);
                                              }
                                          
                                              function daiToChai(
                                                  IChai /*chai*/,
                                                  uint256 amount
                                              ) internal view returns (uint256) {
                                                  uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
                                                  return _rdiv(amount, chi);
                                              }
                                          
                                              function chaiToDai(
                                                  IChai /*chai*/,
                                                  uint256 amount
                                              ) internal view returns (uint256) {
                                                  uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
                                                  return _rmul(chi, amount);
                                              }
                                          }
                                          
                                          // File: contracts/interface/ICompound.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract ICompound {
                                              function markets(address cToken)
                                                  external
                                                  view
                                                  returns (bool isListed, uint256 collateralFactorMantissa);
                                          }
                                          
                                          
                                          contract ICompoundToken is IERC20 {
                                              function underlying() external view returns (address);
                                          
                                              function exchangeRateStored() external view returns (uint256);
                                          
                                              function mint(uint256 mintAmount) external returns (uint256);
                                          
                                              function redeem(uint256 redeemTokens) external returns (uint256);
                                          }
                                          
                                          
                                          contract ICompoundEther is IERC20 {
                                              function mint() external payable;
                                          
                                              function redeem(uint256 redeemTokens) external returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/ICompoundRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract ICompoundRegistry {
                                              function tokenByCToken(ICompoundToken cToken) external view returns(IERC20);
                                              function cTokenByToken(IERC20 token) external view returns(ICompoundToken);
                                          }
                                          
                                          // File: contracts/interface/IAaveToken.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IAaveToken is IERC20 {
                                              function underlyingAssetAddress() external view returns (IERC20);
                                          
                                              function redeem(uint256 amount) external;
                                          }
                                          
                                          
                                          interface IAaveLendingPool {
                                              function core() external view returns (address);
                                          
                                              function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
                                          }
                                          
                                          // File: contracts/interface/IAaveRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract IAaveRegistry {
                                              function tokenByAToken(IAaveToken aToken) external view returns(IERC20);
                                              function aTokenByToken(IERC20 token) external view returns(IAaveToken);
                                          }
                                          
                                          // File: contracts/interface/IMooniswap.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IMooniswapRegistry {
                                              function target() external view returns(IMooniswap);
                                          }
                                          
                                          
                                          interface IMooniswap {
                                              function getReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount
                                              )
                                                  external
                                                  view
                                                  returns(uint256 returnAmount);
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn
                                              )
                                                  external
                                                  payable
                                                  returns(uint256 returnAmount);
                                          }
                                          
                                          // File: @openzeppelin/contracts/utils/Address.sol
                                          
                                          pragma solidity ^0.5.5;
                                          
                                          /**
                                           * @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) {
                                                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                                  // for accounts without code, i.e. `keccak256('')`
                                                  bytes32 codehash;
                                                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                                  // solhint-disable-next-line no-inline-assembly
                                                  assembly { codehash := extcodehash(account) }
                                                  return (codehash != accountHash && codehash != 0x0);
                                              }
                                          
                                              /**
                                               * @dev Converts an `address` into `address payable`. Note that this is
                                               * simply a type cast: the actual underlying value is not changed.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function toPayable(address account) internal pure returns (address payable) {
                                                  return address(uint160(account));
                                              }
                                          
                                              /**
                                               * @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].
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sendValue(address payable recipient, uint256 amount) internal {
                                                  require(address(this).balance >= amount, "Address: insufficient balance");
                                          
                                                  // solhint-disable-next-line avoid-call-value
                                                  (bool success, ) = recipient.call.value(amount)("");
                                                  require(success, "Address: unable to send value, recipient may have reverted");
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                                          
                                          pragma solidity ^0.5.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 ERC20;` 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));
                                              }
                                          
                                              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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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: contracts/UniversalERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          library UniversalERC20 {
                                          
                                              using SafeMath for uint256;
                                              using SafeERC20 for IERC20;
                                          
                                              IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
                                              IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
                                                  if (amount == 0) {
                                                      return true;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      address(uint160(to)).transfer(amount);
                                                  } else {
                                                      token.safeTransfer(to, amount);
                                                      return true;
                                                  }
                                              }
                                          
                                              function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
                                                      if (to != address(this)) {
                                                          address(uint160(to)).transfer(amount);
                                                      }
                                                      if (msg.value > amount) {
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(from, to, amount);
                                                  }
                                              }
                                          
                                              function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      if (msg.value > amount) {
                                                          // Return remainder if exist
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(msg.sender, address(this), amount);
                                                  }
                                              }
                                          
                                              function universalApprove(IERC20 token, address to, uint256 amount) internal {
                                                  if (!isETH(token)) {
                                                      if (amount == 0) {
                                                          token.safeApprove(to, 0);
                                                          return;
                                                      }
                                          
                                                      uint256 allowance = token.allowance(address(this), to);
                                                      if (allowance < amount) {
                                                          if (allowance > 0) {
                                                              token.safeApprove(to, 0);
                                                          }
                                                          token.safeApprove(to, amount);
                                                      }
                                                  }
                                              }
                                          
                                              function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
                                                  if (isETH(token)) {
                                                      return who.balance;
                                                  } else {
                                                      return token.balanceOf(who);
                                                  }
                                              }
                                          
                                              function universalDecimals(IERC20 token) internal view returns (uint256) {
                                          
                                                  if (isETH(token)) {
                                                      return 18;
                                                  }
                                          
                                                  (bool success, bytes memory data) = address(token).staticcall.gas(10000)(
                                                      abi.encodeWithSignature("decimals()")
                                                  );
                                                  if (!success || data.length == 0) {
                                                      (success, data) = address(token).staticcall.gas(10000)(
                                                          abi.encodeWithSignature("DECIMALS()")
                                                      );
                                                  }
                                          
                                                  return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
                                              }
                                          
                                              function isETH(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
                                              }
                                          
                                              function notExist(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(-1));
                                              }
                                          }
                                          
                                          // File: contracts/interface/IUniswapV2Exchange.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          interface IUniswapV2Exchange {
                                              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                          }
                                          
                                          
                                          library UniswapV2ExchangeLib {
                                              using SafeMath for uint256;
                                              using UniversalERC20 for IERC20;
                                          
                                              function getReturn(
                                                  IUniswapV2Exchange exchange,
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint amountIn
                                              ) internal view returns (uint256) {
                                                  uint256 reserveIn = fromToken.universalBalanceOf(address(exchange));
                                                  uint256 reserveOut = destToken.universalBalanceOf(address(exchange));
                                          
                                                  uint256 amountInWithFee = amountIn.mul(997);
                                                  uint256 numerator = amountInWithFee.mul(reserveOut);
                                                  uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
                                                  return (denominator == 0) ? 0 : numerator.div(denominator);
                                              }
                                          }
                                          
                                          // File: contracts/interface/IUniswapV2Factory.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IUniswapV2Factory {
                                              function getPair(IERC20 tokenA, IERC20 tokenB) external view returns (IUniswapV2Exchange pair);
                                          }
                                          
                                          // File: contracts/interface/IDForceSwap.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IDForceSwap {
                                              function getAmountByInput(IERC20 input, IERC20 output, uint256 amount) external view returns(uint256);
                                              function swap(IERC20 input, IERC20 output, uint256 amount) external;
                                          }
                                          
                                          // File: contracts/interface/IShell.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IShell {
                                              function viewOriginTrade(
                                                  address origin,
                                                  address target,
                                                  uint256 originAmount
                                              ) external view returns (uint256);
                                          
                                              function swapByOrigin(
                                                  address origin,
                                                  address target,
                                                  uint256 originAmount,
                                                  uint256 minTargetAmount,
                                                  uint256 deadline
                                              ) external returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/IMStable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IMStable is IERC20 {
                                              function getSwapOutput(
                                                  IERC20 _input,
                                                  IERC20 _output,
                                                  uint256 _quantity
                                              )
                                                  external
                                                  view
                                                  returns (bool, string memory, uint256 output);
                                          
                                              function swap(
                                                  IERC20 _input,
                                                  IERC20 _output,
                                                  uint256 _quantity,
                                                  address _recipient
                                              )
                                                  external
                                                  returns (uint256 output);
                                          
                                              function redeem(
                                                  IERC20 _basset,
                                                  uint256 _bassetQuantity
                                              )
                                                  external
                                                  returns (uint256 massetRedeemed);
                                          }
                                          
                                          interface IMassetRedemptionValidator {
                                              function getRedeemValidity(
                                                  IERC20 _mAsset,
                                                  uint256 _mAssetQuantity,
                                                  IERC20 _outputBasset
                                              )
                                                  external
                                                  view
                                                  returns (bool, string memory, uint256 output);
                                          }
                                          
                                          // File: contracts/interface/IBalancerRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBalancerPool {
                                              function swapExactAmountIn(
                                                  IERC20 tokenIn,
                                                  uint256 tokenAmountIn,
                                                  IERC20 tokenOut,
                                                  uint256 minAmountOut,
                                                  uint256 maxPrice
                                              )
                                                  external
                                                  returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
                                          }
                                          
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IBalancerRegistry {
                                              event PoolAdded(
                                                  address indexed pool
                                              );
                                              event PoolTokenPairAdded(
                                                  address indexed pool,
                                                  address indexed fromToken,
                                                  address indexed destToken
                                              );
                                              event IndicesUpdated(
                                                  address indexed fromToken,
                                                  address indexed destToken,
                                                  bytes32 oldIndices,
                                                  bytes32 newIndices
                                              );
                                          
                                              // Get info about pool pair for 1 SLOAD
                                              function getPairInfo(address pool, address fromToken, address destToken)
                                                  external view returns(uint256 weight1, uint256 weight2, uint256 swapFee);
                                          
                                              // Pools
                                              function checkAddedPools(address pool)
                                                  external view returns(bool);
                                              function getAddedPoolsLength()
                                                  external view returns(uint256);
                                              function getAddedPools()
                                                  external view returns(address[] memory);
                                              function getAddedPoolsWithLimit(uint256 offset, uint256 limit)
                                                  external view returns(address[] memory result);
                                          
                                              // Tokens
                                              function getAllTokensLength()
                                                  external view returns(uint256);
                                              function getAllTokens()
                                                  external view returns(address[] memory);
                                              function getAllTokensWithLimit(uint256 offset, uint256 limit)
                                                  external view returns(address[] memory result);
                                          
                                              // Pairs
                                              function getPoolsLength(address fromToken, address destToken)
                                                  external view returns(uint256);
                                              function getPools(address fromToken, address destToken)
                                                  external view returns(address[] memory);
                                              function getPoolsWithLimit(address fromToken, address destToken, uint256 offset, uint256 limit)
                                                  external view returns(address[] memory result);
                                              function getBestPools(address fromToken, address destToken)
                                                  external view returns(address[] memory pools);
                                              function getBestPoolsWithLimit(address fromToken, address destToken, uint256 limit)
                                                  external view returns(address[] memory pools);
                                          
                                              // Get swap rates
                                              function getPoolReturn(address pool, address fromToken, address destToken, uint256 amount)
                                                  external view returns(uint256);
                                              function getPoolReturns(address pool, address fromToken, address destToken, uint256[] calldata amounts)
                                                  external view returns(uint256[] memory result);
                                          
                                              // Add and update registry
                                              function addPool(address pool) external returns(uint256 listed);
                                              function addPools(address[] calldata pools) external returns(uint256[] memory listed);
                                              function updatedIndices(address[] calldata tokens, uint256 lengthLimit) external;
                                          }
                                          
                                          // File: contracts/OneSplitBase.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract IOneSplitView is IOneSplitConsts {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          }
                                          
                                          
                                          library DisableFlags {
                                              function check(uint256 flags, uint256 flag) internal pure returns(bool) {
                                                  return (flags & flag) != 0;
                                              }
                                          }
                                          
                                          
                                          contract OneSplitRoot is IOneSplitView {
                                              using SafeMath for uint256;
                                              using DisableFlags for uint256;
                                          
                                              using UniversalERC20 for IERC20;
                                              using UniversalERC20 for IWETH;
                                              using UniswapV2ExchangeLib for IUniswapV2Exchange;
                                              using ChaiHelper for IChai;
                                          
                                              uint256 constant internal DEXES_COUNT = 31;
                                              IERC20 constant internal ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              IBancorEtherToken constant internal bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
                                              IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
                                              IChai constant internal chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
                                              IERC20 constant internal dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
                                              IERC20 constant internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
                                              IERC20 constant internal usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
                                              IERC20 constant internal tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
                                              IERC20 constant internal busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
                                              IERC20 constant internal susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
                                              IERC20 constant internal pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1);
                                              IERC20 constant internal renbtc = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D);
                                              IERC20 constant internal wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
                                              IERC20 constant internal tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847);
                                              IERC20 constant internal hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380);
                                              IERC20 constant internal sbtc = IERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6);
                                          
                                              IKyberNetworkProxy constant internal kyberNetworkProxy = IKyberNetworkProxy(0x9AAb3f75489902f3a48495025729a0AF77d4b11e);
                                              IKyberStorage constant internal kyberStorage = IKyberStorage(0xC8fb12402cB16970F3C5F4b48Ff68Eb9D1289301);
                                              IKyberHintHandler constant internal kyberHintHandler = IKyberHintHandler(0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C);
                                              IUniswapFactory constant internal uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
                                              IBancorContractRegistry constant internal bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4);
                                              IBancorNetworkPathFinder constant internal bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
                                              //IBancorConverterRegistry constant internal bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518);
                                              IBancorFinder constant internal bancorFinder = IBancorFinder(0x2B344e14dc2641D11D338C053C908c7A7D4c30B9);
                                              IOasisExchange constant internal oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D);
                                              ICurve constant internal curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56);
                                              ICurve constant internal curveUSDT = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C);
                                              ICurve constant internal curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
                                              ICurve constant internal curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27);
                                              ICurve constant internal curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD);
                                              ICurve constant internal curvePAX = ICurve(0x06364f10B501e868329afBc005b3492902d6C763);
                                              ICurve constant internal curveRenBTC = ICurve(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
                                              ICurve constant internal curveTBTC = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E);
                                              ICurve constant internal curveSBTC = ICurve(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714);
                                              IShell constant internal shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D);
                                              IAaveLendingPool constant internal aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
                                              ICompound constant internal compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
                                              ICompoundEther constant internal cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
                                              IMooniswapRegistry constant internal mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70);
                                              IUniswapV2Factory constant internal uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
                                              IDForceSwap constant internal dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2);
                                              IMStable constant internal musd = IMStable(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
                                              IMassetRedemptionValidator constant internal musd_helper = IMassetRedemptionValidator(0x4c5e03065bC52cCe84F3ac94DF14bbAC27eac89b);
                                              IBalancerRegistry constant internal balancerRegistry = IBalancerRegistry(0x65e67cbc342712DF67494ACEfc06fe951EE93982);
                                              ICurveCalculator constant internal curveCalculator = ICurveCalculator(0xc1DB00a8E5Ef7bfa476395cdbcc98235477cDE4E);
                                              ICurveRegistry constant internal curveRegistry = ICurveRegistry(0x7002B727Ef8F5571Cb5F9D70D13DBEEb4dFAe9d1);
                                              ICompoundRegistry constant internal compoundRegistry = ICompoundRegistry(0xF451Dbd7Ba14BFa7B1B78A766D3Ed438F79EE1D1);
                                              IAaveRegistry constant internal aaveRegistry = IAaveRegistry(0xEd8b133B7B88366E01Bb9E38305Ab11c26521494);
                                          
                                              int256 internal constant VERY_NEGATIVE_VALUE = -1e72;
                                          
                                              function _findBestDistribution(
                                                  uint256 s,                // parts
                                                  int256[][] memory amounts // exchangesReturns
                                              )
                                                  internal
                                                  pure
                                                  returns(
                                                      int256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  uint256 n = amounts.length;
                                          
                                                  int256[][] memory answer = new int256[][](n); // int[n][s+1]
                                                  uint256[][] memory parent = new uint256[][](n); // int[n][s+1]
                                          
                                                  for (uint i = 0; i < n; i++) {
                                                      answer[i] = new int256[](s + 1);
                                                      parent[i] = new uint256[](s + 1);
                                                  }
                                          
                                                  for (uint j = 0; j <= s; j++) {
                                                      answer[0][j] = amounts[0][j];
                                                      for (uint i = 1; i < n; i++) {
                                                          answer[i][j] = -1e72;
                                                      }
                                                      parent[0][j] = 0;
                                                  }
                                          
                                                  for (uint i = 1; i < n; i++) {
                                                      for (uint j = 0; j <= s; j++) {
                                                          answer[i][j] = answer[i - 1][j];
                                                          parent[i][j] = j;
                                          
                                                          for (uint k = 1; k <= j; k++) {
                                                              if (answer[i - 1][j - k] + amounts[i][k] > answer[i][j]) {
                                                                  answer[i][j] = answer[i - 1][j - k] + amounts[i][k];
                                                                  parent[i][j] = j - k;
                                                              }
                                                          }
                                                      }
                                                  }
                                          
                                                  distribution = new uint256[](DEXES_COUNT);
                                          
                                                  uint256 partsLeft = s;
                                                  for (uint curExchange = n - 1; partsLeft > 0; curExchange--) {
                                                      distribution[curExchange] = partsLeft - parent[curExchange][partsLeft];
                                                      partsLeft = parent[curExchange][partsLeft];
                                                  }
                                          
                                                  returnAmount = (answer[n - 1][s] == VERY_NEGATIVE_VALUE) ? 0 : answer[n - 1][s];
                                              }
                                          
                                              function _kyberReserveIdByTokens(
                                                  IERC20 fromToken,
                                                  IERC20 destToken
                                              ) internal view returns(bytes32) {
                                                  if (!fromToken.isETH() && !destToken.isETH()) {
                                                      return 0;
                                                  }
                                          
                                                  bytes32[] memory reserveIds = kyberStorage.getReserveIdsPerTokenSrc(
                                                      fromToken.isETH() ? destToken : fromToken
                                                  );
                                          
                                                  for (uint i = 0; i < reserveIds.length; i++) {
                                                      if ((uint256(reserveIds[i]) >> 248) != 0xBB && // Bridge
                                                          reserveIds[i] != 0xff4b796265722046707200000000000000000000000000000000000000000000 && // Reserve 1
                                                          reserveIds[i] != 0xffabcd0000000000000000000000000000000000000000000000000000000000 && // Reserve 2
                                                          reserveIds[i] != 0xff4f6e65426974205175616e7400000000000000000000000000000000000000)   // Reserve 3
                                                      {
                                                          return reserveIds[i];
                                                      }
                                                  }
                                          
                                                  return 0;
                                              }
                                          
                                              function _scaleDestTokenEthPriceTimesGasPrice(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              ) internal view returns(uint256) {
                                                  if (fromToken == destToken) {
                                                      return destTokenEthPriceTimesGasPrice;
                                                  }
                                          
                                                  uint256 mul = _cheapGetPrice(ETH_ADDRESS, destToken, 0.01 ether);
                                                  uint256 div = _cheapGetPrice(ETH_ADDRESS, fromToken, 0.01 ether);
                                                  if (div > 0) {
                                                      return destTokenEthPriceTimesGasPrice.mul(mul).div(div);
                                                  }
                                                  return 0;
                                              }
                                          
                                              function _cheapGetPrice(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount
                                              ) internal view returns(uint256 returnAmount) {
                                                  (returnAmount,,) = this.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      1,
                                                      FLAG_DISABLE_SPLIT_RECALCULATION |
                                                      FLAG_DISABLE_ALL_SPLIT_SOURCES |
                                                      FLAG_DISABLE_UNISWAP_V2_ALL |
                                                      FLAG_DISABLE_UNISWAP,
                                                      0
                                                  );
                                              }
                                          
                                              function _linearInterpolation(
                                                  uint256 value,
                                                  uint256 parts
                                              ) internal pure returns(uint256[] memory rets) {
                                                  rets = new uint256[](parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      rets[i] = value.mul(i + 1).div(parts);
                                                  }
                                              }
                                          
                                              function _tokensEqual(IERC20 tokenA, IERC20 tokenB) internal pure returns(bool) {
                                                  return ((tokenA.isETH() && tokenB.isETH()) || tokenA == tokenB);
                                              }
                                          }
                                          
                                          
                                          contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = this.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _getExpectedReturnRespectingGasFloor(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _getExpectedReturnRespectingGasFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  internal
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          }
                                          
                                          
                                          contract OneSplitView is IOneSplitView, OneSplitRoot {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  distribution = new uint256[](DEXES_COUNT);
                                          
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, distribution);
                                                  }
                                          
                                                  function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory reserves = _getAllReserves(flags);
                                          
                                                  int256[][] memory matrix = new int256[][](DEXES_COUNT);
                                                  uint256[DEXES_COUNT] memory gases;
                                                  bool atLeastOnePositive = false;
                                                  for (uint i = 0; i < DEXES_COUNT; i++) {
                                                      uint256[] memory rets;
                                                      (rets, gases[i]) = reserves[i](fromToken, destToken, amount, parts, flags);
                                          
                                                      // Prepend zero and sub gas
                                                      int256 gas = int256(gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18));
                                                      matrix[i] = new int256[](parts + 1);
                                                      for (uint j = 0; j < parts; j++) {
                                                          matrix[i][j + 1] = int256(rets[j]) - gas;
                                                          atLeastOnePositive = atLeastOnePositive || (matrix[i][j + 1] > 0);
                                                      }
                                                  }
                                          
                                                  if (!atLeastOnePositive) {
                                                      for (uint i = 0; i < DEXES_COUNT; i++) {
                                                          for (uint j = 1; j < parts + 1; j++) {
                                                              if (matrix[i][j] == 0) {
                                                                  matrix[i][j] = VERY_NEGATIVE_VALUE;
                                                              }
                                                          }
                                                      }
                                                  }
                                          
                                                  (, distribution) = _findBestDistribution(parts, matrix);
                                          
                                                  (returnAmount, estimateGasAmount) = _getReturnAndGasByDistribution(
                                                      Args({
                                                          fromToken: fromToken,
                                                          destToken: destToken,
                                                          amount: amount,
                                                          parts: parts,
                                                          flags: flags,
                                                          destTokenEthPriceTimesGasPrice: destTokenEthPriceTimesGasPrice,
                                                          distribution: distribution,
                                                          matrix: matrix,
                                                          gases: gases,
                                                          reserves: reserves
                                                      })
                                                  );
                                                  return (returnAmount, estimateGasAmount, distribution);
                                              }
                                          
                                              struct Args {
                                                  IERC20 fromToken;
                                                  IERC20 destToken;
                                                  uint256 amount;
                                                  uint256 parts;
                                                  uint256 flags;
                                                  uint256 destTokenEthPriceTimesGasPrice;
                                                  uint256[] distribution;
                                                  int256[][] matrix;
                                                  uint256[DEXES_COUNT] gases;
                                                  function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] reserves;
                                              }
                                          
                                              function _getReturnAndGasByDistribution(
                                                  Args memory args
                                              ) internal view returns(uint256 returnAmount, uint256 estimateGasAmount) {
                                                  bool[DEXES_COUNT] memory exact = [
                                                      true,  // "Uniswap",
                                                      false, // "Kyber",
                                                      false, // "Bancor",
                                                      false, // "Oasis",
                                                      true,  // "Curve Compound",
                                                      true,  // "Curve USDT",
                                                      true,  // "Curve Y",
                                                      true,  // "Curve Binance",
                                                      true,  // "Curve Synthetix",
                                                      true,  // "Uniswap Compound",
                                                      true,  // "Uniswap CHAI",
                                                      true,  // "Uniswap Aave",
                                                      false, // "Mooniswap",
                                                      true,  // "Uniswap V2",
                                                      true,  // "Uniswap V2 (ETH)",
                                                      true,  // "Uniswap V2 (DAI)",
                                                      true,  // "Uniswap V2 (USDC)",
                                                      true,  // "Curve Pax",
                                                      true,  // "Curve RenBTC",
                                                      true,  // "Curve tBTC",
                                                      true,  // "Dforce XSwap",
                                                      false, // "Shell",
                                                      true,  // "mStable",
                                                      true,  // "Curve sBTC"
                                                      true,  // "Balancer 1"
                                                      true,  // "Balancer 2"
                                                      true,  // "Balancer 3"
                                                      true,  // "Kyber 1"
                                                      true,  // "Kyber 2"
                                                      true,  // "Kyber 3"
                                                      true   // "Kyber 4"
                                                  ];
                                          
                                                  for (uint i = 0; i < DEXES_COUNT; i++) {
                                                      if (args.distribution[i] > 0) {
                                                          if (args.distribution[i] == args.parts || exact[i] || args.flags.check(FLAG_DISABLE_SPLIT_RECALCULATION)) {
                                                              estimateGasAmount = estimateGasAmount.add(args.gases[i]);
                                                              int256 value = args.matrix[i][args.distribution[i]];
                                                              returnAmount = returnAmount.add(uint256(
                                                                  (value == VERY_NEGATIVE_VALUE ? 0 : value) +
                                                                  int256(args.gases[i].mul(args.destTokenEthPriceTimesGasPrice).div(1e18))
                                                              ));
                                                          }
                                                          else {
                                                              (uint256[] memory rets, uint256 gas) = args.reserves[i](args.fromToken, args.destToken, args.amount.mul(args.distribution[i]).div(args.parts), 1, args.flags);
                                                              estimateGasAmount = estimateGasAmount.add(gas);
                                                              returnAmount = returnAmount.add(rets[0]);
                                                          }
                                                      }
                                                  }
                                              }
                                          
                                              function _getAllReserves(uint256 flags)
                                                  internal
                                                  pure
                                                  returns(function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory)
                                              {
                                                  bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES);
                                                  return [
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP)            ? _calculateNoReturn : calculateUniswap,
                                                      _calculateNoReturn, // invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyber,
                                                      invert != flags.check(FLAG_DISABLE_BANCOR)                                        ? _calculateNoReturn : calculateBancor,
                                                      invert != flags.check(FLAG_DISABLE_OASIS)                                         ? _calculateNoReturn : calculateOasis,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_COMPOUND)       ? _calculateNoReturn : calculateCurveCompound,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_USDT)           ? _calculateNoReturn : calculateCurveUSDT,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_Y)              ? _calculateNoReturn : calculateCurveY,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_BINANCE)        ? _calculateNoReturn : calculateCurveBinance,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SYNTHETIX)      ? _calculateNoReturn : calculateCurveSynthetix,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_COMPOUND)   ? _calculateNoReturn : calculateUniswapCompound,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_CHAI)       ? _calculateNoReturn : calculateUniswapChai,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_AAVE)       ? _calculateNoReturn : calculateUniswapAave,
                                                      invert != flags.check(FLAG_DISABLE_MOONISWAP)                                     ? _calculateNoReturn : calculateMooniswap,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2)      ? _calculateNoReturn : calculateUniswapV2,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_ETH)  ? _calculateNoReturn : calculateUniswapV2ETH,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_DAI)  ? _calculateNoReturn : calculateUniswapV2DAI,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_PAX)            ? _calculateNoReturn : calculateCurvePAX,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_RENBTC)         ? _calculateNoReturn : calculateCurveRenBTC,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_TBTC)           ? _calculateNoReturn : calculateCurveTBTC,
                                                      invert != flags.check(FLAG_DISABLE_DFORCE_SWAP)                                   ? _calculateNoReturn : calculateDforceSwap,
                                                      invert != flags.check(FLAG_DISABLE_SHELL)                                         ? _calculateNoReturn : calculateShell,
                                                      invert != flags.check(FLAG_DISABLE_MSTABLE_MUSD)                                  ? _calculateNoReturn : calculateMStableMUSD,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SBTC)           ? _calculateNoReturn : calculateCurveSBTC,
                                                      invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_1)        ? _calculateNoReturn : calculateBalancer1,
                                                      invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_2)        ? _calculateNoReturn : calculateBalancer2,
                                                      invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_3)        ? _calculateNoReturn : calculateBalancer3,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_1)              ? _calculateNoReturn : calculateKyber1,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_2)              ? _calculateNoReturn : calculateKyber2,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_3)              ? _calculateNoReturn : calculateKyber3,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_4)              ? _calculateNoReturn : calculateKyber4
                                                  ];
                                              }
                                          
                                              function _calculateNoGas(
                                                  IERC20 /*fromToken*/,
                                                  IERC20 /*destToken*/,
                                                  uint256 /*amount*/,
                                                  uint256 /*parts*/,
                                                  uint256 /*destTokenEthPriceTimesGasPrice*/,
                                                  uint256 /*flags*/,
                                                  uint256 /*destTokenEthPrice*/
                                              ) internal view returns(uint256[] memory /*rets*/, uint256 /*gas*/) {
                                                  this;
                                              }
                                          
                                              // View Helpers
                                          
                                              function _calculateBalancer(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/,
                                                  uint256 poolIndex
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = new uint256[](parts);
                                          
                                                  address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
                                                      address(fromToken.isETH() ? weth : fromToken),
                                                      address(destToken.isETH() ? weth : destToken),
                                                      poolIndex + 1
                                                  );
                                                  if (poolIndex >= pools.length) {
                                                      return (rets, 0);
                                                  }
                                          
                                                  (bool success, bytes memory result) = address(balancerRegistry).staticcall(
                                                      abi.encodeWithSelector(
                                                          balancerRegistry.getPoolReturns.selector,
                                                          pools[poolIndex],
                                                          address(fromToken.isETH() ? weth : fromToken),
                                                          address(destToken.isETH() ? weth : destToken),
                                                          _linearInterpolation(amount, parts)
                                                      )
                                                  );
                                          
                                                  if (!success || result.length == 0) {
                                                      return (rets, 0);
                                                  }
                                          
                                                  return (
                                                      abi.decode(result, (uint256[])),
                                                      100_000
                                                  );
                                              }
                                          
                                              function calculateBalancer1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateBalancer(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function calculateBalancer2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateBalancer(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      1
                                                  );
                                              }
                                          
                                              function calculateBalancer3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateBalancer(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      2
                                                  );
                                              }
                                          
                                              function calculateMStableMUSD(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = new uint256[](parts);
                                          
                                                  if ((fromToken != usdc && fromToken != dai && fromToken != usdt && fromToken != tusd) ||
                                                      (destToken != usdc && destToken != dai && destToken != usdt && destToken != tusd))
                                                  {
                                                      return (rets, 0);
                                                  }
                                          
                                                  for (uint i = 1; i <= parts; i *= 2) {
                                                      (bool success, bytes memory data) = address(musd).staticcall(abi.encodeWithSelector(
                                                          musd.getSwapOutput.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount.mul(parts.div(i)).div(parts)
                                                      ));
                                          
                                                      if (success && data.length > 0) {
                                                          (,, uint256 maxRet) = abi.decode(data, (bool,string,uint256));
                                                          if (maxRet > 0) {
                                                              for (uint j = 0; j < parts.div(i); j++) {
                                                                  rets[j] = maxRet.mul(j + 1).div(parts.div(i));
                                                              }
                                                              break;
                                                          }
                                                      }
                                                  }
                                          
                                                  return (
                                                      rets,
                                                      700_000
                                                  );
                                              }
                                          
                                              function _getCurvePoolInfo(
                                                  ICurve curve,
                                                  bool haveUnderlying
                                              ) internal view returns(
                                                  uint256[8] memory balances,
                                                  uint256[8] memory precisions,
                                                  uint256[8] memory rates,
                                                  uint256 amp,
                                                  uint256 fee
                                              ) {
                                                  uint256[8] memory underlying_balances;
                                                  uint256[8] memory decimals;
                                                  uint256[8] memory underlying_decimals;
                                          
                                                  (
                                                      balances,
                                                      underlying_balances,
                                                      decimals,
                                                      underlying_decimals,
                                                      /*address lp_token*/,
                                                      amp,
                                                      fee
                                                  ) = curveRegistry.get_pool_info(address(curve));
                                          
                                                  for (uint k = 0; k < 8 && balances[k] > 0; k++) {
                                                      precisions[k] = 10 ** (18 - (haveUnderlying ? underlying_decimals : decimals)[k]);
                                                      if (haveUnderlying) {
                                                          rates[k] = underlying_balances[k].mul(1e18).div(balances[k]);
                                                      } else {
                                                          rates[k] = 1e18;
                                                      }
                                                  }
                                              }
                                          
                                              function _calculateCurveSelector(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  ICurve curve,
                                                  bool haveUnderlying,
                                                  IERC20[] memory tokens
                                              ) internal view returns(uint256[] memory rets) {
                                                  rets = new uint256[](parts);
                                          
                                                  int128 i = 0;
                                                  int128 j = 0;
                                                  for (uint t = 0; t < tokens.length; t++) {
                                                      if (fromToken == tokens[t]) {
                                                          i = int128(t + 1);
                                                      }
                                                      if (destToken == tokens[t]) {
                                                          j = int128(t + 1);
                                                      }
                                                  }
                                          
                                                  if (i == 0 || j == 0) {
                                                      return rets;
                                                  }
                                          
                                                  bytes memory data = abi.encodePacked(
                                                      uint256(haveUnderlying ? 1 : 0),
                                                      uint256(i - 1),
                                                      uint256(j - 1),
                                                      _linearInterpolation100(amount, parts)
                                                  );
                                          
                                                  (
                                                      uint256[8] memory balances,
                                                      uint256[8] memory precisions,
                                                      uint256[8] memory rates,
                                                      uint256 amp,
                                                      uint256 fee
                                                  ) = _getCurvePoolInfo(curve, haveUnderlying);
                                          
                                                  bool success;
                                                  (success, data) = address(curveCalculator).staticcall(
                                                      abi.encodePacked(
                                                          abi.encodeWithSelector(
                                                              curveCalculator.get_dy.selector,
                                                              tokens.length,
                                                              balances,
                                                              amp,
                                                              fee,
                                                              rates,
                                                              precisions
                                                          ),
                                                          data
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return rets;
                                                  }
                                          
                                                  uint256[100] memory dy = abi.decode(data, (uint256[100]));
                                                  for (uint t = 0; t < parts; t++) {
                                                      rets[t] = dy[t];
                                                  }
                                              }
                                          
                                              function _linearInterpolation100(
                                                  uint256 value,
                                                  uint256 parts
                                              ) internal pure returns(uint256[100] memory rets) {
                                                  for (uint i = 0; i < parts; i++) {
                                                      rets[i] = value.mul(i + 1).div(parts);
                                                  }
                                              }
                                          
                                              function calculateCurveCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](2);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveCompound,
                                                      true,
                                                      tokens
                                                  ), 720_000);
                                              }
                                          
                                              function calculateCurveUSDT(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](3);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveUSDT,
                                                      true,
                                                      tokens
                                                  ), 720_000);
                                              }
                                          
                                              function calculateCurveY(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = tusd;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveY,
                                                      true,
                                                      tokens
                                                  ), 1_400_000);
                                              }
                                          
                                              function calculateCurveBinance(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = busd;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveBinance,
                                                      true,
                                                      tokens
                                                  ), 1_400_000);
                                              }
                                          
                                              function calculateCurveSynthetix(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = susd;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveSynthetix,
                                                      true,
                                                      tokens
                                                  ), 200_000);
                                              }
                                          
                                              function calculateCurvePAX(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = pax;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curvePAX,
                                                      true,
                                                      tokens
                                                  ), 1_000_000);
                                              }
                                          
                                              function calculateCurveRenBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](2);
                                                  tokens[0] = renbtc;
                                                  tokens[1] = wbtc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveRenBTC,
                                                      false,
                                                      tokens
                                                  ), 130_000);
                                              }
                                          
                                              function calculateCurveTBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](3);
                                                  tokens[0] = tbtc;
                                                  tokens[1] = wbtc;
                                                  tokens[2] = hbtc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveTBTC,
                                                      false,
                                                      tokens
                                                  ), 145_000);
                                              }
                                          
                                              function calculateCurveSBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](3);
                                                  tokens[0] = renbtc;
                                                  tokens[1] = wbtc;
                                                  tokens[2] = sbtc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveSBTC,
                                                      false,
                                                      tokens
                                                  ), 150_000);
                                              }
                                          
                                              function calculateShell(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  (bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector(
                                                      shell.viewOriginTrade.selector,
                                                      fromToken,
                                                      destToken,
                                                      amount
                                                  ));
                                          
                                                  if (!success || data.length == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  uint256 maxRet = abi.decode(data, (uint256));
                                                  return (_linearInterpolation(maxRet, parts), 300_000);
                                              }
                                          
                                              function calculateDforceSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  (bool success, bytes memory data) = address(dforceSwap).staticcall(
                                                      abi.encodeWithSelector(
                                                          dforceSwap.getAmountByInput.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount
                                                      )
                                                  );
                                                  if (!success || data.length == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  uint256 maxRet = abi.decode(data, (uint256));
                                                  uint256 available = destToken.universalBalanceOf(address(dforceSwap));
                                                  if (maxRet > available) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return (_linearInterpolation(maxRet, parts), 160_000);
                                              }
                                          
                                              function _calculateUniswapFormula(uint256 fromBalance, uint256 toBalance, uint256 amount) internal pure returns(uint256) {
                                                  if (amount == 0) {
                                                      return 0;
                                                  }
                                                  return amount.mul(toBalance).mul(997).div(
                                                      fromBalance.mul(1000).add(amount.mul(997))
                                                  );
                                              }
                                          
                                              function _calculateUniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256[] memory amounts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = amounts;
                                          
                                                  if (!fromToken.isETH()) {
                                                      IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
                                                      if (fromExchange == IUniswapExchange(0)) {
                                                          return (new uint256[](rets.length), 0);
                                                      }
                                          
                                                      uint256 fromTokenBalance = fromToken.universalBalanceOf(address(fromExchange));
                                                      uint256 fromEtherBalance = address(fromExchange).balance;
                                          
                                                      for (uint i = 0; i < rets.length; i++) {
                                                          rets[i] = _calculateUniswapFormula(fromTokenBalance, fromEtherBalance, rets[i]);
                                                      }
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
                                                      if (toExchange == IUniswapExchange(0)) {
                                                          return (new uint256[](rets.length), 0);
                                                      }
                                          
                                                      uint256 toEtherBalance = address(toExchange).balance;
                                                      uint256 toTokenBalance = destToken.universalBalanceOf(address(toExchange));
                                          
                                                      for (uint i = 0; i < rets.length; i++) {
                                                          rets[i] = _calculateUniswapFormula(toEtherBalance, toTokenBalance, rets[i]);
                                                      }
                                                  }
                                          
                                                  return (rets, fromToken.isETH() || destToken.isETH() ? 60_000 : 100_000);
                                              }
                                          
                                              function calculateUniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateUniswap(
                                                      fromToken,
                                                      destToken,
                                                      _linearInterpolation(amount, parts),
                                                      flags
                                                  );
                                              }
                                          
                                              function _calculateUniswapWrapped(
                                                  IERC20 fromToken,
                                                  IERC20 midToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 midTokenPrice,
                                                  uint256 flags,
                                                  uint256 gas1,
                                                  uint256 gas2
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (!fromToken.isETH() && destToken.isETH()) {
                                                      (rets, gas) = _calculateUniswap(
                                                          midToken,
                                                          destToken,
                                                          _linearInterpolation(amount.mul(1e18).div(midTokenPrice), parts),
                                                          flags
                                                      );
                                                      return (rets, gas + gas1);
                                                  }
                                                  else if (fromToken.isETH() && !destToken.isETH()) {
                                                      (rets, gas) = _calculateUniswap(
                                                          fromToken,
                                                          midToken,
                                                          _linearInterpolation(amount, parts),
                                                          flags
                                                      );
                                          
                                                      for (uint i = 0; i < parts; i++) {
                                                          rets[i] = rets[i].mul(midTokenPrice).div(1e18);
                                                      }
                                                      return (rets, gas + gas2);
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateUniswapCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20 midPreToken;
                                                  if (!fromToken.isETH() && destToken.isETH()) {
                                                      midPreToken = fromToken;
                                                  }
                                                  else if (!destToken.isETH() && fromToken.isETH()) {
                                                      midPreToken = destToken;
                                                  }
                                          
                                                  if (!midPreToken.isETH()) {
                                                      ICompoundToken midToken = compoundRegistry.cTokenByToken(midPreToken);
                                                      if (midToken != ICompoundToken(0)) {
                                                          return _calculateUniswapWrapped(
                                                              fromToken,
                                                              midToken,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              midToken.exchangeRateStored(),
                                                              flags,
                                                              200_000,
                                                              200_000
                                                          );
                                                      }
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateUniswapChai(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken == dai && destToken.isETH() ||
                                                      fromToken.isETH() && destToken == dai)
                                                  {
                                                      return _calculateUniswapWrapped(
                                                          fromToken,
                                                          chai,
                                                          destToken,
                                                          amount,
                                                          parts,
                                                          chai.chaiPrice(),
                                                          flags,
                                                          180_000,
                                                          160_000
                                                      );
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateUniswapAave(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20 midPreToken;
                                                  if (!fromToken.isETH() && destToken.isETH()) {
                                                      midPreToken = fromToken;
                                                  }
                                                  else if (!destToken.isETH() && fromToken.isETH()) {
                                                      midPreToken = destToken;
                                                  }
                                          
                                                  if (!midPreToken.isETH()) {
                                                      IAaveToken midToken = aaveRegistry.aTokenByToken(midPreToken);
                                                      if (midToken != IAaveToken(0)) {
                                                          return _calculateUniswapWrapped(
                                                              fromToken,
                                                              midToken,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              1e18,
                                                              flags,
                                                              310_000,
                                                              670_000
                                                          );
                                                      }
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateKyber1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0xff4b796265722046707200000000000000000000000000000000000000000000 // 0x63825c174ab367968EC60f061753D3bbD36A0D8F
                                                  );
                                              }
                                          
                                              function calculateKyber2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0xffabcd0000000000000000000000000000000000000000000000000000000000 // 0x7a3370075a54B187d7bD5DceBf0ff2B5552d4F7D
                                                  );
                                              }
                                          
                                              function calculateKyber3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0xff4f6e65426974205175616e7400000000000000000000000000000000000000 // 0x4f32BbE8dFc9efD54345Fc936f9fEF1048746fCF
                                                  );
                                              }
                                          
                                              function calculateKyber4(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  bytes32 reserveId = _kyberReserveIdByTokens(fromToken, destToken);
                                                  if (reserveId == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      reserveId
                                                  );
                                              }
                                          
                                              function _kyberGetRate(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags,
                                                  bytes memory hint
                                              ) private view returns(uint256) {
                                                  (, bytes memory data) = address(kyberNetworkProxy).staticcall(
                                                      abi.encodeWithSelector(
                                                          kyberNetworkProxy.getExpectedRateAfterFee.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount,
                                                          flags.check(1 << 255) ? 10 : 0,
                                                          hint
                                                      )
                                                  );
                                          
                                                  return (data.length == 32) ? abi.decode(data, (uint256)) : 0;
                                              }
                                          
                                              function _calculateKyber(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  bytes32 reserveId
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  bytes memory fromHint;
                                                  bytes memory destHint;
                                                  {
                                                      bytes32[] memory reserveIds = new bytes32[](1);
                                                      reserveIds[0] = reserveId;
                                          
                                                      (bool success, bytes memory data) = address(kyberHintHandler).staticcall(
                                                          abi.encodeWithSelector(
                                                              kyberHintHandler.buildTokenToEthHint.selector,
                                                              fromToken,
                                                              IKyberHintHandler.TradeType.MaskIn,
                                                              reserveIds,
                                                              new uint256[](0)
                                                          )
                                                      );
                                                      fromHint = success ? abi.decode(data, (bytes)) : bytes("");
                                          
                                                      (success, data) = address(kyberHintHandler).staticcall(
                                                          abi.encodeWithSelector(
                                                              kyberHintHandler.buildEthToTokenHint.selector,
                                                              destToken,
                                                              IKyberHintHandler.TradeType.MaskIn,
                                                              reserveIds,
                                                              new uint256[](0)
                                                          )
                                                      );
                                                      destHint = success ? abi.decode(data, (bytes)) : bytes("");
                                                  }
                                          
                                                  uint256 fromTokenDecimals = 10 ** IERC20(fromToken).universalDecimals();
                                                  uint256 destTokenDecimals = 10 ** IERC20(destToken).universalDecimals();
                                                  rets = new uint256[](parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      if (i > 0 && rets[i - 1] == 0) {
                                                          break;
                                                      }
                                                      rets[i] = amount.mul(i + 1).div(parts);
                                          
                                                      if (!fromToken.isETH()) {
                                                          if (fromHint.length == 0) {
                                                              rets[i] = 0;
                                                              break;
                                                          }
                                                          uint256 rate = _kyberGetRate(
                                                              fromToken,
                                                              ETH_ADDRESS,
                                                              rets[i],
                                                              flags,
                                                              fromHint
                                                          );
                                                          rets[i] = rate.mul(rets[i]).div(fromTokenDecimals);
                                                      }
                                          
                                                      if (!destToken.isETH() && rets[i] > 0) {
                                                          if (destHint.length == 0) {
                                                              rets[i] = 0;
                                                              break;
                                                          }
                                                          uint256 rate = _kyberGetRate(
                                                              ETH_ADDRESS,
                                                              destToken,
                                                              rets[i],
                                                              flags.check(1 << 255) ? 10 : 0,
                                                              destHint
                                                          );
                                                          rets[i] = rate.mul(rets[i]).mul(destTokenDecimals).div(1e36);
                                                      }
                                                  }
                                          
                                                  return (rets, 100_000);
                                              }
                                          
                                              function calculateBancor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
                                          
                                                  address[] memory path = bancorFinder.buildBancorPath(
                                                      fromToken.isETH() ? bancorEtherToken : fromToken,
                                                      destToken.isETH() ? bancorEtherToken : destToken
                                                  );
                                          
                                                  rets = _linearInterpolation(amount, parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      (bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)(
                                                          abi.encodeWithSelector(
                                                              bancorNetwork.getReturnByPath.selector,
                                                              path,
                                                              rets[i]
                                                          )
                                                      );
                                                      if (!success || data.length == 0) {
                                                          for (; i < parts; i++) {
                                                              rets[i] = 0;
                                                          }
                                                          break;
                                                      } else {
                                                          (uint256 ret,) = abi.decode(data, (uint256,uint256));
                                                          rets[i] = ret;
                                                      }
                                                  }
                                          
                                                  return (rets, path.length.mul(150_000));
                                              }
                                          
                                              function calculateOasis(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = _linearInterpolation(amount, parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      (bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)(
                                                          abi.encodeWithSelector(
                                                              oasisExchange.getBuyAmount.selector,
                                                              destToken.isETH() ? weth : destToken,
                                                              fromToken.isETH() ? weth : fromToken,
                                                              rets[i]
                                                          )
                                                      );
                                          
                                                      if (!success || data.length == 0) {
                                                          for (; i < parts; i++) {
                                                              rets[i] = 0;
                                                          }
                                                          break;
                                                      } else {
                                                          rets[i] = abi.decode(data, (uint256));
                                                      }
                                                  }
                                          
                                                  return (rets, 500_000);
                                              }
                                          
                                              function calculateMooniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IMooniswap mooniswap = mooniswapRegistry.target();
                                                  (bool success, bytes memory data) = address(mooniswap).staticcall.gas(1000000)(
                                                      abi.encodeWithSelector(
                                                          mooniswap.getReturn.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  uint256 maxRet = abi.decode(data, (uint256));
                                                  return (_linearInterpolation(maxRet, parts), 1_000_000);
                                              }
                                          
                                              function calculateUniswapV2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateUniswapV2(
                                                      fromToken,
                                                      destToken,
                                                      _linearInterpolation(amount, parts),
                                                      flags
                                                  );
                                              }
                                          
                                              function calculateUniswapV2ETH(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken.isETH() || fromToken == weth || destToken.isETH() || destToken == weth) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateUniswapV2OverMidToken(
                                                      fromToken,
                                                      weth,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags
                                                  );
                                              }
                                          
                                              function calculateUniswapV2DAI(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken == dai || destToken == dai) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateUniswapV2OverMidToken(
                                                      fromToken,
                                                      dai,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags
                                                  );
                                              }
                                          
                                              function calculateUniswapV2USDC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken == usdc || destToken == usdc) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateUniswapV2OverMidToken(
                                                      fromToken,
                                                      usdc,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags
                                                  );
                                              }
                                          
                                              function _calculateUniswapV2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256[] memory amounts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = new uint256[](amounts.length);
                                          
                                                  IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
                                                  IERC20 destTokenReal = destToken.isETH() ? weth : destToken;
                                                  IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, destTokenReal);
                                                  if (exchange != IUniswapV2Exchange(0)) {
                                                      uint256 fromTokenBalance = fromTokenReal.universalBalanceOf(address(exchange));
                                                      uint256 destTokenBalance = destTokenReal.universalBalanceOf(address(exchange));
                                                      for (uint i = 0; i < amounts.length; i++) {
                                                          rets[i] = _calculateUniswapFormula(fromTokenBalance, destTokenBalance, amounts[i]);
                                                      }
                                                      return (rets, 50_000);
                                                  }
                                              }
                                          
                                              function _calculateUniswapV2OverMidToken(
                                                  IERC20 fromToken,
                                                  IERC20 midToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = _linearInterpolation(amount, parts);
                                          
                                                  uint256 gas1;
                                                  uint256 gas2;
                                                  (rets, gas1) = _calculateUniswapV2(fromToken, midToken, rets, flags);
                                                  (rets, gas2) = _calculateUniswapV2(midToken, destToken, rets, flags);
                                                  return (rets, gas1 + gas2);
                                              }
                                          
                                              function _calculateNoReturn(
                                                  IERC20 /*fromToken*/,
                                                  IERC20 /*destToken*/,
                                                  uint256 /*amount*/,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  this;
                                                  return (new uint256[](parts), 0);
                                              }
                                          }
                                          
                                          
                                          contract OneSplitBaseWrap is IOneSplit, OneSplitRoot {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  _swapFloor(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 /*flags*/ // See constants in IOneSplit.sol
                                              ) internal;
                                          }
                                          
                                          
                                          contract OneSplit is IOneSplit, OneSplitRoot {
                                              IOneSplitView public oneSplitView;
                                          
                                              constructor(IOneSplitView _oneSplitView) public {
                                                  oneSplitView = _oneSplitView;
                                              }
                                          
                                              function() external payable {
                                                  // solium-disable-next-line security/no-tx-origin
                                                  require(msg.sender != tx.origin);
                                              }
                                          
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return oneSplitView.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256 flags  // See constants in IOneSplit.sol
                                              ) public payable returns(uint256 returnAmount) {
                                                  if (fromToken == destToken) {
                                                      return amount;
                                                  }
                                          
                                                  function(IERC20,IERC20,uint256,uint256)[DEXES_COUNT] memory reserves = [
                                                      _swapOnUniswap,
                                                      _swapOnNowhere,
                                                      _swapOnBancor,
                                                      _swapOnOasis,
                                                      _swapOnCurveCompound,
                                                      _swapOnCurveUSDT,
                                                      _swapOnCurveY,
                                                      _swapOnCurveBinance,
                                                      _swapOnCurveSynthetix,
                                                      _swapOnUniswapCompound,
                                                      _swapOnUniswapChai,
                                                      _swapOnUniswapAave,
                                                      _swapOnMooniswap,
                                                      _swapOnUniswapV2,
                                                      _swapOnUniswapV2ETH,
                                                      _swapOnUniswapV2DAI,
                                                      _swapOnUniswapV2USDC,
                                                      _swapOnCurvePAX,
                                                      _swapOnCurveRenBTC,
                                                      _swapOnCurveTBTC,
                                                      _swapOnDforceSwap,
                                                      _swapOnShell,
                                                      _swapOnMStableMUSD,
                                                      _swapOnCurveSBTC,
                                                      _swapOnBalancer1,
                                                      _swapOnBalancer2,
                                                      _swapOnBalancer3,
                                                      _swapOnKyber1,
                                                      _swapOnKyber2,
                                                      _swapOnKyber3,
                                                      _swapOnKyber4
                                                  ];
                                          
                                                  require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size");
                                          
                                                  uint256 parts = 0;
                                                  uint256 lastNonZeroIndex = 0;
                                                  for (uint i = 0; i < distribution.length; i++) {
                                                      if (distribution[i] > 0) {
                                                          parts = parts.add(distribution[i]);
                                                          lastNonZeroIndex = i;
                                                      }
                                                  }
                                          
                                                  if (parts == 0) {
                                                      if (fromToken.isETH()) {
                                                          msg.sender.transfer(msg.value);
                                                          return msg.value;
                                                      }
                                                      return amount;
                                                  }
                                          
                                                  fromToken.universalTransferFrom(msg.sender, address(this), amount);
                                                  uint256 remainingAmount = fromToken.universalBalanceOf(address(this));
                                          
                                                  for (uint i = 0; i < distribution.length; i++) {
                                                      if (distribution[i] == 0) {
                                                          continue;
                                                      }
                                          
                                                      uint256 swapAmount = amount.mul(distribution[i]).div(parts);
                                                      if (i == lastNonZeroIndex) {
                                                          swapAmount = remainingAmount;
                                                      }
                                                      remainingAmount -= swapAmount;
                                                      reserves[i](fromToken, destToken, swapAmount, flags);
                                                  }
                                          
                                                  returnAmount = destToken.universalBalanceOf(address(this));
                                                  require(returnAmount >= minReturn, "OneSplit: Return amount was not enough");
                                                  destToken.universalTransfer(msg.sender, returnAmount);
                                                  fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
                                              }
                                          
                                              // Swap helpers
                                          
                                              function _swapOnCurveCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveCompound), amount);
                                                  curveCompound.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveUSDT(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveUSDT), amount);
                                                  curveUSDT.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveY(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == tusd ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == tusd ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveY), amount);
                                                  curveY.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveBinance(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == busd ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == busd ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveBinance), amount);
                                                  curveBinance.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveSynthetix(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == susd ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == susd ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveSynthetix), amount);
                                                  curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurvePAX(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == pax ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == pax ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curvePAX), amount);
                                                  curvePAX.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnShell(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  fromToken.universalApprove(address(shell), amount);
                                                  shell.swapByOrigin(
                                                      address(fromToken),
                                                      address(destToken),
                                                      amount,
                                                      0,
                                                      now + 50
                                                  );
                                              }
                                          
                                              function _swapOnMStableMUSD(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  fromToken.universalApprove(address(musd), amount);
                                                  musd.swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      address(this)
                                                  );
                                              }
                                          
                                              function _swapOnCurveRenBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == renbtc ? 1 : 0) +
                                                      (fromToken == wbtc ? 2 : 0);
                                                  int128 j = (destToken == renbtc ? 1 : 0) +
                                                      (destToken == wbtc ? 2 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveRenBTC), amount);
                                                  curveRenBTC.exchange(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveTBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == tbtc ? 1 : 0) +
                                                      (fromToken == wbtc ? 2 : 0) +
                                                      (fromToken == hbtc ? 3 : 0);
                                                  int128 j = (destToken == tbtc ? 1 : 0) +
                                                      (destToken == wbtc ? 2 : 0) +
                                                      (destToken == hbtc ? 3 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveTBTC), amount);
                                                  curveTBTC.exchange(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveSBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == renbtc ? 1 : 0) +
                                                      (fromToken == wbtc ? 2 : 0) +
                                                      (fromToken == sbtc ? 3 : 0);
                                                  int128 j = (destToken == renbtc ? 1 : 0) +
                                                      (destToken == wbtc ? 2 : 0) +
                                                      (destToken == sbtc ? 3 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveSBTC), amount);
                                                  curveSBTC.exchange(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnDforceSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  fromToken.universalApprove(address(dforceSwap), amount);
                                                  dforceSwap.swap(fromToken, destToken, amount);
                                              }
                                          
                                              function _swapOnUniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  uint256 returnAmount = amount;
                                          
                                                  if (!fromToken.isETH()) {
                                                      IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
                                                      if (fromExchange != IUniswapExchange(0)) {
                                                          fromToken.universalApprove(address(fromExchange), returnAmount);
                                                          returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now);
                                                      }
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
                                                      if (toExchange != IUniswapExchange(0)) {
                                                          returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now);
                                                      }
                                                  }
                                              }
                                          
                                              function _swapOnUniswapCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  if (!fromToken.isETH()) {
                                                      ICompoundToken fromCompound = compoundRegistry.cTokenByToken(fromToken);
                                                      fromToken.universalApprove(address(fromCompound), amount);
                                                      fromCompound.mint(amount);
                                                      _swapOnUniswap(IERC20(fromCompound), destToken, IERC20(fromCompound).universalBalanceOf(address(this)), flags);
                                                      return;
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      ICompoundToken toCompound = compoundRegistry.cTokenByToken(destToken);
                                                      _swapOnUniswap(fromToken, IERC20(toCompound), amount, flags);
                                                      toCompound.redeem(IERC20(toCompound).universalBalanceOf(address(this)));
                                                      destToken.universalBalanceOf(address(this));
                                                      return;
                                                  }
                                              }
                                          
                                              function _swapOnUniswapChai(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == dai) {
                                                      fromToken.universalApprove(address(chai), amount);
                                                      chai.join(address(this), amount);
                                                      _swapOnUniswap(IERC20(chai), destToken, IERC20(chai).universalBalanceOf(address(this)), flags);
                                                      return;
                                                  }
                                          
                                                  if (destToken == dai) {
                                                      _swapOnUniswap(fromToken, IERC20(chai), amount, flags);
                                                      chai.exit(address(this), chai.balanceOf(address(this)));
                                                      return;
                                                  }
                                              }
                                          
                                              function _swapOnUniswapAave(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  if (!fromToken.isETH()) {
                                                      IAaveToken fromAave = aaveRegistry.aTokenByToken(fromToken);
                                                      fromToken.universalApprove(aave.core(), amount);
                                                      aave.deposit(fromToken, amount, 1101);
                                                      _swapOnUniswap(IERC20(fromAave), destToken, IERC20(fromAave).universalBalanceOf(address(this)), flags);
                                                      return;
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      IAaveToken toAave = aaveRegistry.aTokenByToken(destToken);
                                                      _swapOnUniswap(fromToken, IERC20(toAave), amount, flags);
                                                      toAave.redeem(toAave.balanceOf(address(this)));
                                                      return;
                                                  }
                                              }
                                          
                                              function _swapOnMooniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  IMooniswap mooniswap = mooniswapRegistry.target();
                                                  fromToken.universalApprove(address(mooniswap), amount);
                                                  mooniswap.swap.value(fromToken.isETH() ? amount : 0)(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      0
                                                  );
                                              }
                                          
                                              function _swapOnNowhere(
                                                  IERC20 /*fromToken*/,
                                                  IERC20 /*destToken*/,
                                                  uint256 /*amount*/,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  revert("This source was deprecated");
                                              }
                                          
                                              function _swapOnKyber1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      0xff4b796265722046707200000000000000000000000000000000000000000000
                                                  );
                                              }
                                          
                                              function _swapOnKyber2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      0xffabcd0000000000000000000000000000000000000000000000000000000000
                                                  );
                                              }
                                          
                                              function _swapOnKyber3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      0xff4f6e65426974205175616e7400000000000000000000000000000000000000
                                                  );
                                              }
                                          
                                              function _swapOnKyber4(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      _kyberReserveIdByTokens(fromToken, destToken)
                                                  );
                                              }
                                          
                                              function _swapOnKyber(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags,
                                                  bytes32 reserveId
                                              ) internal {
                                                  uint256 returnAmount = amount;
                                                  uint256 bps = flags.check(1 << 255) ? 10 : 0;
                                          
                                                  bytes32[] memory reserveIds = new bytes32[](1);
                                                  reserveIds[0] = reserveId;
                                          
                                                  if (!fromToken.isETH()) {
                                                      bytes memory fromHint = kyberHintHandler.buildTokenToEthHint(
                                                          fromToken,
                                                          IKyberHintHandler.TradeType.MaskIn,
                                                          reserveIds,
                                                          new uint256[](0)
                                                      );
                                          
                                                      fromToken.universalApprove(address(kyberNetworkProxy), amount);
                                                      returnAmount = kyberNetworkProxy.tradeWithHintAndFee(
                                                          fromToken,
                                                          returnAmount,
                                                          ETH_ADDRESS,
                                                          address(this),
                                                          uint256(-1),
                                                          0,
                                                          0x4D37f28D2db99e8d35A6C725a5f1749A085850a3,
                                                          bps,
                                                          fromHint
                                                      );
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      bytes memory destHint = kyberHintHandler.buildEthToTokenHint(
                                                          destToken,
                                                          IKyberHintHandler.TradeType.MaskIn,
                                                          reserveIds,
                                                          new uint256[](0)
                                                      );
                                          
                                                      returnAmount = kyberNetworkProxy.tradeWithHintAndFee.value(returnAmount)(
                                                          ETH_ADDRESS,
                                                          returnAmount,
                                                          destToken,
                                                          address(this),
                                                          uint256(-1),
                                                          0,
                                                          0x4D37f28D2db99e8d35A6C725a5f1749A085850a3,
                                                          bps,
                                                          destHint
                                                      );
                                                  }
                                              }
                                          
                                              function _swapOnBancor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
                                                  address[] memory path = bancorNetworkPathFinder.generatePath(
                                                      fromToken.isETH() ? bancorEtherToken : fromToken,
                                                      destToken.isETH() ? bancorEtherToken : destToken
                                                  );
                                                  fromToken.universalApprove(address(bancorNetwork), amount);
                                                  bancorNetwork.convert.value(fromToken.isETH() ? amount : 0)(path, amount, 1);
                                              }
                                          
                                              function _swapOnOasis(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  if (fromToken.isETH()) {
                                                      weth.deposit.value(amount)();
                                                  }
                                          
                                                  IERC20 approveToken = fromToken.isETH() ? weth : fromToken;
                                                  approveToken.universalApprove(address(oasisExchange), amount);
                                                  oasisExchange.sellAllAmount(
                                                      fromToken.isETH() ? weth : fromToken,
                                                      amount,
                                                      destToken.isETH() ? weth : destToken,
                                                      1
                                                  );
                                          
                                                  if (destToken.isETH()) {
                                                      weth.withdraw(weth.balanceOf(address(this)));
                                                  }
                                              }
                                          
                                              function _swapOnUniswapV2Internal(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal returns(uint256 returnAmount) {
                                                  if (fromToken.isETH()) {
                                                      weth.deposit.value(amount)();
                                                  }
                                          
                                                  IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
                                                  IERC20 toTokenReal = destToken.isETH() ? weth : destToken;
                                                  IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal);
                                                  returnAmount = exchange.getReturn(fromTokenReal, toTokenReal, amount);
                                          
                                                  fromTokenReal.universalTransfer(address(exchange), amount);
                                                  if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) {
                                                      exchange.swap(0, returnAmount, address(this), "");
                                                  } else {
                                                      exchange.swap(returnAmount, 0, address(this), "");
                                                  }
                                          
                                                  if (destToken.isETH()) {
                                                      weth.withdraw(weth.balanceOf(address(this)));
                                                  }
                                              }
                                          
                                              function _swapOnUniswapV2OverMid(
                                                  IERC20 fromToken,
                                                  IERC20 midToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2Internal(
                                                      midToken,
                                                      destToken,
                                                      _swapOnUniswapV2Internal(
                                                          fromToken,
                                                          midToken,
                                                          amount,
                                                          flags
                                                      ),
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2Internal(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2ETH(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2OverMid(
                                                      fromToken,
                                                      weth,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2DAI(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2OverMid(
                                                      fromToken,
                                                      dai,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2USDC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2OverMid(
                                                      fromToken,
                                                      usdc,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnBalancerX(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/,
                                                  uint256 poolIndex
                                              ) internal {
                                                  address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
                                                      address(fromToken.isETH() ? weth : fromToken),
                                                      address(destToken.isETH() ? weth : destToken),
                                                      poolIndex + 1
                                                  );
                                          
                                                  if (fromToken.isETH()) {
                                                      weth.deposit.value(amount)();
                                                  }
                                          
                                                  (fromToken.isETH() ? weth : fromToken).universalApprove(pools[poolIndex], amount);
                                                  IBalancerPool(pools[poolIndex]).swapExactAmountIn(
                                                      fromToken.isETH() ? weth : fromToken,
                                                      amount,
                                                      destToken.isETH() ? weth : destToken,
                                                      0,
                                                      uint256(-1)
                                                  );
                                          
                                                  if (destToken.isETH()) {
                                                      weth.withdraw(weth.balanceOf(address(this)));
                                                  }
                                              }
                                          
                                              function _swapOnBalancer1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnBalancerX(fromToken, destToken, amount, flags, 0);
                                              }
                                          
                                              function _swapOnBalancer2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnBalancerX(fromToken, destToken, amount, flags, 1);
                                              }
                                          
                                              function _swapOnBalancer3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnBalancerX(fromToken, destToken, amount, flags, 2);
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitCompound.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitCompoundView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _compoundGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _compoundGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
                                                      IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored();
                                                          (returnAmount, estimateGasAmount, distribution) = _compoundGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount.mul(compoundRate).div(1e18),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 295_000, distribution);
                                                      }
                                          
                                                      underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                          uint256 compoundRate = ICompoundToken(address(destToken)).exchangeRateStored();
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              _destTokenEthPriceTimesGasPrice.mul(compoundRate).div(1e18)
                                                          );
                                                          return (returnAmount.mul(1e18).div(compoundRate), estimateGasAmount + 430_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitCompound is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _compoundSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _compoundSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
                                                      IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          ICompoundToken(address(fromToken)).redeem(amount);
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          return _compoundSwap(
                                                              underlying,
                                                              destToken,
                                                              underlyingAmount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          super._swap(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          if (underlying.isETH()) {
                                                              cETH.mint.value(underlyingAmount)();
                                                          } else {
                                                              underlying.universalApprove(address(destToken), underlyingAmount);
                                                              ICompoundToken(address(destToken)).mint(underlyingAmount);
                                                          }
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/interface/IFulcrum.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IFulcrumToken is IERC20 {
                                              function tokenPrice() external view returns (uint256);
                                          
                                              function loanTokenAddress() external view returns (address);
                                          
                                              function mintWithEther(address receiver) external payable returns (uint256 mintAmount);
                                          
                                              function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
                                          
                                              function burnToEther(address receiver, uint256 burnAmount)
                                                  external
                                                  returns (uint256 loanAmountPaid);
                                          
                                              function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
                                          }
                                          
                                          // File: contracts/OneSplitFulcrum.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitFulcrumBase {
                                              using UniversalERC20 for IERC20;
                                          
                                              function _isFulcrumToken(IERC20 token) internal view returns(IERC20) {
                                                  if (token.isETH()) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  (bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSignature(
                                                      "name()"
                                                  ));
                                                  if (!success) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  bool foundBZX = false;
                                                  for (uint i = 0; i + 6 < data.length; i++) {
                                                      if (data[i + 0] == "F" &&
                                                          data[i + 1] == "u" &&
                                                          data[i + 2] == "l" &&
                                                          data[i + 3] == "c" &&
                                                          data[i + 4] == "r" &&
                                                          data[i + 5] == "u" &&
                                                          data[i + 6] == "m")
                                                      {
                                                          foundBZX = true;
                                                          break;
                                                      }
                                                  }
                                                  if (!foundBZX) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  (success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
                                                      IFulcrumToken(address(token)).loanTokenAddress.selector
                                                  ));
                                                  if (!success) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  return abi.decode(data, (IERC20));
                                              }
                                          }
                                          
                                          
                                          contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _fulcrumGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _fulcrumGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
                                                      IERC20 underlying = _isFulcrumToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice();
                                                          (returnAmount, estimateGasAmount, distribution) = _fulcrumGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount.mul(fulcrumRate).div(1e18),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 381_000, distribution);
                                                      }
                                          
                                                      underlying = _isFulcrumToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                          uint256 fulcrumRate = IFulcrumToken(address(destToken)).tokenPrice();
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              _destTokenEthPriceTimesGasPrice.mul(fulcrumRate).div(1e18)
                                                          );
                                                          return (returnAmount.mul(1e18).div(fulcrumRate), estimateGasAmount + 354_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _fulcrumSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _fulcrumSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
                                                      IERC20 underlying = _isFulcrumToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          if (underlying.isETH()) {
                                                              IFulcrumToken(address(fromToken)).burnToEther(address(this), amount);
                                                          } else {
                                                              IFulcrumToken(address(fromToken)).burn(address(this), amount);
                                                          }
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          return super._swap(
                                                              underlying,
                                                              destToken,
                                                              underlyingAmount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = _isFulcrumToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          super._swap(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          if (underlying.isETH()) {
                                                              IFulcrumToken(address(destToken)).mintWithEther.value(underlyingAmount)(address(this));
                                                          } else {
                                                              underlying.universalApprove(address(destToken), underlyingAmount);
                                                              IFulcrumToken(address(destToken)).mint(address(this), underlyingAmount);
                                                          }
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitChai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitChaiView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
                                                      if (fromToken == IERC20(chai)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              dai,
                                                              destToken,
                                                              chai.chaiToDai(amount),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 197_000, distribution);
                                                      }
                                          
                                                      if (destToken == IERC20(chai)) {
                                                          uint256 price = chai.chaiPrice();
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              dai,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice.mul(1e18).div(price)
                                                          );
                                                          return (returnAmount.mul(price).div(1e18), estimateGasAmount + 168_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitChai is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
                                                      if (fromToken == IERC20(chai)) {
                                                          chai.exit(address(this), amount);
                                          
                                                          return super._swap(
                                                              dai,
                                                              destToken,
                                                              dai.balanceOf(address(this)),
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      if (destToken == IERC20(chai)) {
                                                          super._swap(
                                                              fromToken,
                                                              dai,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 daiBalance = dai.balanceOf(address(this));
                                                          dai.universalApprove(address(chai), daiBalance);
                                                          chai.join(address(this), daiBalance);
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/interface/IBdai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IBdai is IERC20 {
                                              function join(uint256) external;
                                          
                                              function exit(uint256) external;
                                          }
                                          
                                          // File: contracts/OneSplitBdai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitBdaiBase {
                                              IBdai internal constant bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8);
                                              IERC20 internal constant btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f);
                                          }
                                          
                                          
                                          contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
                                                      if (fromToken == IERC20(bdai)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              dai,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 227_000, distribution);
                                                      }
                                          
                                                      if (destToken == IERC20(bdai)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              dai,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 295_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
                                                      if (fromToken == IERC20(bdai)) {
                                                          bdai.exit(amount);
                                          
                                                          uint256 btuBalance = btu.balanceOf(address(this));
                                                          if (btuBalance > 0) {
                                                              (,uint256[] memory btuDistribution) = getExpectedReturn(
                                                                  btu,
                                                                  destToken,
                                                                  btuBalance,
                                                                  1,
                                                                  flags
                                                              );
                                          
                                                              _swap(
                                                                  btu,
                                                                  destToken,
                                                                  btuBalance,
                                                                  btuDistribution,
                                                                  flags
                                                              );
                                                          }
                                          
                                                          return super._swap(
                                                              dai,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      if (destToken == IERC20(bdai)) {
                                                          super._swap(fromToken, dai, amount, distribution, flags);
                                          
                                                          uint256 daiBalance = dai.balanceOf(address(this));
                                                          dai.universalApprove(address(bdai), daiBalance);
                                                          bdai.join(daiBalance);
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(fromToken, destToken, amount, distribution, flags);
                                              }
                                          }
                                          
                                          // File: contracts/interface/IIearn.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IIearn is IERC20 {
                                              function token() external view returns(IERC20);
                                          
                                              function calcPoolValueInToken() external view returns(uint256);
                                          
                                              function deposit(uint256 _amount) external;
                                          
                                              function withdraw(uint256 _shares) external;
                                          }
                                          
                                          // File: contracts/OneSplitIearn.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitIearnBase {
                                              function _yTokens() internal pure returns(IIearn[13] memory) {
                                                  return [
                                                      IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01),
                                                      IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9),
                                                      IIearn(0x73a052500105205d34Daf004eAb301916DA8190f),
                                                      IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D),
                                                      IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e),
                                                      IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600),
                                                      IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE),
                                                      IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32),
                                                      IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447),
                                                      IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951),
                                                      IIearn(0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc),
                                                      IIearn(0x9777d7E2b60bB01759D0E2f8be2095df444cb07E),
                                                      IIearn(0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59)
                                                  ];
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _iearnGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _iearnGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IEARN)) {
                                                      IIearn[13] memory yTokens = _yTokens();
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (fromToken == IERC20(yTokens[i])) {
                                                              (returnAmount, estimateGasAmount, distribution) = _iearnGetExpectedReturn(
                                                                  yTokens[i].token(),
                                                                  destToken,
                                                                  amount
                                                                      .mul(yTokens[i].calcPoolValueInToken())
                                                                      .div(yTokens[i].totalSupply()),
                                                                  parts,
                                                                  flags,
                                                                  destTokenEthPriceTimesGasPrice
                                                              );
                                                              return (returnAmount, estimateGasAmount + 260_000, distribution);
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (destToken == IERC20(yTokens[i])) {
                                                              uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                              IERC20 token = yTokens[i].token();
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  fromToken,
                                                                  token,
                                                                  amount,
                                                                  parts,
                                                                  flags,
                                                                  _destTokenEthPriceTimesGasPrice
                                                                      .mul(yTokens[i].calcPoolValueInToken())
                                                                      .div(yTokens[i].totalSupply())
                                                              );
                                          
                                                              return(
                                                                  returnAmount
                                                                      .mul(yTokens[i].totalSupply())
                                                                      .div(yTokens[i].calcPoolValueInToken()),
                                                                  estimateGasAmount + 743_000,
                                                                  distribution
                                                              );
                                                          }
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _iearnSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _iearnSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_IEARN)) {
                                                      IIearn[13] memory yTokens = _yTokens();
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (fromToken == IERC20(yTokens[i])) {
                                                              IERC20 underlying = yTokens[i].token();
                                                              yTokens[i].withdraw(amount);
                                                              _iearnSwap(underlying, destToken, underlying.balanceOf(address(this)), distribution, flags);
                                                              return;
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (destToken == IERC20(yTokens[i])) {
                                                              IERC20 underlying = yTokens[i].token();
                                                              super._swap(fromToken, underlying, amount, distribution, flags);
                                          
                                                              uint256 underlyingBalance = underlying.balanceOf(address(this));
                                                              underlying.universalApprove(address(yTokens[i]), underlyingBalance);
                                                              yTokens[i].deposit(underlyingBalance);
                                                              return;
                                                          }
                                                      }
                                                  }
                                          
                                                  return super._swap(fromToken, destToken, amount, distribution, flags);
                                              }
                                          }
                                          
                                          // File: contracts/interface/IIdle.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IIdle is IERC20 {
                                              function token()
                                                  external view returns (IERC20);
                                          
                                              function tokenPrice()
                                                  external view returns (uint256);
                                          
                                              function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts)
                                                  external returns (uint256 mintedTokens);
                                          
                                              function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts)
                                                  external returns (uint256 redeemedTokens);
                                          }
                                          
                                          // File: contracts/OneSplitIdle.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitIdleBase {
                                              function _idleTokens() internal pure returns(IIdle[8] memory) {
                                                  // https://developers.idle.finance/contracts-and-codebase
                                                  return [
                                                      // V3
                                                      IIdle(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934),
                                                      IIdle(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6),
                                                      IIdle(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D),
                                                      IIdle(0x1846bdfDB6A0f5c473dEc610144513bd071999fB),
                                                      IIdle(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C),
                                                      IIdle(0x42740698959761BAF1B06baa51EfBD88CB1D862B),
                                                      // V2
                                                      IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD),
                                                      IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991)
                                                  ];
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _idleGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _idleGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  internal
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
                                                      IIdle[8] memory tokens = _idleTokens();
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (fromToken == IERC20(tokens[i])) {
                                                              (returnAmount, estimateGasAmount, distribution) = _idleGetExpectedReturn(
                                                                  tokens[i].token(),
                                                                  destToken,
                                                                  amount.mul(tokens[i].tokenPrice()).div(1e18),
                                                                  parts,
                                                                  flags,
                                                                  destTokenEthPriceTimesGasPrice
                                                              );
                                                              return (returnAmount, estimateGasAmount + 2_400_000, distribution);
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (destToken == IERC20(tokens[i])) {
                                                              uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                              uint256 _price = tokens[i].tokenPrice();
                                                              IERC20 token = tokens[i].token();
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  fromToken,
                                                                  token,
                                                                  amount,
                                                                  parts,
                                                                  flags,
                                                                  _destTokenEthPriceTimesGasPrice.mul(_price).div(1e18)
                                                              );
                                                              return (returnAmount.mul(1e18).div(_price), estimateGasAmount + 1_300_000, distribution);
                                                          }
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _idleSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _idleSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
                                                      IIdle[8] memory tokens = _idleTokens();
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (fromToken == IERC20(tokens[i])) {
                                                              IERC20 underlying = tokens[i].token();
                                                              uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0));
                                                              _idleSwap(underlying, destToken, minted, distribution, flags);
                                                              return;
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (destToken == IERC20(tokens[i])) {
                                                              IERC20 underlying = tokens[i].token();
                                                              super._swap(fromToken, underlying, amount, distribution, flags);
                                          
                                                              uint256 underlyingBalance = underlying.balanceOf(address(this));
                                                              underlying.universalApprove(address(tokens[i]), underlyingBalance);
                                                              tokens[i].mintIdleToken(underlyingBalance, new uint256[](0));
                                                              return;
                                                          }
                                                      }
                                                  }
                                          
                                                  return super._swap(fromToken, destToken, amount, distribution, flags);
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitAave.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitAaveView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _aaveGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _aaveGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
                                                      IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          (returnAmount, estimateGasAmount, distribution) = _aaveGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 670_000, distribution);
                                                      }
                                          
                                                      underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 310_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitAave is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _aaveSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _aaveSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
                                                      IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          IAaveToken(address(fromToken)).redeem(amount);
                                          
                                                          return _aaveSwap(
                                                              underlying,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          super._swap(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          underlying.universalApprove(aave.core(), underlyingAmount);
                                                          aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)(
                                                              underlying.isETH() ? ETH_ADDRESS : underlying,
                                                              underlyingAmount,
                                                              1101
                                                          );
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitWeth.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitWethView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _wethGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _wethGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
                                                      if (fromToken == weth || fromToken == bancorEtherToken) {
                                                          return super.getExpectedReturnWithGas(ETH_ADDRESS, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice);
                                                      }
                                          
                                                      if (destToken == weth || destToken == bancorEtherToken) {
                                                          return super.getExpectedReturnWithGas(fromToken, ETH_ADDRESS, amount, parts, flags, destTokenEthPriceTimesGasPrice);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitWeth is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _wethSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _wethSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
                                                      if (fromToken == weth) {
                                                          weth.withdraw(weth.balanceOf(address(this)));
                                                          super._swap(
                                                              ETH_ADDRESS,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          return;
                                                      }
                                          
                                                      if (fromToken == bancorEtherToken) {
                                                          bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
                                                          super._swap(
                                                              ETH_ADDRESS,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          return;
                                                      }
                                          
                                                      if (destToken == weth) {
                                                          _wethSwap(
                                                              fromToken,
                                                              ETH_ADDRESS,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          weth.deposit.value(address(this).balance)();
                                                          return;
                                                      }
                                          
                                                      if (destToken == bancorEtherToken) {
                                                          _wethSwap(
                                                              fromToken,
                                                              ETH_ADDRESS,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          bancorEtherToken.deposit.value(address(this).balance)();
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitMStable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitMStableView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
                                                      if (fromToken == IERC20(musd)) {
                                                          if (destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd) {
                                                              (,, returnAmount) = musd_helper.getRedeemValidity(fromToken, amount, destToken);
                                                              return (returnAmount, 300_000, new uint256[](DEXES_COUNT));
                                                          }
                                                          else {
                                                              (,, returnAmount) = musd_helper.getRedeemValidity(fromToken, amount, dai);
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  dai,
                                                                  destToken,
                                                                  returnAmount,
                                                                  parts,
                                                                  flags,
                                                                  destTokenEthPriceTimesGasPrice
                                                              );
                                                              return (returnAmount, estimateGasAmount + 300_000, distribution);
                                                          }
                                                      }
                                          
                                                      if (destToken == IERC20(musd)) {
                                                          if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
                                                              (,, returnAmount) = musd.getSwapOutput(fromToken, destToken, amount);
                                                              return (returnAmount, 300_000, new uint256[](DEXES_COUNT));
                                                          }
                                                          else {
                                                              IERC20 _destToken = destToken;
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  fromToken,
                                                                  dai,
                                                                  amount,
                                                                  parts,
                                                                  flags,
                                                                  _scaleDestTokenEthPriceTimesGasPrice(
                                                                      _destToken,
                                                                      dai,
                                                                      destTokenEthPriceTimesGasPrice
                                                                  )
                                                              );
                                                              (,, returnAmount) = musd_helper.getRedeemValidity(dai, returnAmount, destToken);
                                                              return (returnAmount, estimateGasAmount + 300_000, distribution);
                                                          }
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitMStable is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
                                                      if (fromToken == IERC20(musd)) {
                                                          if (destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd) {
                                                              (,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, destToken);
                                                              musd.redeem(
                                                                  destToken,
                                                                  result
                                                              );
                                                          }
                                                          else {
                                                              (,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, dai);
                                                              musd.redeem(
                                                                  dai,
                                                                  result
                                                              );
                                                              super._swap(
                                                                  dai,
                                                                  destToken,
                                                                  dai.balanceOf(address(this)),
                                                                  distribution,
                                                                  flags
                                                              );
                                                          }
                                                          return;
                                                      }
                                          
                                                      if (destToken == IERC20(musd)) {
                                                          if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
                                                              fromToken.universalApprove(address(musd), amount);
                                                              musd.swap(
                                                                  fromToken,
                                                                  destToken,
                                                                  amount,
                                                                  address(this)
                                                              );
                                                          }
                                                          else {
                                                              super._swap(
                                                                  fromToken,
                                                                  dai,
                                                                  amount,
                                                                  distribution,
                                                                  flags
                                                              );
                                                              musd.swap(
                                                                  dai,
                                                                  destToken,
                                                                  dai.balanceOf(address(this)),
                                                                  address(this)
                                                              );
                                                          }
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/interface/IDMM.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IDMMController {
                                              function getUnderlyingTokenForDmm(IERC20 token) external view returns(IERC20);
                                          }
                                          
                                          
                                          contract IDMM is IERC20 {
                                              function getCurrentExchangeRate() public view returns(uint256);
                                              function mint(uint256 underlyingAmount) public returns(uint256);
                                              function redeem(uint256 amount) public returns(uint256);
                                          }
                                          
                                          // File: contracts/OneSplitDMM.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitDMMBase {
                                              IDMMController internal constant _dmmController = IDMMController(0x4CB120Dd1D33C9A3De8Bc15620C7Cd43418d77E2);
                                          
                                              function _getDMMUnderlyingToken(IERC20 token) internal view returns(IERC20) {
                                                  (bool success, bytes memory data) = address(_dmmController).staticcall(
                                                      abi.encodeWithSelector(
                                                          _dmmController.getUnderlyingTokenForDmm.selector,
                                                          token
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  return abi.decode(data, (IERC20));
                                              }
                                          
                                              function _getDMMExchangeRate(IDMM dmm) internal view returns(uint256) {
                                                  (bool success, bytes memory data) = address(dmm).staticcall(
                                                      abi.encodeWithSelector(
                                                          dmm.getCurrentExchangeRate.selector
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return 0;
                                                  }
                                          
                                                  return abi.decode(data, (uint256));
                                              }
                                          }
                                          
                                          
                                          contract OneSplitDMMView is OneSplitViewWrapBase, OneSplitDMMBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _dmmGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _dmmGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
                                                      IERC20 underlying = _getDMMUnderlyingToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          if (underlying == weth) {
                                                              underlying = ETH_ADDRESS;
                                                          }
                                                          IERC20 _fromToken = fromToken;
                                                          (returnAmount, estimateGasAmount, distribution) = _dmmGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount.mul(_getDMMExchangeRate(IDMM(address(_fromToken)))).div(1e18),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 295_000, distribution);
                                                      }
                                          
                                                      underlying = _getDMMUnderlyingToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          if (underlying == weth) {
                                                              underlying = ETH_ADDRESS;
                                                          }
                                                          uint256 price = _getDMMExchangeRate(IDMM(address(destToken)));
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice.mul(price).div(1e18)
                                                          );
                                                          return (
                                                              returnAmount.mul(1e18).div(price),
                                                              estimateGasAmount + 430_000,
                                                              distribution
                                                          );
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitDMM is OneSplitBaseWrap, OneSplitDMMBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _dmmSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _dmmSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
                                                      IERC20 underlying = _getDMMUnderlyingToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          IDMM(address(fromToken)).redeem(amount);
                                                          uint256 balance = underlying.universalBalanceOf(address(this));
                                                          if (underlying == weth) {
                                                              weth.withdraw(balance);
                                                          }
                                                          _dmmSwap(
                                                              (underlying == weth) ? ETH_ADDRESS : underlying,
                                                              destToken,
                                                              balance,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = _getDMMUnderlyingToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          super._swap(
                                                              fromToken,
                                                              (underlying == weth) ? ETH_ADDRESS : underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = ((underlying == weth) ? ETH_ADDRESS : underlying).universalBalanceOf(address(this));
                                                          if (underlying == weth) {
                                                              weth.deposit.value(underlyingAmount);
                                                          }
                                          
                                                          underlying.universalApprove(address(destToken), underlyingAmount);
                                                          IDMM(address(destToken)).mint(underlyingAmount);
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplit.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract OneSplitViewWrap is
                                              OneSplitViewWrapBase,
                                              OneSplitMStableView,
                                              OneSplitChaiView,
                                              OneSplitBdaiView,
                                              OneSplitAaveView,
                                              OneSplitFulcrumView,
                                              OneSplitCompoundView,
                                              OneSplitIearnView,
                                              OneSplitIdleView,
                                              OneSplitWethView,
                                              OneSplitDMMView
                                          {
                                              IOneSplitView public oneSplitView;
                                          
                                              constructor(IOneSplitView _oneSplit) public {
                                                  oneSplitView = _oneSplit;
                                              }
                                          
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _getExpectedReturnRespectingGasFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  internal
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return oneSplitView.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitWrap is
                                              OneSplitBaseWrap,
                                              OneSplitMStable,
                                              OneSplitChai,
                                              OneSplitBdai,
                                              OneSplitAave,
                                              OneSplitFulcrum,
                                              OneSplitCompound,
                                              OneSplitIearn,
                                              OneSplitIdle,
                                              OneSplitWeth,
                                              OneSplitDMM
                                          {
                                              IOneSplitView public oneSplitView;
                                              IOneSplit public oneSplit;
                                          
                                              constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public {
                                                  oneSplitView = _oneSplitView;
                                                  oneSplit = _oneSplit;
                                              }
                                          
                                              function() external payable {
                                                  // solium-disable-next-line security/no-tx-origin
                                                  require(msg.sender != tx.origin);
                                              }
                                          
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return oneSplitView.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGasMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256[] memory parts,
                                                  uint256[] memory flags,
                                                  uint256[] memory destTokenEthPriceTimesGasPrices
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256[] memory returnAmounts,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  uint256[] memory dist;
                                          
                                                  returnAmounts = new uint256[](tokens.length - 1);
                                                  for (uint i = 1; i < tokens.length; i++) {
                                                      if (tokens[i - 1] == tokens[i]) {
                                                          continue;
                                                      }
                                          
                                                      IERC20[] memory _tokens = tokens;
                                          
                                                      (
                                                          returnAmounts[i - 1],
                                                          amount,
                                                          dist
                                                      ) = getExpectedReturnWithGas(
                                                          _tokens[i - 1],
                                                          _tokens[i],
                                                          (i == 1) ? amount : returnAmounts[i - 2],
                                                          parts[i],
                                                          flags[i],
                                                          destTokenEthPriceTimesGasPrices[i]
                                                      );
                                                      estimateGasAmount = estimateGasAmount.add(amount);
                                          
                                                      if (distribution.length == 0) {
                                                          distribution = new uint256[](dist.length);
                                                      }
                                                      for (uint j = 0; j < distribution.length; j++) {
                                                          distribution[j] = distribution[j].add(dist[j] << (8 * (i - 1)));
                                                      }
                                                  }
                                              }
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) public payable returns(uint256 returnAmount) {
                                                  fromToken.universalTransferFrom(msg.sender, address(this), amount);
                                                  uint256 confirmed = fromToken.universalBalanceOf(address(this));
                                                  _swap(fromToken, destToken, confirmed, distribution, flags);
                                          
                                                  returnAmount = destToken.universalBalanceOf(address(this));
                                                  require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
                                                  destToken.universalTransfer(msg.sender, returnAmount);
                                                  fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
                                              }
                                          
                                              function swapMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256[] memory flags
                                              ) public payable returns(uint256 returnAmount) {
                                                  tokens[0].universalTransferFrom(msg.sender, address(this), amount);
                                          
                                                  returnAmount = tokens[0].universalBalanceOf(address(this));
                                                  for (uint i = 1; i < tokens.length; i++) {
                                                      if (tokens[i - 1] == tokens[i]) {
                                                          continue;
                                                      }
                                          
                                                      uint256[] memory dist = new uint256[](distribution.length);
                                                      for (uint j = 0; j < distribution.length; j++) {
                                                          dist[j] = (distribution[j] >> (8 * (i - 1))) & 0xFF;
                                                      }
                                          
                                                      _swap(
                                                          tokens[i - 1],
                                                          tokens[i],
                                                          returnAmount,
                                                          dist,
                                                          flags[i]
                                                      );
                                                      returnAmount = tokens[i].universalBalanceOf(address(this));
                                                      tokens[i - 1].universalTransfer(msg.sender, tokens[i - 1].universalBalanceOf(address(this)));
                                                  }
                                          
                                                  require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
                                                  tokens[tokens.length - 1].universalTransfer(msg.sender, returnAmount);
                                              }
                                          
                                              function _swapFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  fromToken.universalApprove(address(oneSplit), amount);
                                                  oneSplit.swap.value(fromToken.isETH() ? amount : 0)(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      0,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }

                                          File 4 of 15: UniswapV2Pair
                                          // File: contracts/interfaces/IUniswapV2Pair.sol
                                          
                                          pragma solidity >=0.5.0;
                                          
                                          interface IUniswapV2Pair {
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              function name() external pure returns (string memory);
                                              function symbol() external pure returns (string memory);
                                              function decimals() external pure returns (uint8);
                                              function totalSupply() external view returns (uint);
                                              function balanceOf(address owner) external view returns (uint);
                                              function allowance(address owner, address spender) external view returns (uint);
                                          
                                              function approve(address spender, uint value) external returns (bool);
                                              function transfer(address to, uint value) external returns (bool);
                                              function transferFrom(address from, address to, uint value) external returns (bool);
                                          
                                              function DOMAIN_SEPARATOR() external view returns (bytes32);
                                              function PERMIT_TYPEHASH() external pure returns (bytes32);
                                              function nonces(address owner) external view returns (uint);
                                          
                                              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                                          
                                              event Mint(address indexed sender, uint amount0, uint amount1);
                                              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                              event Swap(
                                                  address indexed sender,
                                                  uint amount0In,
                                                  uint amount1In,
                                                  uint amount0Out,
                                                  uint amount1Out,
                                                  address indexed to
                                              );
                                              event Sync(uint112 reserve0, uint112 reserve1);
                                          
                                              function MINIMUM_LIQUIDITY() external pure returns (uint);
                                              function factory() external view returns (address);
                                              function token0() external view returns (address);
                                              function token1() external view returns (address);
                                              function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                                              function price0CumulativeLast() external view returns (uint);
                                              function price1CumulativeLast() external view returns (uint);
                                              function kLast() external view returns (uint);
                                          
                                              function mint(address to) external returns (uint liquidity);
                                              function burn(address to) external returns (uint amount0, uint amount1);
                                              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                              function skim(address to) external;
                                              function sync() external;
                                          
                                              function initialize(address, address) external;
                                          }
                                          
                                          // File: contracts/interfaces/IUniswapV2ERC20.sol
                                          
                                          pragma solidity >=0.5.0;
                                          
                                          interface IUniswapV2ERC20 {
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              function name() external pure returns (string memory);
                                              function symbol() external pure returns (string memory);
                                              function decimals() external pure returns (uint8);
                                              function totalSupply() external view returns (uint);
                                              function balanceOf(address owner) external view returns (uint);
                                              function allowance(address owner, address spender) external view returns (uint);
                                          
                                              function approve(address spender, uint value) external returns (bool);
                                              function transfer(address to, uint value) external returns (bool);
                                              function transferFrom(address from, address to, uint value) external returns (bool);
                                          
                                              function DOMAIN_SEPARATOR() external view returns (bytes32);
                                              function PERMIT_TYPEHASH() external pure returns (bytes32);
                                              function nonces(address owner) external view returns (uint);
                                          
                                              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                                          }
                                          
                                          // File: contracts/libraries/SafeMath.sol
                                          
                                          pragma solidity =0.5.16;
                                          
                                          // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
                                          
                                          library SafeMath {
                                              function add(uint x, uint y) internal pure returns (uint z) {
                                                  require((z = x + y) >= x, 'ds-math-add-overflow');
                                              }
                                          
                                              function sub(uint x, uint y) internal pure returns (uint z) {
                                                  require((z = x - y) <= x, 'ds-math-sub-underflow');
                                              }
                                          
                                              function mul(uint x, uint y) internal pure returns (uint z) {
                                                  require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                                              }
                                          }
                                          
                                          // File: contracts/UniswapV2ERC20.sol
                                          
                                          pragma solidity =0.5.16;
                                          
                                          
                                          
                                          contract UniswapV2ERC20 is IUniswapV2ERC20 {
                                              using SafeMath for uint;
                                          
                                              string public constant name = 'Uniswap V2';
                                              string public constant symbol = 'UNI-V2';
                                              uint8 public constant decimals = 18;
                                              uint  public totalSupply;
                                              mapping(address => uint) public balanceOf;
                                              mapping(address => mapping(address => uint)) public allowance;
                                          
                                              bytes32 public DOMAIN_SEPARATOR;
                                              // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                                              bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                              mapping(address => uint) public nonces;
                                          
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              constructor() public {
                                                  uint chainId;
                                                  assembly {
                                                      chainId := chainid
                                                  }
                                                  DOMAIN_SEPARATOR = keccak256(
                                                      abi.encode(
                                                          keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                                                          keccak256(bytes(name)),
                                                          keccak256(bytes('1')),
                                                          chainId,
                                                          address(this)
                                                      )
                                                  );
                                              }
                                          
                                              function _mint(address to, uint value) internal {
                                                  totalSupply = totalSupply.add(value);
                                                  balanceOf[to] = balanceOf[to].add(value);
                                                  emit Transfer(address(0), to, value);
                                              }
                                          
                                              function _burn(address from, uint value) internal {
                                                  balanceOf[from] = balanceOf[from].sub(value);
                                                  totalSupply = totalSupply.sub(value);
                                                  emit Transfer(from, address(0), value);
                                              }
                                          
                                              function _approve(address owner, address spender, uint value) private {
                                                  allowance[owner][spender] = value;
                                                  emit Approval(owner, spender, value);
                                              }
                                          
                                              function _transfer(address from, address to, uint value) private {
                                                  balanceOf[from] = balanceOf[from].sub(value);
                                                  balanceOf[to] = balanceOf[to].add(value);
                                                  emit Transfer(from, to, value);
                                              }
                                          
                                              function approve(address spender, uint value) external returns (bool) {
                                                  _approve(msg.sender, spender, value);
                                                  return true;
                                              }
                                          
                                              function transfer(address to, uint value) external returns (bool) {
                                                  _transfer(msg.sender, to, value);
                                                  return true;
                                              }
                                          
                                              function transferFrom(address from, address to, uint value) external returns (bool) {
                                                  if (allowance[from][msg.sender] != uint(-1)) {
                                                      allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                                  }
                                                  _transfer(from, to, value);
                                                  return true;
                                              }
                                          
                                              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                                                  require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                                                  bytes32 digest = keccak256(
                                                      abi.encodePacked(
                                                          '\x19\x01',
                                                          DOMAIN_SEPARATOR,
                                                          keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                                      )
                                                  );
                                                  address recoveredAddress = ecrecover(digest, v, r, s);
                                                  require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                                                  _approve(owner, spender, value);
                                              }
                                          }
                                          
                                          // File: contracts/libraries/Math.sol
                                          
                                          pragma solidity =0.5.16;
                                          
                                          // a library for performing various math operations
                                          
                                          library Math {
                                              function min(uint x, uint y) internal pure returns (uint z) {
                                                  z = x < y ? x : y;
                                              }
                                          
                                              // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                                              function sqrt(uint y) internal pure returns (uint z) {
                                                  if (y > 3) {
                                                      z = y;
                                                      uint x = y / 2 + 1;
                                                      while (x < z) {
                                                          z = x;
                                                          x = (y / x + x) / 2;
                                                      }
                                                  } else if (y != 0) {
                                                      z = 1;
                                                  }
                                              }
                                          }
                                          
                                          // File: contracts/libraries/UQ112x112.sol
                                          
                                          pragma solidity =0.5.16;
                                          
                                          // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                                          
                                          // range: [0, 2**112 - 1]
                                          // resolution: 1 / 2**112
                                          
                                          library UQ112x112 {
                                              uint224 constant Q112 = 2**112;
                                          
                                              // encode a uint112 as a UQ112x112
                                              function encode(uint112 y) internal pure returns (uint224 z) {
                                                  z = uint224(y) * Q112; // never overflows
                                              }
                                          
                                              // divide a UQ112x112 by a uint112, returning a UQ112x112
                                              function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                                                  z = x / uint224(y);
                                              }
                                          }
                                          
                                          // File: contracts/interfaces/IERC20.sol
                                          
                                          pragma solidity >=0.5.0;
                                          
                                          interface IERC20 {
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              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 (uint);
                                              function balanceOf(address owner) external view returns (uint);
                                              function allowance(address owner, address spender) external view returns (uint);
                                          
                                              function approve(address spender, uint value) external returns (bool);
                                              function transfer(address to, uint value) external returns (bool);
                                              function transferFrom(address from, address to, uint value) external returns (bool);
                                          }
                                          
                                          // File: contracts/interfaces/IUniswapV2Factory.sol
                                          
                                          pragma solidity >=0.5.0;
                                          
                                          interface IUniswapV2Factory {
                                              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                                          
                                              function feeTo() external view returns (address);
                                              function feeToSetter() external view returns (address);
                                          
                                              function getPair(address tokenA, address tokenB) external view returns (address pair);
                                              function allPairs(uint) external view returns (address pair);
                                              function allPairsLength() external view returns (uint);
                                          
                                              function createPair(address tokenA, address tokenB) external returns (address pair);
                                          
                                              function setFeeTo(address) external;
                                              function setFeeToSetter(address) external;
                                          }
                                          
                                          // File: contracts/interfaces/IUniswapV2Callee.sol
                                          
                                          pragma solidity >=0.5.0;
                                          
                                          interface IUniswapV2Callee {
                                              function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                                          }
                                          
                                          // File: contracts/UniswapV2Pair.sol
                                          
                                          pragma solidity =0.5.16;
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
                                              using SafeMath  for uint;
                                              using UQ112x112 for uint224;
                                          
                                              uint public constant MINIMUM_LIQUIDITY = 10**3;
                                              bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
                                          
                                              address public factory;
                                              address public token0;
                                              address public token1;
                                          
                                              uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                                              uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                                              uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
                                          
                                              uint public price0CumulativeLast;
                                              uint public price1CumulativeLast;
                                              uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                                          
                                              uint private unlocked = 1;
                                              modifier lock() {
                                                  require(unlocked == 1, 'UniswapV2: LOCKED');
                                                  unlocked = 0;
                                                  _;
                                                  unlocked = 1;
                                              }
                                          
                                              function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                                                  _reserve0 = reserve0;
                                                  _reserve1 = reserve1;
                                                  _blockTimestampLast = blockTimestampLast;
                                              }
                                          
                                              function _safeTransfer(address token, address to, uint value) private {
                                                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                                                  require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                                              }
                                          
                                              event Mint(address indexed sender, uint amount0, uint amount1);
                                              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                              event Swap(
                                                  address indexed sender,
                                                  uint amount0In,
                                                  uint amount1In,
                                                  uint amount0Out,
                                                  uint amount1Out,
                                                  address indexed to
                                              );
                                              event Sync(uint112 reserve0, uint112 reserve1);
                                          
                                              constructor() public {
                                                  factory = msg.sender;
                                              }
                                          
                                              // called once by the factory at time of deployment
                                              function initialize(address _token0, address _token1) external {
                                                  require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                                                  token0 = _token0;
                                                  token1 = _token1;
                                              }
                                          
                                              // update reserves and, on the first call per block, price accumulators
                                              function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                                                  require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                                                  uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                                                  uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                                                  if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                                                      // * never overflows, and + overflow is desired
                                                      price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                                                      price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                                                  }
                                                  reserve0 = uint112(balance0);
                                                  reserve1 = uint112(balance1);
                                                  blockTimestampLast = blockTimestamp;
                                                  emit Sync(reserve0, reserve1);
                                              }
                                          
                                              // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                                              function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                                                  address feeTo = IUniswapV2Factory(factory).feeTo();
                                                  feeOn = feeTo != address(0);
                                                  uint _kLast = kLast; // gas savings
                                                  if (feeOn) {
                                                      if (_kLast != 0) {
                                                          uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                                                          uint rootKLast = Math.sqrt(_kLast);
                                                          if (rootK > rootKLast) {
                                                              uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                                              uint denominator = rootK.mul(5).add(rootKLast);
                                                              uint liquidity = numerator / denominator;
                                                              if (liquidity > 0) _mint(feeTo, liquidity);
                                                          }
                                                      }
                                                  } else if (_kLast != 0) {
                                                      kLast = 0;
                                                  }
                                              }
                                          
                                              // this low-level function should be called from a contract which performs important safety checks
                                              function mint(address to) external lock returns (uint liquidity) {
                                                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                                  uint balance0 = IERC20(token0).balanceOf(address(this));
                                                  uint balance1 = IERC20(token1).balanceOf(address(this));
                                                  uint amount0 = balance0.sub(_reserve0);
                                                  uint amount1 = balance1.sub(_reserve1);
                                          
                                                  bool feeOn = _mintFee(_reserve0, _reserve1);
                                                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                                  if (_totalSupply == 0) {
                                                      liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                                                     _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                                                  } else {
                                                      liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                                                  }
                                                  require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                                                  _mint(to, liquidity);
                                          
                                                  _update(balance0, balance1, _reserve0, _reserve1);
                                                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                                  emit Mint(msg.sender, amount0, amount1);
                                              }
                                          
                                              // this low-level function should be called from a contract which performs important safety checks
                                              function burn(address to) external lock returns (uint amount0, uint amount1) {
                                                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                                  address _token0 = token0;                                // gas savings
                                                  address _token1 = token1;                                // gas savings
                                                  uint balance0 = IERC20(_token0).balanceOf(address(this));
                                                  uint balance1 = IERC20(_token1).balanceOf(address(this));
                                                  uint liquidity = balanceOf[address(this)];
                                          
                                                  bool feeOn = _mintFee(_reserve0, _reserve1);
                                                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                                  amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                                                  amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                                                  require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                                                  _burn(address(this), liquidity);
                                                  _safeTransfer(_token0, to, amount0);
                                                  _safeTransfer(_token1, to, amount1);
                                                  balance0 = IERC20(_token0).balanceOf(address(this));
                                                  balance1 = IERC20(_token1).balanceOf(address(this));
                                          
                                                  _update(balance0, balance1, _reserve0, _reserve1);
                                                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                                  emit Burn(msg.sender, amount0, amount1, to);
                                              }
                                          
                                              // this low-level function should be called from a contract which performs important safety checks
                                              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                                                  require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                                                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                                  require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
                                          
                                                  uint balance0;
                                                  uint balance1;
                                                  { // scope for _token{0,1}, avoids stack too deep errors
                                                  address _token0 = token0;
                                                  address _token1 = token1;
                                                  require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                                                  if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                                                  if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                                                  if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                                                  balance0 = IERC20(_token0).balanceOf(address(this));
                                                  balance1 = IERC20(_token1).balanceOf(address(this));
                                                  }
                                                  uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                                                  uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                                                  require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                                                  { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                                                  uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                                                  uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                                                  require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                                                  }
                                          
                                                  _update(balance0, balance1, _reserve0, _reserve1);
                                                  emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                                              }
                                          
                                              // force balances to match reserves
                                              function skim(address to) external lock {
                                                  address _token0 = token0; // gas savings
                                                  address _token1 = token1; // gas savings
                                                  _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                                                  _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
                                              }
                                          
                                              // force reserves to match balances
                                              function sync() external lock {
                                                  _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
                                              }
                                          }

                                          File 5 of 15: AdminUpgradeabilityProxy
                                          // File: zos-lib/contracts/upgradeability/Proxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @title Proxy
                                           * @dev Implements delegation of calls to other contracts, with proper
                                           * forwarding of return values and bubbling of failures.
                                           * It defines a fallback function that delegates all calls to the address
                                           * returned by the abstract _implementation() internal function.
                                           */
                                          contract Proxy {
                                            /**
                                             * @dev Fallback function.
                                             * Implemented entirely in `_fallback`.
                                             */
                                            function () payable external {
                                              _fallback();
                                            }
                                          
                                            /**
                                             * @return The Address of the implementation.
                                             */
                                            function _implementation() internal view returns (address);
                                          
                                            /**
                                             * @dev Delegates execution to an implementation contract.
                                             * This is a low level function that doesn't return to its internal call site.
                                             * It will return to the external caller whatever the implementation returns.
                                             * @param implementation Address to delegate.
                                             */
                                            function _delegate(address implementation) internal {
                                              assembly {
                                                // Copy msg.data. We take full control of memory in this inline assembly
                                                // block because it will not return to Solidity code. We overwrite the
                                                // Solidity scratch pad at memory position 0.
                                                calldatacopy(0, 0, calldatasize)
                                          
                                                // Call the implementation.
                                                // out and outsize are 0 because we don't know the size yet.
                                                let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
                                          
                                                // Copy the returned data.
                                                returndatacopy(0, 0, returndatasize)
                                          
                                                switch result
                                                // delegatecall returns 0 on error.
                                                case 0 { revert(0, returndatasize) }
                                                default { return(0, returndatasize) }
                                              }
                                            }
                                          
                                            /**
                                             * @dev Function that is run as the first thing in the fallback function.
                                             * Can be redefined in derived contracts to add functionality.
                                             * Redefinitions must call super._willFallback().
                                             */
                                            function _willFallback() internal {
                                            }
                                          
                                            /**
                                             * @dev fallback implementation.
                                             * Extracted to enable manual triggering.
                                             */
                                            function _fallback() internal {
                                              _willFallback();
                                              _delegate(_implementation());
                                            }
                                          }
                                          
                                          // File: zos-lib/contracts/utils/Address.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * Utility library of inline functions on addresses
                                           *
                                           * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
                                           * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
                                           * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
                                           * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
                                           */
                                          library ZOSLibAddress {
                                              /**
                                               * Returns whether the target address is a contract
                                               * @dev This function will return false if invoked during the constructor of a contract,
                                               * as the code is not actually created until after the constructor finishes.
                                               * @param account address of the account to check
                                               * @return whether the target address is a contract
                                               */
                                              function isContract(address account) internal view returns (bool) {
                                                  uint256 size;
                                                  // XXX Currently there is no better way to check if there is a contract in an address
                                                  // than to check the size of the code at that address.
                                                  // See https://ethereum.stackexchange.com/a/14016/36603
                                                  // for more details about how this works.
                                                  // TODO Check this again before the Serenity release, because all addresses will be
                                                  // contracts then.
                                                  // solhint-disable-next-line no-inline-assembly
                                                  assembly { size := extcodesize(account) }
                                                  return size > 0;
                                              }
                                          }
                                          
                                          // File: zos-lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          /**
                                           * @title BaseUpgradeabilityProxy
                                           * @dev This contract implements a proxy that allows to change the
                                           * implementation address to which it will delegate.
                                           * Such a change is called an implementation upgrade.
                                           */
                                          contract BaseUpgradeabilityProxy is Proxy {
                                            /**
                                             * @dev Emitted when the implementation is upgraded.
                                             * @param implementation Address of the new implementation.
                                             */
                                            event Upgraded(address indexed implementation);
                                          
                                            /**
                                             * @dev Storage slot with the address of the current implementation.
                                             * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
                                             * validated in the constructor.
                                             */
                                            bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
                                          
                                            /**
                                             * @dev Returns the current implementation.
                                             * @return Address of the current implementation
                                             */
                                            function _implementation() internal view returns (address impl) {
                                              bytes32 slot = IMPLEMENTATION_SLOT;
                                              assembly {
                                                impl := sload(slot)
                                              }
                                            }
                                          
                                            /**
                                             * @dev Upgrades the proxy to a new implementation.
                                             * @param newImplementation Address of the new implementation.
                                             */
                                            function _upgradeTo(address newImplementation) internal {
                                              _setImplementation(newImplementation);
                                              emit Upgraded(newImplementation);
                                            }
                                          
                                            /**
                                             * @dev Sets the implementation address of the proxy.
                                             * @param newImplementation Address of the new implementation.
                                             */
                                            function _setImplementation(address newImplementation) internal {
                                              require(ZOSLibAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                                          
                                              bytes32 slot = IMPLEMENTATION_SLOT;
                                          
                                              assembly {
                                                sstore(slot, newImplementation)
                                              }
                                            }
                                          }
                                          
                                          // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          /**
                                           * @title UpgradeabilityProxy
                                           * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
                                           * implementation and init data.
                                           */
                                          contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
                                            /**
                                             * @dev Contract constructor.
                                             * @param _logic Address of the initial implementation.
                                             * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
                                             * It should include the signature and the parameters of the function to be called, as described in
                                             * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                                             * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
                                             */
                                            constructor(address _logic, bytes memory _data) public payable {
                                              assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
                                              _setImplementation(_logic);
                                              if(_data.length > 0) {
                                                (bool success,) = _logic.delegatecall(_data);
                                                require(success);
                                              }
                                            }  
                                          }
                                          
                                          // File: zos-lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          /**
                                           * @title BaseAdminUpgradeabilityProxy
                                           * @dev This contract combines an upgradeability proxy with an authorization
                                           * mechanism for administrative tasks.
                                           * All external functions in this contract must be guarded by the
                                           * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                                           * feature proposal that would enable this to be done automatically.
                                           */
                                          contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
                                            /**
                                             * @dev Emitted when the administration has been transferred.
                                             * @param previousAdmin Address of the previous admin.
                                             * @param newAdmin Address of the new admin.
                                             */
                                            event AdminChanged(address previousAdmin, address newAdmin);
                                          
                                            /**
                                             * @dev Storage slot with the admin of the contract.
                                             * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
                                             * validated in the constructor.
                                             */
                                            bytes32 internal constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
                                          
                                            /**
                                             * @dev Modifier to check whether the `msg.sender` is the admin.
                                             * If it is, it will run the function. Otherwise, it will delegate the call
                                             * to the implementation.
                                             */
                                            modifier ifAdmin() {
                                              if (msg.sender == _admin()) {
                                                _;
                                              } else {
                                                _fallback();
                                              }
                                            }
                                          
                                            /**
                                             * @return The address of the proxy admin.
                                             */
                                            function admin() external ifAdmin returns (address) {
                                              return _admin();
                                            }
                                          
                                            /**
                                             * @return The address of the implementation.
                                             */
                                            function implementation() external ifAdmin returns (address) {
                                              return _implementation();
                                            }
                                          
                                            /**
                                             * @dev Changes the admin of the proxy.
                                             * Only the current admin can call this function.
                                             * @param newAdmin Address to transfer proxy administration to.
                                             */
                                            function changeAdmin(address newAdmin) external ifAdmin {
                                              require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                                              emit AdminChanged(_admin(), newAdmin);
                                              _setAdmin(newAdmin);
                                            }
                                          
                                            /**
                                             * @dev Upgrade the backing implementation of the proxy.
                                             * Only the admin can call this function.
                                             * @param newImplementation Address of the new implementation.
                                             */
                                            function upgradeTo(address newImplementation) external ifAdmin {
                                              _upgradeTo(newImplementation);
                                            }
                                          
                                            /**
                                             * @dev Upgrade the backing implementation of the proxy and call a function
                                             * on the new implementation.
                                             * This is useful to initialize the proxied contract.
                                             * @param newImplementation Address of the new implementation.
                                             * @param data Data to send as msg.data in the low level call.
                                             * It should include the signature and the parameters of the function to be called, as described in
                                             * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                                             */
                                            function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
                                              _upgradeTo(newImplementation);
                                              (bool success,) = newImplementation.delegatecall(data);
                                              require(success);
                                            }
                                          
                                            /**
                                             * @return The admin slot.
                                             */
                                            function _admin() internal view returns (address adm) {
                                              bytes32 slot = ADMIN_SLOT;
                                              assembly {
                                                adm := sload(slot)
                                              }
                                            }
                                          
                                            /**
                                             * @dev Sets the address of the proxy admin.
                                             * @param newAdmin Address of the new proxy admin.
                                             */
                                            function _setAdmin(address newAdmin) internal {
                                              bytes32 slot = ADMIN_SLOT;
                                          
                                              assembly {
                                                sstore(slot, newAdmin)
                                              }
                                            }
                                          
                                            /**
                                             * @dev Only fall back when the sender is not the admin.
                                             */
                                            function _willFallback() internal {
                                              require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                                              super._willFallback();
                                            }
                                          }
                                          
                                          // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          /**
                                           * @title AdminUpgradeabilityProxy
                                           * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for 
                                           * initializing the implementation, admin, and init data.
                                           */
                                          contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
                                            /**
                                             * Contract constructor.
                                             * @param _logic address of the initial implementation.
                                             * @param _admin Address of the proxy administrator.
                                             * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
                                             * It should include the signature and the parameters of the function to be called, as described in
                                             * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                                             * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
                                             */
                                            constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
                                              assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
                                              _setAdmin(_admin);
                                            }
                                          }

                                          File 6 of 15: ChiToken
                                          /*
                                                                                                           ,╖╗#▒▓▓▓▓▓╣╬╣▓▓▓▓▒#╗╗╓,
                                                                                                     ,╗@▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╗╖
                                                                                                 ╓#▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╠╠▄╣╝╜"""╙╙▀╝╝╣╬╬╬╬▓▌╖
                                                                                              ╓▓╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀`╓å▓▓▓╙  ,▄▓▓██▓▓▓▄▄▄▄▄╠╠╙╠▄▄
                                                                                           ╓@╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌  ê`'     *▀▀▀▀▀▀▀▓██████████████▄
                                                                                         ╔▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬                      ╙▀████████████▌
                                                                                       ╓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬                         ╙████████████▌
                                                                                     ,▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▀                          ╗▄█████████████▄
                                                                                    é╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌   #╙                       ╙▀█████████████▓
                                                                                   ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀              ╙▓╬╣▓▄            ╙▀▀███████████µ
                                                                                  ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀╣╝╙             ╒▓╬╬╬╬╬╬▓         ╙████████████████µ
                                                                                 ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌              ╖╖╖▄▓╬╬╬╬╬╬╬▓         █████████████████µ
                                                                                ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬        ,#▓╣╬╬▓╬╬╬╬╬╬╬╬╬╬╬╬▌         ▓█████████████████
                                                                               ]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╓╖     ]╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣╨          ██████████████████▌
                                                                               ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌╖,   ╙╠╠▓╬╬╬╬╬╬╬╬╬▓╝╙           ╫███████████████████
                                                                              ]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙              ▓████████████████████▌
                                                                              ║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙`                 ▄███████████████████████
                                                                              ╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╝▀╙                     ,▄█████████████████████████
                                                                              ╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝╜`                       ▄▓████████████████████████████
                                                                              ║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣▀`                     ,▄▄▓████████████████████████████████
                                                                              ▐╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙                       ,,,▄╠▓██████████████████████████████▌
                                                                               ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙╔▒`               ╓▄▓████████████████████████████████████████⌐
                                                                               ╚╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╣▓              ▄▓████████████████████████████████████████████
                                                                                ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬             ▄██████████████████████████████████████████████⌐
                                                                                 ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╛           ▄███████████████████████████████████████████████▌
                                                                                 └╣╬╬╬╬╬╬╬╬╬╬╬▓           ▄███████████████████████████████████████████████▌
                                                                                  └▓╬╬╬╬╬╬╬╬╬╬Γ          ]███████████████████████████████████████████████▀
                                                                                    ╣╬╬╬╬╬╬╬╬╬⌐          ╫████████████████████████████████▀▀▀▀▀▓████████╜
                                                                                     ╙╬╬╬╬╬╬╬╬⌐          ╟███████████████████████████▀╙    ,▄▓▓▓▓▓████▓
                                                                                       ╫╬╬╬╬╬╬b           ████████████████████████▀`    ,Φ▀▀█████████╙
                                                                                         ╫╬╬╬╬▌╟           ██████████████████▀╓▀─       ▄▓█████████▀
                                                                                           ╚╣╬▓╣▓           └▀████████████▀`         ╓▓█████████▓╙
                                                                                             ╙╝╬╬▓             .▄▄▓█▀▀▀`           ▄▓█████████▀
                                                                                                ╙▀▓▄                            ƒ,▓███████▀▀
                                                                                                    "                        ╓▓█▓█████▀▀└
                                                                                                                         ╓▄▓████▀▀╙└
                                          
                                           ██████╗██╗  ██╗██╗     ██████╗  █████╗ ███████╗████████╗ ██████╗ ██╗  ██╗███████╗███╗   ██╗    ██████╗ ██╗   ██╗     ██╗██╗███╗   ██╗ ██████╗██╗  ██╗
                                          ██╔════╝██║  ██║██║    ██╔════╝ ██╔══██╗██╔════╝╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗  ██║    ██╔══██╗╚██╗ ██╔╝    ███║██║████╗  ██║██╔════╝██║  ██║
                                          ██║     ███████║██║    ██║  ███╗███████║███████╗   ██║   ██║   ██║█████╔╝ █████╗  ██╔██╗ ██║    ██████╔╝ ╚████╔╝     ╚██║██║██╔██╗ ██║██║     ███████║
                                          ██║     ██╔══██║██║    ██║   ██║██╔══██║╚════██║   ██║   ██║   ██║██╔═██╗ ██╔══╝  ██║╚██╗██║    ██╔══██╗  ╚██╔╝       ██║██║██║╚██╗██║██║     ██╔══██║
                                          ╚██████╗██║  ██║██║    ╚██████╔╝██║  ██║███████║   ██║   ╚██████╔╝██║  ██╗███████╗██║ ╚████║    ██████╔╝   ██║        ██║██║██║ ╚████║╚██████╗██║  ██║
                                           ╚═════╝╚═╝  ╚═╝╚═╝     ╚═════╝ ╚═╝  ╚═╝╚══════╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝    ╚═════╝    ╚═╝        ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝╚═╝  ╚═╝
                                          
                                                                                                       Copyright by 1inch Corporation
                                                                                                           https://1inch.exchange
                                          
                                          ---
                                          Deployer wallet address:
                                          0x7E1E3334130355799F833ffec2D731BCa3E68aF6
                                          
                                          Signed raw transaction for chainId 1:
                                          0xf90d7f808506fc23ac00830bd0fa8080b90d2c608060405234801561001057600080fd5b50610d0c806100206000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c806370a08231116100a2578063a9059cbb11610071578063a9059cbb14610305578063b0ac19a014610331578063d89135cd1461036a578063d8ccd0f314610372578063dd62ed3e1461038f5761010b565b806370a08231146102b057806395d89b41146102d6578063a0712d68146102de578063a2309ff8146102fd5761010b565b806323b872dd116100de57806323b872dd14610213578063313ce567146102495780635f2e2b45146102675780636366b936146102935761010b565b806306fdde0314610110578063079d229f1461018d578063095ea7b3146101cb57806318160ddd1461020b575b600080fd5b6101186103bd565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561015257818101518382015260200161013a565b50505050905090810190601f16801561017f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101b9600480360360408110156101a357600080fd5b506001600160a01b0381351690602001356103ee565b60408051918252519081900360200190f35b6101f7600480360360408110156101e157600080fd5b506001600160a01b03813516906020013561041f565b604080519115158252519081900360200190f35b6101b9610435565b6101f76004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610453565b6102516104c2565b6040805160ff9092168252519081900360200190f35b6101b96004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356104c7565b6101b9600480360360208110156102a957600080fd5b50356104e2565b6101b9600480360360208110156102c657600080fd5b50356001600160a01b03166104ff565b61011861051a565b6102fb600480360360208110156102f457600080fd5b5035610539565b005b6101b961070d565b6101f76004803603604081101561031b57600080fd5b506001600160a01b038135169060200135610713565b61034e6004803603602081101561034757600080fd5b5035610720565b604080516001600160a01b039092168252519081900360200190f35b6101b961078b565b6101b96004803603602081101561038857600080fd5b5035610791565b6101b9600480360360408110156103a557600080fd5b506001600160a01b03813581169160200135166107aa565b60405180604001604052806015815260200174086d0d2408ec2e6e8ded6cadc40c4f24062d2dcc6d605b1b81525081565b60006104188361041361040985610404886104ff565b6107d5565b61040487336107aa565b6104c7565b9392505050565b600061042c3384846107eb565b50600192915050565b600061044e60035460025461084d90919063ffffffff16565b905090565b600061046084848461088f565b6104b884336104b385604051806060016040528060288152602001610c8b602891396001600160a01b038a166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b6107eb565b5060019392505050565b600081565b60006104d383836109f8565b6104dc82610a59565b50919050565b60006104f96104f483610404336104ff565b610791565b92915050565b6001600160a01b031660009081526020819052604090205490565b6040518060400160405280600381526020016243484960e81b81525081565b6002547f746d4946c0e9f43f4dee607b0ef1fa1c3318585733ff6000526015600bf30000600052602082045b80156106d85781601e600080f55060018201601e600080f55060028201601e600080f55060038201601e600080f55060048201601e600080f55060058201601e600080f55060068201601e600080f55060078201601e600080f55060088201601e600080f55060098201601e600080f550600a8201601e600080f550600b8201601e600080f550600c8201601e600080f550600d8201601e600080f550600e8201601e600080f550600f8201601e600080f55060108201601e600080f55060118201601e600080f55060128201601e600080f55060138201601e600080f55060148201601e600080f55060158201601e600080f55060168201601e600080f55060178201601e600080f55060188201601e600080f55060198201601e600080f550601a8201601e600080f550601b8201601e600080f550601c8201601e600080f550601d8201601e600080f550601e8201601e600080f550601f8201601e600080f5506020919091019060001901610565565b50601f82165b80156106fc5781601e600080f55060019190910190600019016106de565b506107073383610ad1565b60025550565b60025481565b600061042c33848461088f565b604080516001600160f81b03196020808301919091523060601b602183015260358201939093527f3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348605580830191909152825180830390910181526075909101909152805191012090565b60035481565b600061079d3383610b50565b6107a682610a59565b5090565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60008183106107e45781610418565b5090919050565b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600061041883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610961565b6108d281604051806060016040528060268152602001610c65602691396001600160a01b038616600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610907908263ffffffff610be816565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156109f05760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156109b557818101518382015260200161099d565b50505050905090810190601f1680156109e25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b610a028282610b50565b610a5582336104b384604051806060016040528060248152602001610cb3602491396001600160a01b0388166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b5050565b60035460005b82811015610aca57610a72818301610720565b6040516001600160a01b039190911690600081818181865af19150503d8060008114610aba576040519150601f19603f3d011682016040523d82523d6000602084013e610abf565b606091505b505050600101610a5f565b5001600355565b6001600160a01b038216600090815260208190526040902054610afa908263ffffffff610be816565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b610b9381604051806060016040528060228152602001610c43602291396001600160a01b038516600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038316600081815260208181526040808320949094558351858152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35050565b600082820183811015610418576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fdfe45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e6365a2646970667358221220687f814fb4c0b3c6abd66ebdb1f1eabcf69becf92a382c3af453e0b21c3d15b564736f6c6343000608003325a00ed87a047b4e415bd7f8cf7a7ce5a1c204125df1cedc35c7bdcb71bd2a29a35ea02db2490337fa6c425f1b3d74b7b217de8b394adb3f571827629c06dc16364b66
                                          ---
                                          */
                                          // File: @openzeppelin/contracts/math/Math.sol
                                          
                                          pragma solidity ^0.6.0;
                                          
                                          /**
                                           * @dev Standard math utilities missing in the Solidity language.
                                           */
                                          library Math {
                                              /**
                                               * @dev Returns the largest of two numbers.
                                               */
                                              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                                                  return a >= b ? a : b;
                                              }
                                          
                                              /**
                                               * @dev Returns the smallest of two numbers.
                                               */
                                              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                                  return a < b ? a : b;
                                              }
                                          
                                              /**
                                               * @dev Returns the average of two numbers. The result is rounded towards
                                               * zero.
                                               */
                                              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                                  // (a + b) / 2 can overflow, so we distribute
                                                  return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.6.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, 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) {
                                                  return sub(a, b, "SafeMath: subtraction overflow");
                                              }
                                          
                                              /**
                                               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                               * overflow (when the result is negative).
                                               *
                                               * 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);
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  return div(a, b, "SafeMath: division by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, errorMessage);
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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) {
                                                  return mod(a, b, "SafeMath: modulo by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts with custom message 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, 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;
                                          
                                          /**
                                           * @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: contracts/ChiToken.sol
                                          
                                          pragma solidity ^0.6.0;
                                          
                                          
                                          
                                          
                                          
                                          abstract contract ERC20WithoutTotalSupply is IERC20 {
                                              using SafeMath for uint256;
                                          
                                              mapping(address => uint256) private _balances;
                                              mapping(address => mapping(address => uint256)) private _allowances;
                                          
                                              function balanceOf(address account) public view override returns (uint256) {
                                                  return _balances[account];
                                              }
                                          
                                              function allowance(address owner, address spender) public view override returns (uint256) {
                                                  return _allowances[owner][spender];
                                              }
                                          
                                              function transfer(address recipient, uint256 amount) public override returns (bool) {
                                                  _transfer(msg.sender, recipient, amount);
                                                  return true;
                                              }
                                          
                                              function approve(address spender, uint256 amount) public override returns (bool) {
                                                  _approve(msg.sender, spender, amount);
                                                  return true;
                                              }
                                          
                                              function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
                                                  _transfer(sender, recipient, amount);
                                                  _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
                                                  return true;
                                              }
                                          
                                              function _transfer(address sender, address recipient, uint256 amount) internal {
                                                  _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                                                  _balances[recipient] = _balances[recipient].add(amount);
                                                  emit Transfer(sender, recipient, amount);
                                              }
                                          
                                              function _approve(address owner, address spender, uint256 amount) internal {
                                                  _allowances[owner][spender] = amount;
                                                  emit Approval(owner, spender, amount);
                                              }
                                          
                                              function _mint(address account, uint256 amount) internal {
                                                  _balances[account] = _balances[account].add(amount);
                                                  emit Transfer(address(0), account, amount);
                                              }
                                          
                                              function _burn(address account, uint256 amount) internal {
                                                  _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                                                  emit Transfer(account, address(0), amount);
                                              }
                                          
                                              function _burnFrom(address account, uint256 amount) internal {
                                                  _burn(account, amount);
                                                  _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance"));
                                              }
                                          }
                                          
                                          
                                          contract ChiToken is IERC20, ERC20WithoutTotalSupply {
                                              string constant public name = "Chi Gastoken by 1inch";
                                              string constant public symbol = "CHI";
                                              uint8 constant public decimals = 0;
                                          
                                              uint256 public totalMinted;
                                              uint256 public totalBurned;
                                          
                                              function totalSupply() public view override returns(uint256) {
                                                  return totalMinted.sub(totalBurned);
                                              }
                                          
                                              function mint(uint256 value) public {
                                                  uint256 offset = totalMinted;
                                                  assembly {
                                                      mstore(0, 0x746d4946c0e9F43F4Dee607b0eF1fA1c3318585733ff6000526015600bf30000)
                                          
                                                      for {let i := div(value, 32)} i {i := sub(i, 1)} {
                                                          pop(create2(0, 0, 30, add(offset, 0))) pop(create2(0, 0, 30, add(offset, 1)))
                                                          pop(create2(0, 0, 30, add(offset, 2))) pop(create2(0, 0, 30, add(offset, 3)))
                                                          pop(create2(0, 0, 30, add(offset, 4))) pop(create2(0, 0, 30, add(offset, 5)))
                                                          pop(create2(0, 0, 30, add(offset, 6))) pop(create2(0, 0, 30, add(offset, 7)))
                                                          pop(create2(0, 0, 30, add(offset, 8))) pop(create2(0, 0, 30, add(offset, 9)))
                                                          pop(create2(0, 0, 30, add(offset, 10))) pop(create2(0, 0, 30, add(offset, 11)))
                                                          pop(create2(0, 0, 30, add(offset, 12))) pop(create2(0, 0, 30, add(offset, 13)))
                                                          pop(create2(0, 0, 30, add(offset, 14))) pop(create2(0, 0, 30, add(offset, 15)))
                                                          pop(create2(0, 0, 30, add(offset, 16))) pop(create2(0, 0, 30, add(offset, 17)))
                                                          pop(create2(0, 0, 30, add(offset, 18))) pop(create2(0, 0, 30, add(offset, 19)))
                                                          pop(create2(0, 0, 30, add(offset, 20))) pop(create2(0, 0, 30, add(offset, 21)))
                                                          pop(create2(0, 0, 30, add(offset, 22))) pop(create2(0, 0, 30, add(offset, 23)))
                                                          pop(create2(0, 0, 30, add(offset, 24))) pop(create2(0, 0, 30, add(offset, 25)))
                                                          pop(create2(0, 0, 30, add(offset, 26))) pop(create2(0, 0, 30, add(offset, 27)))
                                                          pop(create2(0, 0, 30, add(offset, 28))) pop(create2(0, 0, 30, add(offset, 29)))
                                                          pop(create2(0, 0, 30, add(offset, 30))) pop(create2(0, 0, 30, add(offset, 31)))
                                                          offset := add(offset, 32)
                                                      }
                                          
                                                      for {let i := and(value, 0x1F)} i {i := sub(i, 1)} {
                                                          pop(create2(0, 0, 30, offset))
                                                          offset := add(offset, 1)
                                                      }
                                                  }
                                          
                                                  _mint(msg.sender, value);
                                                  totalMinted = offset;
                                              }
                                          
                                              function computeAddress2(uint256 salt) public view returns (address) {
                                                  bytes32 _data = keccak256(
                                                      abi.encodePacked(bytes1(0xff), address(this), salt, bytes32(0x3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348))
                                                  );
                                                  return address(uint256(_data));
                                              }
                                          
                                              function _destroyChildren(uint256 value) internal {
                                                  uint256 _totalBurned = totalBurned;
                                                  for (uint256 i = 0; i < value; i++) {
                                                      computeAddress2(_totalBurned + i).call("");
                                                  }
                                                  totalBurned = _totalBurned + value;
                                              }
                                          
                                              function free(uint256 value) public returns (uint256)  {
                                                  _burn(msg.sender, value);
                                                  _destroyChildren(value);
                                                  return value;
                                              }
                                          
                                              function freeUpTo(uint256 value) public returns (uint256) {
                                                  return free(Math.min(value, balanceOf(msg.sender)));
                                              }
                                          
                                              function freeFrom(address from, uint256 value) public returns (uint256) {
                                                  _burnFrom(from, value);
                                                  _destroyChildren(value);
                                                  return value;
                                              }
                                          
                                              function freeFromUpTo(address from, uint256 value) public returns (uint256) {
                                                  return freeFrom(from, Math.min(Math.min(value, balanceOf(from)), allowance(from, msg.sender)));
                                              }
                                          }

                                          File 7 of 15: GasToken2
                                          pragma solidity ^0.4.10;
                                          
                                          contract GasToken2 {
                                              //////////////////////////////////////////////////////////////////////////
                                              // RLP.sol
                                              // Due to some unexplained bug, we get a slightly different bytecode if 
                                              // we use an import, and are then unable to verify the code in Etherscan
                                              //////////////////////////////////////////////////////////////////////////
                                              
                                              uint256 constant ADDRESS_BYTES = 20;
                                              uint256 constant MAX_SINGLE_BYTE = 128;
                                              uint256 constant MAX_NONCE = 256**9 - 1;
                                          
                                              // count number of bytes required to represent an unsigned integer
                                              function count_bytes(uint256 n) constant internal returns (uint256 c) {
                                                  uint i = 0;
                                                  uint mask = 1;
                                                  while (n >= mask) {
                                                      i += 1;
                                                      mask *= 256;
                                                  }
                                          
                                                  return i;
                                              }
                                          
                                              function mk_contract_address(address a, uint256 n) constant internal returns (address rlp) {
                                                  /*
                                                   * make sure the RLP encoding fits in one word:
                                                   * total_length      1 byte
                                                   * address_length    1 byte
                                                   * address          20 bytes
                                                   * nonce_length      1 byte (or 0)
                                                   * nonce           1-9 bytes
                                                   *                ==========
                                                   *                24-32 bytes
                                                   */
                                                  require(n <= MAX_NONCE);
                                          
                                                  // number of bytes required to write down the nonce
                                                  uint256 nonce_bytes;
                                                  // length in bytes of the RLP encoding of the nonce
                                                  uint256 nonce_rlp_len;
                                          
                                                  if (0 < n && n < MAX_SINGLE_BYTE) {
                                                      // nonce fits in a single byte
                                                      // RLP(nonce) = nonce
                                                      nonce_bytes = 1;
                                                      nonce_rlp_len = 1;
                                                  } else {
                                                      // RLP(nonce) = [num_bytes_in_nonce nonce]
                                                      nonce_bytes = count_bytes(n);
                                                      nonce_rlp_len = nonce_bytes + 1;
                                                  }
                                          
                                                  // [address_length(1) address(20) nonce_length(0 or 1) nonce(1-9)]
                                                  uint256 tot_bytes = 1 + ADDRESS_BYTES + nonce_rlp_len;
                                          
                                                  // concatenate all parts of the RLP encoding in the leading bytes of
                                                  // one 32-byte word
                                                  uint256 word = ((192 + tot_bytes) * 256**31) +
                                                                 ((128 + ADDRESS_BYTES) * 256**30) +
                                                                 (uint256(a) * 256**10);
                                          
                                                  if (0 < n && n < MAX_SINGLE_BYTE) {
                                                      word += n * 256**9;
                                                  } else {
                                                      word += (128 + nonce_bytes) * 256**9;
                                                      word += n * 256**(9 - nonce_bytes);
                                                  }
                                          
                                                  uint256 hash;
                                          
                                                  assembly {
                                                      let mem_start := mload(0x40)        // get a pointer to free memory
                                                      mstore(0x40, add(mem_start, 0x20))  // update the pointer
                                          
                                                      mstore(mem_start, word)             // store the rlp encoding
                                                      hash := sha3(mem_start,
                                                                   add(tot_bytes, 1))     // hash the rlp encoding
                                                  }
                                          
                                                  // interpret hash as address (20 least significant bytes)
                                                  return address(hash);
                                              }
                                              
                                              //////////////////////////////////////////////////////////////////////////
                                              // Generic ERC20
                                              //////////////////////////////////////////////////////////////////////////
                                          
                                              // owner -> amount
                                              mapping(address => uint256) s_balances;
                                              // owner -> spender -> max amount
                                              mapping(address => mapping(address => uint256)) s_allowances;
                                          
                                              event Transfer(address indexed from, address indexed to, uint256 value);
                                          
                                              event Approval(address indexed owner, address indexed spender, uint256 value);
                                          
                                              // Spec: Get the account balance of another account with address `owner`
                                              function balanceOf(address owner) public constant returns (uint256 balance) {
                                                  return s_balances[owner];
                                              }
                                          
                                              function internalTransfer(address from, address to, uint256 value) internal returns (bool success) {
                                                  if (value <= s_balances[from]) {
                                                      s_balances[from] -= value;
                                                      s_balances[to] += value;
                                                      Transfer(from, to, value);
                                                      return true;
                                                  } else {
                                                      return false;
                                                  }
                                              }
                                          
                                              // Spec: Send `value` amount of tokens to address `to`
                                              function transfer(address to, uint256 value) public returns (bool success) {
                                                  address from = msg.sender;
                                                  return internalTransfer(from, to, value);
                                              }
                                          
                                              // Spec: Send `value` amount of tokens from address `from` to address `to`
                                              function transferFrom(address from, address to, uint256 value) public returns (bool success) {
                                                  address spender = msg.sender;
                                                  if(value <= s_allowances[from][spender] && internalTransfer(from, to, value)) {
                                                      s_allowances[from][spender] -= value;
                                                      return true;
                                                  } else {
                                                      return false;
                                                  }
                                              }
                                          
                                              // Spec: Allow `spender` to withdraw from your account, multiple times, up
                                              // to the `value` amount. If this function is called again it overwrites the
                                              // current allowance with `value`.
                                              function approve(address spender, uint256 value) public returns (bool success) {
                                                  address owner = msg.sender;
                                                  if (value != 0 && s_allowances[owner][spender] != 0) {
                                                      return false;
                                                  }
                                                  s_allowances[owner][spender] = value;
                                                  Approval(owner, spender, value);
                                                  return true;
                                              }
                                          
                                              // Spec: Returns the `amount` which `spender` is still allowed to withdraw
                                              // from `owner`.
                                              // What if the allowance is higher than the balance of the `owner`?
                                              // Callers should be careful to use min(allowance, balanceOf) to make sure
                                              // that the allowance is actually present in the account!
                                              function allowance(address owner, address spender) public constant returns (uint256 remaining) {
                                                  return s_allowances[owner][spender];
                                              }
                                          
                                              //////////////////////////////////////////////////////////////////////////
                                              // GasToken specifics
                                              //////////////////////////////////////////////////////////////////////////
                                          
                                              uint8 constant public decimals = 2;
                                              string constant public name = "Gastoken.io";
                                              string constant public symbol = "GST2";
                                          
                                              // We build a queue of nonces at which child contracts are stored. s_head is
                                              // the nonce at the head of the queue, s_tail is the nonce behind the tail
                                              // of the queue. The queue grows at the head and shrinks from the tail.
                                              // Note that when and only when a contract CREATEs another contract, the
                                              // creating contract's nonce is incremented.
                                              // The first child contract is created with nonce == 1, the second child
                                              // contract is created with nonce == 2, and so on...
                                              // For example, if there are child contracts at nonces [2,3,4],
                                              // then s_head == 4 and s_tail == 1. If there are no child contracts,
                                              // s_head == s_tail.
                                              uint256 s_head;
                                              uint256 s_tail;
                                          
                                              // totalSupply gives  the number of tokens currently in existence
                                              // Each token corresponds to one child contract that can be SELFDESTRUCTed
                                              // for a gas refund.
                                              function totalSupply() public constant returns (uint256 supply) {
                                                  return s_head - s_tail;
                                              }
                                          
                                              // Creates a child contract that can only be destroyed by this contract.
                                              function makeChild() internal returns (address addr) {
                                                  assembly {
                                                      // EVM assembler of runtime portion of child contract:
                                                      //     ;; Pseudocode: if (msg.sender != 0x0000000000b3f879cb30fe243b4dfee438691c04) { throw; }
                                                      //     ;;             suicide(msg.sender)
                                                      //     PUSH15 0xb3f879cb30fe243b4dfee438691c04 ;; hardcoded address of this contract
                                                      //     CALLER
                                                      //     XOR
                                                      //     PC
                                                      //     JUMPI
                                                      //     CALLER
                                                      //     SELFDESTRUCT
                                                      // Or in binary: 6eb3f879cb30fe243b4dfee438691c043318585733ff
                                                      // Since the binary is so short (22 bytes), we can get away
                                                      // with a very simple initcode:
                                                      //     PUSH22 0x6eb3f879cb30fe243b4dfee438691c043318585733ff
                                                      //     PUSH1 0
                                                      //     MSTORE ;; at this point, memory locations mem[10] through
                                                      //            ;; mem[31] contain the runtime portion of the child
                                                      //            ;; contract. all that's left to do is to RETURN this
                                                      //            ;; chunk of memory.
                                                      //     PUSH1 22 ;; length
                                                      //     PUSH1 10 ;; offset
                                                      //     RETURN
                                                      // Or in binary: 756eb3f879cb30fe243b4dfee438691c043318585733ff6000526016600af3
                                                      // Almost done! All we have to do is put this short (31 bytes) blob into
                                                      // memory and call CREATE with the appropriate offsets.
                                                      let solidity_free_mem_ptr := mload(0x40)
                                                      mstore(solidity_free_mem_ptr, 0x00756eb3f879cb30fe243b4dfee438691c043318585733ff6000526016600af3)
                                                      addr := create(0, add(solidity_free_mem_ptr, 1), 31)
                                                  }
                                              }
                                          
                                              // Mints `value` new sub-tokens (e.g. cents, pennies, ...) by creating `value`
                                              // new child contracts. The minted tokens are owned by the caller of this
                                              // function.
                                              function mint(uint256 value) public {
                                                  for (uint256 i = 0; i < value; i++) {
                                                      makeChild();
                                                  }
                                                  s_head += value;
                                                  s_balances[msg.sender] += value;
                                              }
                                          
                                              // Destroys `value` child contracts and updates s_tail.
                                              //
                                              // This function is affected by an issue in solc: https://github.com/ethereum/solidity/issues/2999
                                              // The `mk_contract_address(this, i).call();` doesn't forward all available gas, but only GAS - 25710.
                                              // As a result, when this line is executed with e.g. 30000 gas, the callee will have less than 5000 gas
                                              // available and its SELFDESTRUCT operation will fail leading to no gas refund occurring.
                                              // The remaining ~29000 gas left after the call is enough to update s_tail and the caller's balance.
                                              // Hence tokens will have been destroyed without a commensurate gas refund.
                                              // Fortunately, there is a simple workaround:
                                              // Whenever you call free, freeUpTo, freeFrom, or freeUpToFrom, ensure that you pass at least
                                              // 25710 + `value` * (1148 + 5722 + 150) gas. (It won't all be used)
                                              function destroyChildren(uint256 value) internal {
                                                  uint256 tail = s_tail;
                                                  // tail points to slot behind the last contract in the queue
                                                  for (uint256 i = tail + 1; i <= tail + value; i++) {
                                                      mk_contract_address(this, i).call();
                                                  }
                                          
                                                  s_tail = tail + value;
                                              }
                                          
                                              // Frees `value` sub-tokens (e.g. cents, pennies, ...) belonging to the
                                              // caller of this function by destroying `value` child contracts, which
                                              // will trigger a partial gas refund.
                                              // You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
                                              // when calling this function. For details, see the comment above `destroyChilden`.
                                              function free(uint256 value) public returns (bool success) {
                                                  uint256 from_balance = s_balances[msg.sender];
                                                  if (value > from_balance) {
                                                      return false;
                                                  }
                                          
                                                  destroyChildren(value);
                                          
                                                  s_balances[msg.sender] = from_balance - value;
                                          
                                                  return true;
                                              }
                                          
                                              // Frees up to `value` sub-tokens. Returns how many tokens were freed.
                                              // Otherwise, identical to free.
                                              // You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
                                              // when calling this function. For details, see the comment above `destroyChilden`.
                                              function freeUpTo(uint256 value) public returns (uint256 freed) {
                                                  uint256 from_balance = s_balances[msg.sender];
                                                  if (value > from_balance) {
                                                      value = from_balance;
                                                  }
                                          
                                                  destroyChildren(value);
                                          
                                                  s_balances[msg.sender] = from_balance - value;
                                          
                                                  return value;
                                              }
                                          
                                              // Frees `value` sub-tokens owned by address `from`. Requires that `msg.sender`
                                              // has been approved by `from`.
                                              // You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
                                              // when calling this function. For details, see the comment above `destroyChilden`.
                                              function freeFrom(address from, uint256 value) public returns (bool success) {
                                                  address spender = msg.sender;
                                                  uint256 from_balance = s_balances[from];
                                                  if (value > from_balance) {
                                                      return false;
                                                  }
                                          
                                                  mapping(address => uint256) from_allowances = s_allowances[from];
                                                  uint256 spender_allowance = from_allowances[spender];
                                                  if (value > spender_allowance) {
                                                      return false;
                                                  }
                                          
                                                  destroyChildren(value);
                                          
                                                  s_balances[from] = from_balance - value;
                                                  from_allowances[spender] = spender_allowance - value;
                                          
                                                  return true;
                                              }
                                          
                                              // Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed.
                                              // Otherwise, identical to `freeFrom`.
                                              // You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas
                                              // when calling this function. For details, see the comment above `destroyChilden`.
                                              function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) {
                                                  address spender = msg.sender;
                                                  uint256 from_balance = s_balances[from];
                                                  if (value > from_balance) {
                                                      value = from_balance;
                                                  }
                                          
                                                  mapping(address => uint256) from_allowances = s_allowances[from];
                                                  uint256 spender_allowance = from_allowances[spender];
                                                  if (value > spender_allowance) {
                                                      value = spender_allowance;
                                                  }
                                          
                                                  destroyChildren(value);
                                          
                                                  s_balances[from] = from_balance - value;
                                                  from_allowances[spender] = spender_allowance - value;
                                          
                                                  return value;
                                              }
                                          }

                                          File 8 of 15: OneSplitWrap
                                          // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see {ERC20Detailed}.
                                           */
                                          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: contracts/IOneSplit.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          //
                                          //  [ msg.sender ]
                                          //       | |
                                          //       | |
                                          //       \_/
                                          // +---------------+ ________________________________
                                          // | OneSplitAudit | _______________________________  \
                                          // +---------------+                                 \ \
                                          //       | |                      ______________      | | (staticcall)
                                          //       | |                    /  ____________  \    | |
                                          //       | | (call)            / /              \ \   | |
                                          //       | |                  / /               | |   | |
                                          //       \_/                  | |               \_/   \_/
                                          // +--------------+           | |           +----------------------+
                                          // | OneSplitWrap |           | |           |   OneSplitViewWrap   |
                                          // +--------------+           | |           +----------------------+
                                          //       | |                  | |                     | |
                                          //       | | (delegatecall)   | | (staticcall)        | | (staticcall)
                                          //       \_/                  | |                     \_/
                                          // +--------------+           | |             +------------------+
                                          // |   OneSplit   |           | |             |   OneSplitView   |
                                          // +--------------+           | |             +------------------+
                                          //       | |                  / /
                                          //        \ \________________/ /
                                          //         \__________________/
                                          //
                                          
                                          
                                          contract IOneSplitConsts {
                                              // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
                                              uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
                                              uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
                                              uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
                                              uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
                                              uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
                                              uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
                                              uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
                                              uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
                                              uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
                                              uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
                                              uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
                                              uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
                                              uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
                                              uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
                                              uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
                                              uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
                                              uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
                                              uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
                                              uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
                                              uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
                                              uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
                                              uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
                                              uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
                                              uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
                                              uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
                                              uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
                                              uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
                                              uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
                                          }
                                          
                                          
                                          contract IOneSplit is IOneSplitConsts {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              )
                                                  public
                                                  payable
                                                  returns(uint256 returnAmount);
                                          }
                                          
                                          
                                          contract IOneSplitMulti is IOneSplit {
                                              function getExpectedReturnWithGasMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256[] memory parts,
                                                  uint256[] memory flags,
                                                  uint256[] memory destTokenEthPriceTimesGasPrices
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256[] memory returnAmounts,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function swapMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256[] memory flags
                                              )
                                                  public
                                                  payable
                                                  returns(uint256 returnAmount);
                                          }
                                          
                                          // File: @openzeppelin/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.5.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, 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) {
                                                  return sub(a, b, "SafeMath: subtraction overflow");
                                              }
                                          
                                              /**
                                               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                               * overflow (when the result is negative).
                                               *
                                               * Counterpart to Solidity's `-` operator.
                                               *
                                               * Requirements:
                                               * - Subtraction cannot overflow.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b <= a, errorMessage);
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  return div(a, b, "SafeMath: division by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, errorMessage);
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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) {
                                                  return mod(a, b, "SafeMath: modulo by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b != 0, errorMessage);
                                                  return a % b;
                                              }
                                          }
                                          
                                          // File: contracts/interface/IUniswapExchange.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IUniswapExchange {
                                              function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought);
                                          
                                              function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought);
                                          
                                              function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
                                                  external
                                                  payable
                                                  returns (uint256 tokensBought);
                                          
                                              function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
                                                  external
                                                  returns (uint256 ethBought);
                                          
                                              function tokenToTokenSwapInput(
                                                  uint256 tokensSold,
                                                  uint256 minTokensBought,
                                                  uint256 minEthBought,
                                                  uint256 deadline,
                                                  address tokenAddr
                                              ) external returns (uint256 tokensBought);
                                          }
                                          
                                          // File: contracts/interface/IUniswapFactory.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IUniswapFactory {
                                              function getExchange(IERC20 token) external view returns (IUniswapExchange exchange);
                                          }
                                          
                                          // File: contracts/interface/IKyberNetworkContract.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberNetworkContract {
                                              function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless)
                                                  external
                                                  view
                                                  returns (address reserve, uint256 rate);
                                          }
                                          
                                          // File: contracts/interface/IKyberNetworkProxy.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberNetworkProxy {
                                              function getExpectedRateAfterFee(
                                                  IERC20 src,
                                                  IERC20 dest,
                                                  uint256 srcQty,
                                                  uint256 platformFeeBps,
                                                  bytes calldata hint
                                              ) external view returns (uint256 expectedRate);
                                          
                                              function tradeWithHintAndFee(
                                                  IERC20 src,
                                                  uint256 srcAmount,
                                                  IERC20 dest,
                                                  address payable destAddress,
                                                  uint256 maxDestAmount,
                                                  uint256 minConversionRate,
                                                  address payable platformWallet,
                                                  uint256 platformFeeBps,
                                                  bytes calldata hint
                                              ) external payable returns (uint256 destAmount);
                                          
                                              function kyberNetworkContract() external view returns (IKyberNetworkContract);
                                          
                                              // TODO: Limit usage by tx.gasPrice
                                              // function maxGasPrice() external view returns (uint256);
                                          
                                              // TODO: Limit usage by user cap
                                              // function getUserCapInWei(address user) external view returns (uint256);
                                              // function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/IKyberStorage.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberStorage {
                                              function getReserveIdsPerTokenSrc(
                                                  IERC20 token
                                              ) external view returns (bytes32[] memory);
                                          }
                                          
                                          // File: contracts/interface/IKyberHintHandler.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IKyberHintHandler {
                                              enum TradeType {
                                                  BestOfAll,
                                                  MaskIn,
                                                  MaskOut,
                                                  Split
                                              }
                                          
                                              function buildTokenToEthHint(
                                                  IERC20 tokenSrc,
                                                  TradeType tokenToEthType,
                                                  bytes32[] calldata tokenToEthReserveIds,
                                                  uint256[] calldata tokenToEthSplits
                                              ) external view returns (bytes memory hint);
                                          
                                              function buildEthToTokenHint(
                                                  IERC20 tokenDest,
                                                  TradeType ethToTokenType,
                                                  bytes32[] calldata ethToTokenReserveIds,
                                                  uint256[] calldata ethToTokenSplits
                                              ) external view returns (bytes memory hint);
                                          }
                                          
                                          // File: contracts/interface/IBancorNetwork.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IBancorNetwork {
                                              function getReturnByPath(address[] calldata path, uint256 amount)
                                                  external
                                                  view
                                                  returns (uint256 returnAmount, uint256 conversionFee);
                                          
                                              function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn)
                                                  external
                                                  returns (uint256);
                                          
                                              function convert(address[] calldata path, uint256 amount, uint256 minReturn)
                                                  external
                                                  payable
                                                  returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/IBancorContractRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          contract IBancorContractRegistry {
                                              function addressOf(bytes32 contractName) external view returns (address);
                                          }
                                          
                                          // File: contracts/interface/IBancorNetworkPathFinder.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBancorNetworkPathFinder {
                                              function generatePath(IERC20 sourceToken, IERC20 targetToken)
                                                  external
                                                  view
                                                  returns (address[] memory);
                                          }
                                          
                                          // File: contracts/interface/IBancorConverterRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBancorConverterRegistry {
                                          
                                              function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken)
                                                  external view returns(uint256);
                                          
                                              function getConvertibleTokenSmartTokens(IERC20 convertibleToken)
                                                  external view returns(address[] memory);
                                          
                                              function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index)
                                                  external view returns(address);
                                          
                                              function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value)
                                                  external view returns(bool);
                                          }
                                          
                                          // File: contracts/interface/IBancorEtherToken.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IBancorEtherToken is IERC20 {
                                              function deposit() external payable;
                                          
                                              function withdraw(uint256 amount) external;
                                          }
                                          
                                          // File: contracts/interface/IBancorFinder.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBancorFinder {
                                              function buildBancorPath(
                                                  IERC20 fromToken,
                                                  IERC20 destToken
                                              )
                                                  external
                                                  view
                                                  returns(address[] memory path);
                                          }
                                          
                                          // File: contracts/interface/IOasisExchange.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IOasisExchange {
                                              function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt)
                                                  external
                                                  view
                                                  returns (uint256 fillAmt);
                                          
                                              function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount)
                                                  external
                                                  returns (uint256 fillAmt);
                                          }
                                          
                                          // File: contracts/interface/IWETH.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IWETH is IERC20 {
                                              function deposit() external payable;
                                          
                                              function withdraw(uint256 amount) external;
                                          }
                                          
                                          // File: contracts/interface/ICurve.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface ICurve {
                                              // solium-disable-next-line mixedcase
                                              function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
                                          
                                              // solium-disable-next-line mixedcase
                                              function get_dy(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
                                          
                                              // solium-disable-next-line mixedcase
                                              function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external;
                                          
                                              // solium-disable-next-line mixedcase
                                              function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external;
                                          }
                                          
                                          
                                          contract ICurveRegistry {
                                              function get_pool_info(address pool)
                                                  external
                                                  view
                                                  returns(
                                                      uint256[8] memory balances,
                                                      uint256[8] memory underlying_balances,
                                                      uint256[8] memory decimals,
                                                      uint256[8] memory underlying_decimals,
                                                      address lp_token,
                                                      uint256 A,
                                                      uint256 fee
                                                  );
                                          }
                                          
                                          
                                          contract ICurveCalculator {
                                              function get_dy(
                                                  int128 nCoins,
                                                  uint256[8] calldata balances,
                                                  uint256 amp,
                                                  uint256 fee,
                                                  uint256[8] calldata rates,
                                                  uint256[8] calldata precisions,
                                                  bool underlying,
                                                  int128 i,
                                                  int128 j,
                                                  uint256[100] calldata dx
                                              ) external view returns(uint256[100] memory dy);
                                          }
                                          
                                          // File: contracts/interface/IChai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IPot {
                                              function dsr() external view returns (uint256);
                                          
                                              function chi() external view returns (uint256);
                                          
                                              function rho() external view returns (uint256);
                                          
                                              function drip() external returns (uint256);
                                          
                                              function join(uint256) external;
                                          
                                              function exit(uint256) external;
                                          }
                                          
                                          
                                          contract IChai is IERC20 {
                                              function POT() public view returns (IPot);
                                          
                                              function join(address dst, uint256 wad) external;
                                          
                                              function exit(address src, uint256 wad) external;
                                          }
                                          
                                          
                                          library ChaiHelper {
                                              IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
                                              uint256 private constant RAY = 10**27;
                                          
                                              function _mul(uint256 x, uint256 y) private pure returns (uint256 z) {
                                                  require(y == 0 || (z = x * y) / y == x);
                                              }
                                          
                                              function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) {
                                                  // always rounds down
                                                  z = _mul(x, y) / RAY;
                                              }
                                          
                                              function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) {
                                                  // always rounds down
                                                  z = _mul(x, RAY) / y;
                                              }
                                          
                                              function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) {
                                                  // solium-disable-next-line security/no-inline-assembly
                                                  assembly {
                                                      switch x
                                                          case 0 {
                                                              switch n
                                                                  case 0 {
                                                                      z := base
                                                                  }
                                                                  default {
                                                                      z := 0
                                                                  }
                                                          }
                                                          default {
                                                              switch mod(n, 2)
                                                                  case 0 {
                                                                      z := base
                                                                  }
                                                                  default {
                                                                      z := x
                                                                  }
                                                              let half := div(base, 2) // for rounding.
                                                              for {
                                                                  n := div(n, 2)
                                                              } n {
                                                                  n := div(n, 2)
                                                              } {
                                                                  let xx := mul(x, x)
                                                                  if iszero(eq(div(xx, x), x)) {
                                                                      revert(0, 0)
                                                                  }
                                                                  let xxRound := add(xx, half)
                                                                  if lt(xxRound, xx) {
                                                                      revert(0, 0)
                                                                  }
                                                                  x := div(xxRound, base)
                                                                  if mod(n, 2) {
                                                                      let zx := mul(z, x)
                                                                      if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
                                                                          revert(0, 0)
                                                                      }
                                                                      let zxRound := add(zx, half)
                                                                      if lt(zxRound, zx) {
                                                                          revert(0, 0)
                                                                      }
                                                                      z := div(zxRound, base)
                                                                  }
                                                              }
                                                          }
                                                  }
                                              }
                                          
                                              function potDrip() private view returns (uint256) {
                                                  return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi());
                                              }
                                          
                                              function chaiPrice(IChai chai) internal view returns(uint256) {
                                                  return chaiToDai(chai, 1e18);
                                              }
                                          
                                              function daiToChai(
                                                  IChai /*chai*/,
                                                  uint256 amount
                                              ) internal view returns (uint256) {
                                                  uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
                                                  return _rdiv(amount, chi);
                                              }
                                          
                                              function chaiToDai(
                                                  IChai /*chai*/,
                                                  uint256 amount
                                              ) internal view returns (uint256) {
                                                  uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
                                                  return _rmul(chi, amount);
                                              }
                                          }
                                          
                                          // File: contracts/interface/ICompound.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract ICompound {
                                              function markets(address cToken)
                                                  external
                                                  view
                                                  returns (bool isListed, uint256 collateralFactorMantissa);
                                          }
                                          
                                          
                                          contract ICompoundToken is IERC20 {
                                              function underlying() external view returns (address);
                                          
                                              function exchangeRateStored() external view returns (uint256);
                                          
                                              function mint(uint256 mintAmount) external returns (uint256);
                                          
                                              function redeem(uint256 redeemTokens) external returns (uint256);
                                          }
                                          
                                          
                                          contract ICompoundEther is IERC20 {
                                              function mint() external payable;
                                          
                                              function redeem(uint256 redeemTokens) external returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/ICompoundRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract ICompoundRegistry {
                                              function tokenByCToken(ICompoundToken cToken) external view returns(IERC20);
                                              function cTokenByToken(IERC20 token) external view returns(ICompoundToken);
                                          }
                                          
                                          // File: contracts/interface/IAaveToken.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IAaveToken is IERC20 {
                                              function underlyingAssetAddress() external view returns (IERC20);
                                          
                                              function redeem(uint256 amount) external;
                                          }
                                          
                                          
                                          interface IAaveLendingPool {
                                              function core() external view returns (address);
                                          
                                              function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
                                          }
                                          
                                          // File: contracts/interface/IAaveRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract IAaveRegistry {
                                              function tokenByAToken(IAaveToken aToken) external view returns(IERC20);
                                              function aTokenByToken(IERC20 token) external view returns(IAaveToken);
                                          }
                                          
                                          // File: contracts/interface/IMooniswap.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IMooniswapRegistry {
                                              function target() external view returns(IMooniswap);
                                          }
                                          
                                          
                                          interface IMooniswap {
                                              function getReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount
                                              )
                                                  external
                                                  view
                                                  returns(uint256 returnAmount);
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn
                                              )
                                                  external
                                                  payable
                                                  returns(uint256 returnAmount);
                                          }
                                          
                                          // File: @openzeppelin/contracts/utils/Address.sol
                                          
                                          pragma solidity ^0.5.5;
                                          
                                          /**
                                           * @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) {
                                                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                                  // for accounts without code, i.e. `keccak256('')`
                                                  bytes32 codehash;
                                                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                                  // solhint-disable-next-line no-inline-assembly
                                                  assembly { codehash := extcodehash(account) }
                                                  return (codehash != accountHash && codehash != 0x0);
                                              }
                                          
                                              /**
                                               * @dev Converts an `address` into `address payable`. Note that this is
                                               * simply a type cast: the actual underlying value is not changed.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function toPayable(address account) internal pure returns (address payable) {
                                                  return address(uint160(account));
                                              }
                                          
                                              /**
                                               * @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].
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sendValue(address payable recipient, uint256 amount) internal {
                                                  require(address(this).balance >= amount, "Address: insufficient balance");
                                          
                                                  // solhint-disable-next-line avoid-call-value
                                                  (bool success, ) = recipient.call.value(amount)("");
                                                  require(success, "Address: unable to send value, recipient may have reverted");
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                                          
                                          pragma solidity ^0.5.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 ERC20;` 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));
                                              }
                                          
                                              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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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: contracts/UniversalERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          library UniversalERC20 {
                                          
                                              using SafeMath for uint256;
                                              using SafeERC20 for IERC20;
                                          
                                              IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
                                              IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
                                                  if (amount == 0) {
                                                      return true;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      address(uint160(to)).transfer(amount);
                                                  } else {
                                                      token.safeTransfer(to, amount);
                                                      return true;
                                                  }
                                              }
                                          
                                              function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
                                                      if (to != address(this)) {
                                                          address(uint160(to)).transfer(amount);
                                                      }
                                                      if (msg.value > amount) {
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(from, to, amount);
                                                  }
                                              }
                                          
                                              function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      if (msg.value > amount) {
                                                          // Return remainder if exist
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(msg.sender, address(this), amount);
                                                  }
                                              }
                                          
                                              function universalApprove(IERC20 token, address to, uint256 amount) internal {
                                                  if (!isETH(token)) {
                                                      if (amount == 0) {
                                                          token.safeApprove(to, 0);
                                                          return;
                                                      }
                                          
                                                      uint256 allowance = token.allowance(address(this), to);
                                                      if (allowance < amount) {
                                                          if (allowance > 0) {
                                                              token.safeApprove(to, 0);
                                                          }
                                                          token.safeApprove(to, amount);
                                                      }
                                                  }
                                              }
                                          
                                              function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
                                                  if (isETH(token)) {
                                                      return who.balance;
                                                  } else {
                                                      return token.balanceOf(who);
                                                  }
                                              }
                                          
                                              function universalDecimals(IERC20 token) internal view returns (uint256) {
                                          
                                                  if (isETH(token)) {
                                                      return 18;
                                                  }
                                          
                                                  (bool success, bytes memory data) = address(token).staticcall.gas(10000)(
                                                      abi.encodeWithSignature("decimals()")
                                                  );
                                                  if (!success || data.length == 0) {
                                                      (success, data) = address(token).staticcall.gas(10000)(
                                                          abi.encodeWithSignature("DECIMALS()")
                                                      );
                                                  }
                                          
                                                  return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
                                              }
                                          
                                              function isETH(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
                                              }
                                          
                                              function notExist(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(-1));
                                              }
                                          }
                                          
                                          // File: contracts/interface/IUniswapV2Exchange.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          interface IUniswapV2Exchange {
                                              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                          }
                                          
                                          
                                          library UniswapV2ExchangeLib {
                                              using SafeMath for uint256;
                                              using UniversalERC20 for IERC20;
                                          
                                              function getReturn(
                                                  IUniswapV2Exchange exchange,
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint amountIn
                                              ) internal view returns (uint256) {
                                                  uint256 reserveIn = fromToken.universalBalanceOf(address(exchange));
                                                  uint256 reserveOut = destToken.universalBalanceOf(address(exchange));
                                          
                                                  uint256 amountInWithFee = amountIn.mul(997);
                                                  uint256 numerator = amountInWithFee.mul(reserveOut);
                                                  uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
                                                  return (denominator == 0) ? 0 : numerator.div(denominator);
                                              }
                                          }
                                          
                                          // File: contracts/interface/IUniswapV2Factory.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IUniswapV2Factory {
                                              function getPair(IERC20 tokenA, IERC20 tokenB) external view returns (IUniswapV2Exchange pair);
                                          }
                                          
                                          // File: contracts/interface/IDForceSwap.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IDForceSwap {
                                              function getAmountByInput(IERC20 input, IERC20 output, uint256 amount) external view returns(uint256);
                                              function swap(IERC20 input, IERC20 output, uint256 amount) external;
                                          }
                                          
                                          // File: contracts/interface/IShell.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IShell {
                                              function viewOriginTrade(
                                                  address origin,
                                                  address target,
                                                  uint256 originAmount
                                              ) external view returns (uint256);
                                          
                                              function swapByOrigin(
                                                  address origin,
                                                  address target,
                                                  uint256 originAmount,
                                                  uint256 minTargetAmount,
                                                  uint256 deadline
                                              ) external returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/IMStable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IMStable is IERC20 {
                                              function getSwapOutput(
                                                  IERC20 _input,
                                                  IERC20 _output,
                                                  uint256 _quantity
                                              )
                                                  external
                                                  view
                                                  returns (bool, string memory, uint256 output);
                                          
                                              function swap(
                                                  IERC20 _input,
                                                  IERC20 _output,
                                                  uint256 _quantity,
                                                  address _recipient
                                              )
                                                  external
                                                  returns (uint256 output);
                                          
                                              function redeem(
                                                  IERC20 _basset,
                                                  uint256 _bassetQuantity
                                              )
                                                  external
                                                  returns (uint256 massetRedeemed);
                                          }
                                          
                                          interface IMassetRedemptionValidator {
                                              function getRedeemValidity(
                                                  IERC20 _mAsset,
                                                  uint256 _mAssetQuantity,
                                                  IERC20 _outputBasset
                                              )
                                                  external
                                                  view
                                                  returns (bool, string memory, uint256 output);
                                          }
                                          
                                          // File: contracts/interface/IBalancerRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IBalancerPool {
                                              function swapExactAmountIn(
                                                  IERC20 tokenIn,
                                                  uint256 tokenAmountIn,
                                                  IERC20 tokenOut,
                                                  uint256 minAmountOut,
                                                  uint256 maxPrice
                                              )
                                                  external
                                                  returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
                                          }
                                          
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IBalancerRegistry {
                                              event PoolAdded(
                                                  address indexed pool
                                              );
                                              event PoolTokenPairAdded(
                                                  address indexed pool,
                                                  address indexed fromToken,
                                                  address indexed destToken
                                              );
                                              event IndicesUpdated(
                                                  address indexed fromToken,
                                                  address indexed destToken,
                                                  bytes32 oldIndices,
                                                  bytes32 newIndices
                                              );
                                          
                                              // Get info about pool pair for 1 SLOAD
                                              function getPairInfo(address pool, address fromToken, address destToken)
                                                  external view returns(uint256 weight1, uint256 weight2, uint256 swapFee);
                                          
                                              // Pools
                                              function checkAddedPools(address pool)
                                                  external view returns(bool);
                                              function getAddedPoolsLength()
                                                  external view returns(uint256);
                                              function getAddedPools()
                                                  external view returns(address[] memory);
                                              function getAddedPoolsWithLimit(uint256 offset, uint256 limit)
                                                  external view returns(address[] memory result);
                                          
                                              // Tokens
                                              function getAllTokensLength()
                                                  external view returns(uint256);
                                              function getAllTokens()
                                                  external view returns(address[] memory);
                                              function getAllTokensWithLimit(uint256 offset, uint256 limit)
                                                  external view returns(address[] memory result);
                                          
                                              // Pairs
                                              function getPoolsLength(address fromToken, address destToken)
                                                  external view returns(uint256);
                                              function getPools(address fromToken, address destToken)
                                                  external view returns(address[] memory);
                                              function getPoolsWithLimit(address fromToken, address destToken, uint256 offset, uint256 limit)
                                                  external view returns(address[] memory result);
                                              function getBestPools(address fromToken, address destToken)
                                                  external view returns(address[] memory pools);
                                              function getBestPoolsWithLimit(address fromToken, address destToken, uint256 limit)
                                                  external view returns(address[] memory pools);
                                          
                                              // Get swap rates
                                              function getPoolReturn(address pool, address fromToken, address destToken, uint256 amount)
                                                  external view returns(uint256);
                                              function getPoolReturns(address pool, address fromToken, address destToken, uint256[] calldata amounts)
                                                  external view returns(uint256[] memory result);
                                          
                                              // Add and update registry
                                              function addPool(address pool) external returns(uint256 listed);
                                              function addPools(address[] calldata pools) external returns(uint256[] memory listed);
                                              function updatedIndices(address[] calldata tokens, uint256 lengthLimit) external;
                                          }
                                          
                                          // File: contracts/OneSplitBase.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract IOneSplitView is IOneSplitConsts {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  );
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          }
                                          
                                          
                                          library DisableFlags {
                                              function check(uint256 flags, uint256 flag) internal pure returns(bool) {
                                                  return (flags & flag) != 0;
                                              }
                                          }
                                          
                                          
                                          contract OneSplitRoot is IOneSplitView {
                                              using SafeMath for uint256;
                                              using DisableFlags for uint256;
                                          
                                              using UniversalERC20 for IERC20;
                                              using UniversalERC20 for IWETH;
                                              using UniswapV2ExchangeLib for IUniswapV2Exchange;
                                              using ChaiHelper for IChai;
                                          
                                              uint256 constant internal DEXES_COUNT = 31;
                                              IERC20 constant internal ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              IBancorEtherToken constant internal bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
                                              IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
                                              IChai constant internal chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
                                              IERC20 constant internal dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
                                              IERC20 constant internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
                                              IERC20 constant internal usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
                                              IERC20 constant internal tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
                                              IERC20 constant internal busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
                                              IERC20 constant internal susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
                                              IERC20 constant internal pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1);
                                              IERC20 constant internal renbtc = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D);
                                              IERC20 constant internal wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
                                              IERC20 constant internal tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847);
                                              IERC20 constant internal hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380);
                                              IERC20 constant internal sbtc = IERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6);
                                          
                                              IKyberNetworkProxy constant internal kyberNetworkProxy = IKyberNetworkProxy(0x9AAb3f75489902f3a48495025729a0AF77d4b11e);
                                              IKyberStorage constant internal kyberStorage = IKyberStorage(0xC8fb12402cB16970F3C5F4b48Ff68Eb9D1289301);
                                              IKyberHintHandler constant internal kyberHintHandler = IKyberHintHandler(0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C);
                                              IUniswapFactory constant internal uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
                                              IBancorContractRegistry constant internal bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4);
                                              IBancorNetworkPathFinder constant internal bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
                                              //IBancorConverterRegistry constant internal bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518);
                                              IBancorFinder constant internal bancorFinder = IBancorFinder(0x2B344e14dc2641D11D338C053C908c7A7D4c30B9);
                                              IOasisExchange constant internal oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D);
                                              ICurve constant internal curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56);
                                              ICurve constant internal curveUSDT = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C);
                                              ICurve constant internal curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
                                              ICurve constant internal curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27);
                                              ICurve constant internal curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD);
                                              ICurve constant internal curvePAX = ICurve(0x06364f10B501e868329afBc005b3492902d6C763);
                                              ICurve constant internal curveRenBTC = ICurve(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
                                              ICurve constant internal curveTBTC = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E);
                                              ICurve constant internal curveSBTC = ICurve(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714);
                                              IShell constant internal shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D);
                                              IAaveLendingPool constant internal aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
                                              ICompound constant internal compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
                                              ICompoundEther constant internal cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
                                              IMooniswapRegistry constant internal mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70);
                                              IUniswapV2Factory constant internal uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
                                              IDForceSwap constant internal dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2);
                                              IMStable constant internal musd = IMStable(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
                                              IMassetRedemptionValidator constant internal musd_helper = IMassetRedemptionValidator(0x4c5e03065bC52cCe84F3ac94DF14bbAC27eac89b);
                                              IBalancerRegistry constant internal balancerRegistry = IBalancerRegistry(0x65e67cbc342712DF67494ACEfc06fe951EE93982);
                                              ICurveCalculator constant internal curveCalculator = ICurveCalculator(0xc1DB00a8E5Ef7bfa476395cdbcc98235477cDE4E);
                                              ICurveRegistry constant internal curveRegistry = ICurveRegistry(0x7002B727Ef8F5571Cb5F9D70D13DBEEb4dFAe9d1);
                                              ICompoundRegistry constant internal compoundRegistry = ICompoundRegistry(0xF451Dbd7Ba14BFa7B1B78A766D3Ed438F79EE1D1);
                                              IAaveRegistry constant internal aaveRegistry = IAaveRegistry(0xEd8b133B7B88366E01Bb9E38305Ab11c26521494);
                                          
                                              int256 internal constant VERY_NEGATIVE_VALUE = -1e72;
                                          
                                              function _findBestDistribution(
                                                  uint256 s,                // parts
                                                  int256[][] memory amounts // exchangesReturns
                                              )
                                                  internal
                                                  pure
                                                  returns(
                                                      int256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  uint256 n = amounts.length;
                                          
                                                  int256[][] memory answer = new int256[][](n); // int[n][s+1]
                                                  uint256[][] memory parent = new uint256[][](n); // int[n][s+1]
                                          
                                                  for (uint i = 0; i < n; i++) {
                                                      answer[i] = new int256[](s + 1);
                                                      parent[i] = new uint256[](s + 1);
                                                  }
                                          
                                                  for (uint j = 0; j <= s; j++) {
                                                      answer[0][j] = amounts[0][j];
                                                      for (uint i = 1; i < n; i++) {
                                                          answer[i][j] = -1e72;
                                                      }
                                                      parent[0][j] = 0;
                                                  }
                                          
                                                  for (uint i = 1; i < n; i++) {
                                                      for (uint j = 0; j <= s; j++) {
                                                          answer[i][j] = answer[i - 1][j];
                                                          parent[i][j] = j;
                                          
                                                          for (uint k = 1; k <= j; k++) {
                                                              if (answer[i - 1][j - k] + amounts[i][k] > answer[i][j]) {
                                                                  answer[i][j] = answer[i - 1][j - k] + amounts[i][k];
                                                                  parent[i][j] = j - k;
                                                              }
                                                          }
                                                      }
                                                  }
                                          
                                                  distribution = new uint256[](DEXES_COUNT);
                                          
                                                  uint256 partsLeft = s;
                                                  for (uint curExchange = n - 1; partsLeft > 0; curExchange--) {
                                                      distribution[curExchange] = partsLeft - parent[curExchange][partsLeft];
                                                      partsLeft = parent[curExchange][partsLeft];
                                                  }
                                          
                                                  returnAmount = (answer[n - 1][s] == VERY_NEGATIVE_VALUE) ? 0 : answer[n - 1][s];
                                              }
                                          
                                              function _kyberReserveIdByTokens(
                                                  IERC20 fromToken,
                                                  IERC20 destToken
                                              ) internal view returns(bytes32) {
                                                  if (!fromToken.isETH() && !destToken.isETH()) {
                                                      return 0;
                                                  }
                                          
                                                  bytes32[] memory reserveIds = kyberStorage.getReserveIdsPerTokenSrc(
                                                      fromToken.isETH() ? destToken : fromToken
                                                  );
                                          
                                                  for (uint i = 0; i < reserveIds.length; i++) {
                                                      if ((uint256(reserveIds[i]) >> 248) != 0xBB && // Bridge
                                                          reserveIds[i] != 0xff4b796265722046707200000000000000000000000000000000000000000000 && // Reserve 1
                                                          reserveIds[i] != 0xffabcd0000000000000000000000000000000000000000000000000000000000 && // Reserve 2
                                                          reserveIds[i] != 0xff4f6e65426974205175616e7400000000000000000000000000000000000000)   // Reserve 3
                                                      {
                                                          return reserveIds[i];
                                                      }
                                                  }
                                          
                                                  return 0;
                                              }
                                          
                                              function _scaleDestTokenEthPriceTimesGasPrice(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              ) internal view returns(uint256) {
                                                  if (fromToken == destToken) {
                                                      return destTokenEthPriceTimesGasPrice;
                                                  }
                                          
                                                  uint256 mul = _cheapGetPrice(ETH_ADDRESS, destToken, 0.01 ether);
                                                  uint256 div = _cheapGetPrice(ETH_ADDRESS, fromToken, 0.01 ether);
                                                  if (div > 0) {
                                                      return destTokenEthPriceTimesGasPrice.mul(mul).div(div);
                                                  }
                                                  return 0;
                                              }
                                          
                                              function _cheapGetPrice(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount
                                              ) internal view returns(uint256 returnAmount) {
                                                  (returnAmount,,) = this.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      1,
                                                      FLAG_DISABLE_SPLIT_RECALCULATION |
                                                      FLAG_DISABLE_ALL_SPLIT_SOURCES |
                                                      FLAG_DISABLE_UNISWAP_V2_ALL |
                                                      FLAG_DISABLE_UNISWAP,
                                                      0
                                                  );
                                              }
                                          
                                              function _linearInterpolation(
                                                  uint256 value,
                                                  uint256 parts
                                              ) internal pure returns(uint256[] memory rets) {
                                                  rets = new uint256[](parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      rets[i] = value.mul(i + 1).div(parts);
                                                  }
                                              }
                                          
                                              function _tokensEqual(IERC20 tokenA, IERC20 tokenB) internal pure returns(bool) {
                                                  return ((tokenA.isETH() && tokenB.isETH()) || tokenA == tokenB);
                                              }
                                          }
                                          
                                          
                                          contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = this.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _getExpectedReturnRespectingGasFloor(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _getExpectedReturnRespectingGasFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  internal
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  );
                                          }
                                          
                                          
                                          contract OneSplitView is IOneSplitView, OneSplitRoot {
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  distribution = new uint256[](DEXES_COUNT);
                                          
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, distribution);
                                                  }
                                          
                                                  function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory reserves = _getAllReserves(flags);
                                          
                                                  int256[][] memory matrix = new int256[][](DEXES_COUNT);
                                                  uint256[DEXES_COUNT] memory gases;
                                                  bool atLeastOnePositive = false;
                                                  for (uint i = 0; i < DEXES_COUNT; i++) {
                                                      uint256[] memory rets;
                                                      (rets, gases[i]) = reserves[i](fromToken, destToken, amount, parts, flags);
                                          
                                                      // Prepend zero and sub gas
                                                      int256 gas = int256(gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18));
                                                      matrix[i] = new int256[](parts + 1);
                                                      for (uint j = 0; j < parts; j++) {
                                                          matrix[i][j + 1] = int256(rets[j]) - gas;
                                                          atLeastOnePositive = atLeastOnePositive || (matrix[i][j + 1] > 0);
                                                      }
                                                  }
                                          
                                                  if (!atLeastOnePositive) {
                                                      for (uint i = 0; i < DEXES_COUNT; i++) {
                                                          for (uint j = 1; j < parts + 1; j++) {
                                                              if (matrix[i][j] == 0) {
                                                                  matrix[i][j] = VERY_NEGATIVE_VALUE;
                                                              }
                                                          }
                                                      }
                                                  }
                                          
                                                  (, distribution) = _findBestDistribution(parts, matrix);
                                          
                                                  (returnAmount, estimateGasAmount) = _getReturnAndGasByDistribution(
                                                      Args({
                                                          fromToken: fromToken,
                                                          destToken: destToken,
                                                          amount: amount,
                                                          parts: parts,
                                                          flags: flags,
                                                          destTokenEthPriceTimesGasPrice: destTokenEthPriceTimesGasPrice,
                                                          distribution: distribution,
                                                          matrix: matrix,
                                                          gases: gases,
                                                          reserves: reserves
                                                      })
                                                  );
                                                  return (returnAmount, estimateGasAmount, distribution);
                                              }
                                          
                                              struct Args {
                                                  IERC20 fromToken;
                                                  IERC20 destToken;
                                                  uint256 amount;
                                                  uint256 parts;
                                                  uint256 flags;
                                                  uint256 destTokenEthPriceTimesGasPrice;
                                                  uint256[] distribution;
                                                  int256[][] matrix;
                                                  uint256[DEXES_COUNT] gases;
                                                  function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] reserves;
                                              }
                                          
                                              function _getReturnAndGasByDistribution(
                                                  Args memory args
                                              ) internal view returns(uint256 returnAmount, uint256 estimateGasAmount) {
                                                  bool[DEXES_COUNT] memory exact = [
                                                      true,  // "Uniswap",
                                                      false, // "Kyber",
                                                      false, // "Bancor",
                                                      false, // "Oasis",
                                                      true,  // "Curve Compound",
                                                      true,  // "Curve USDT",
                                                      true,  // "Curve Y",
                                                      true,  // "Curve Binance",
                                                      true,  // "Curve Synthetix",
                                                      true,  // "Uniswap Compound",
                                                      true,  // "Uniswap CHAI",
                                                      true,  // "Uniswap Aave",
                                                      false, // "Mooniswap",
                                                      true,  // "Uniswap V2",
                                                      true,  // "Uniswap V2 (ETH)",
                                                      true,  // "Uniswap V2 (DAI)",
                                                      true,  // "Uniswap V2 (USDC)",
                                                      true,  // "Curve Pax",
                                                      true,  // "Curve RenBTC",
                                                      true,  // "Curve tBTC",
                                                      true,  // "Dforce XSwap",
                                                      false, // "Shell",
                                                      true,  // "mStable",
                                                      true,  // "Curve sBTC"
                                                      true,  // "Balancer 1"
                                                      true,  // "Balancer 2"
                                                      true,  // "Balancer 3"
                                                      true,  // "Kyber 1"
                                                      true,  // "Kyber 2"
                                                      true,  // "Kyber 3"
                                                      true   // "Kyber 4"
                                                  ];
                                          
                                                  for (uint i = 0; i < DEXES_COUNT; i++) {
                                                      if (args.distribution[i] > 0) {
                                                          if (args.distribution[i] == args.parts || exact[i] || args.flags.check(FLAG_DISABLE_SPLIT_RECALCULATION)) {
                                                              estimateGasAmount = estimateGasAmount.add(args.gases[i]);
                                                              int256 value = args.matrix[i][args.distribution[i]];
                                                              returnAmount = returnAmount.add(uint256(
                                                                  (value == VERY_NEGATIVE_VALUE ? 0 : value) +
                                                                  int256(args.gases[i].mul(args.destTokenEthPriceTimesGasPrice).div(1e18))
                                                              ));
                                                          }
                                                          else {
                                                              (uint256[] memory rets, uint256 gas) = args.reserves[i](args.fromToken, args.destToken, args.amount.mul(args.distribution[i]).div(args.parts), 1, args.flags);
                                                              estimateGasAmount = estimateGasAmount.add(gas);
                                                              returnAmount = returnAmount.add(rets[0]);
                                                          }
                                                      }
                                                  }
                                              }
                                          
                                              function _getAllReserves(uint256 flags)
                                                  internal
                                                  pure
                                                  returns(function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory)
                                              {
                                                  bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES);
                                                  return [
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP)            ? _calculateNoReturn : calculateUniswap,
                                                      _calculateNoReturn, // invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyber,
                                                      invert != flags.check(FLAG_DISABLE_BANCOR)                                        ? _calculateNoReturn : calculateBancor,
                                                      invert != flags.check(FLAG_DISABLE_OASIS)                                         ? _calculateNoReturn : calculateOasis,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_COMPOUND)       ? _calculateNoReturn : calculateCurveCompound,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_USDT)           ? _calculateNoReturn : calculateCurveUSDT,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_Y)              ? _calculateNoReturn : calculateCurveY,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_BINANCE)        ? _calculateNoReturn : calculateCurveBinance,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SYNTHETIX)      ? _calculateNoReturn : calculateCurveSynthetix,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_COMPOUND)   ? _calculateNoReturn : calculateUniswapCompound,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_CHAI)       ? _calculateNoReturn : calculateUniswapChai,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_ALL | FLAG_DISABLE_UNISWAP_AAVE)       ? _calculateNoReturn : calculateUniswapAave,
                                                      invert != flags.check(FLAG_DISABLE_MOONISWAP)                                     ? _calculateNoReturn : calculateMooniswap,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2)      ? _calculateNoReturn : calculateUniswapV2,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_ETH)  ? _calculateNoReturn : calculateUniswapV2ETH,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_DAI)  ? _calculateNoReturn : calculateUniswapV2DAI,
                                                      invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ALL | FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_PAX)            ? _calculateNoReturn : calculateCurvePAX,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_RENBTC)         ? _calculateNoReturn : calculateCurveRenBTC,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_TBTC)           ? _calculateNoReturn : calculateCurveTBTC,
                                                      invert != flags.check(FLAG_DISABLE_DFORCE_SWAP)                                   ? _calculateNoReturn : calculateDforceSwap,
                                                      invert != flags.check(FLAG_DISABLE_SHELL)                                         ? _calculateNoReturn : calculateShell,
                                                      invert != flags.check(FLAG_DISABLE_MSTABLE_MUSD)                                  ? _calculateNoReturn : calculateMStableMUSD,
                                                      invert != flags.check(FLAG_DISABLE_CURVE_ALL | FLAG_DISABLE_CURVE_SBTC)           ? _calculateNoReturn : calculateCurveSBTC,
                                                      invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_1)        ? _calculateNoReturn : calculateBalancer1,
                                                      invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_2)        ? _calculateNoReturn : calculateBalancer2,
                                                      invert != flags.check(FLAG_DISABLE_BALANCER_ALL | FLAG_DISABLE_BALANCER_3)        ? _calculateNoReturn : calculateBalancer3,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_1)              ? _calculateNoReturn : calculateKyber1,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_2)              ? _calculateNoReturn : calculateKyber2,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_3)              ? _calculateNoReturn : calculateKyber3,
                                                      invert != flags.check(FLAG_DISABLE_KYBER_ALL | FLAG_DISABLE_KYBER_4)              ? _calculateNoReturn : calculateKyber4
                                                  ];
                                              }
                                          
                                              function _calculateNoGas(
                                                  IERC20 /*fromToken*/,
                                                  IERC20 /*destToken*/,
                                                  uint256 /*amount*/,
                                                  uint256 /*parts*/,
                                                  uint256 /*destTokenEthPriceTimesGasPrice*/,
                                                  uint256 /*flags*/,
                                                  uint256 /*destTokenEthPrice*/
                                              ) internal view returns(uint256[] memory /*rets*/, uint256 /*gas*/) {
                                                  this;
                                              }
                                          
                                              // View Helpers
                                          
                                              function _calculateBalancer(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/,
                                                  uint256 poolIndex
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = new uint256[](parts);
                                          
                                                  address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
                                                      address(fromToken.isETH() ? weth : fromToken),
                                                      address(destToken.isETH() ? weth : destToken),
                                                      poolIndex + 1
                                                  );
                                                  if (poolIndex >= pools.length) {
                                                      return (rets, 0);
                                                  }
                                          
                                                  (bool success, bytes memory result) = address(balancerRegistry).staticcall(
                                                      abi.encodeWithSelector(
                                                          balancerRegistry.getPoolReturns.selector,
                                                          pools[poolIndex],
                                                          address(fromToken.isETH() ? weth : fromToken),
                                                          address(destToken.isETH() ? weth : destToken),
                                                          _linearInterpolation(amount, parts)
                                                      )
                                                  );
                                          
                                                  if (!success || result.length == 0) {
                                                      return (rets, 0);
                                                  }
                                          
                                                  return (
                                                      abi.decode(result, (uint256[])),
                                                      100_000
                                                  );
                                              }
                                          
                                              function calculateBalancer1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateBalancer(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function calculateBalancer2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateBalancer(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      1
                                                  );
                                              }
                                          
                                              function calculateBalancer3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateBalancer(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      2
                                                  );
                                              }
                                          
                                              function calculateMStableMUSD(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = new uint256[](parts);
                                          
                                                  if ((fromToken != usdc && fromToken != dai && fromToken != usdt && fromToken != tusd) ||
                                                      (destToken != usdc && destToken != dai && destToken != usdt && destToken != tusd))
                                                  {
                                                      return (rets, 0);
                                                  }
                                          
                                                  for (uint i = 1; i <= parts; i *= 2) {
                                                      (bool success, bytes memory data) = address(musd).staticcall(abi.encodeWithSelector(
                                                          musd.getSwapOutput.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount.mul(parts.div(i)).div(parts)
                                                      ));
                                          
                                                      if (success && data.length > 0) {
                                                          (,, uint256 maxRet) = abi.decode(data, (bool,string,uint256));
                                                          if (maxRet > 0) {
                                                              for (uint j = 0; j < parts.div(i); j++) {
                                                                  rets[j] = maxRet.mul(j + 1).div(parts.div(i));
                                                              }
                                                              break;
                                                          }
                                                      }
                                                  }
                                          
                                                  return (
                                                      rets,
                                                      700_000
                                                  );
                                              }
                                          
                                              function _getCurvePoolInfo(
                                                  ICurve curve,
                                                  bool haveUnderlying
                                              ) internal view returns(
                                                  uint256[8] memory balances,
                                                  uint256[8] memory precisions,
                                                  uint256[8] memory rates,
                                                  uint256 amp,
                                                  uint256 fee
                                              ) {
                                                  uint256[8] memory underlying_balances;
                                                  uint256[8] memory decimals;
                                                  uint256[8] memory underlying_decimals;
                                          
                                                  (
                                                      balances,
                                                      underlying_balances,
                                                      decimals,
                                                      underlying_decimals,
                                                      /*address lp_token*/,
                                                      amp,
                                                      fee
                                                  ) = curveRegistry.get_pool_info(address(curve));
                                          
                                                  for (uint k = 0; k < 8 && balances[k] > 0; k++) {
                                                      precisions[k] = 10 ** (18 - (haveUnderlying ? underlying_decimals : decimals)[k]);
                                                      if (haveUnderlying) {
                                                          rates[k] = underlying_balances[k].mul(1e18).div(balances[k]);
                                                      } else {
                                                          rates[k] = 1e18;
                                                      }
                                                  }
                                              }
                                          
                                              function _calculateCurveSelector(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  ICurve curve,
                                                  bool haveUnderlying,
                                                  IERC20[] memory tokens
                                              ) internal view returns(uint256[] memory rets) {
                                                  rets = new uint256[](parts);
                                          
                                                  int128 i = 0;
                                                  int128 j = 0;
                                                  for (uint t = 0; t < tokens.length; t++) {
                                                      if (fromToken == tokens[t]) {
                                                          i = int128(t + 1);
                                                      }
                                                      if (destToken == tokens[t]) {
                                                          j = int128(t + 1);
                                                      }
                                                  }
                                          
                                                  if (i == 0 || j == 0) {
                                                      return rets;
                                                  }
                                          
                                                  bytes memory data = abi.encodePacked(
                                                      uint256(haveUnderlying ? 1 : 0),
                                                      uint256(i - 1),
                                                      uint256(j - 1),
                                                      _linearInterpolation100(amount, parts)
                                                  );
                                          
                                                  (
                                                      uint256[8] memory balances,
                                                      uint256[8] memory precisions,
                                                      uint256[8] memory rates,
                                                      uint256 amp,
                                                      uint256 fee
                                                  ) = _getCurvePoolInfo(curve, haveUnderlying);
                                          
                                                  bool success;
                                                  (success, data) = address(curveCalculator).staticcall(
                                                      abi.encodePacked(
                                                          abi.encodeWithSelector(
                                                              curveCalculator.get_dy.selector,
                                                              tokens.length,
                                                              balances,
                                                              amp,
                                                              fee,
                                                              rates,
                                                              precisions
                                                          ),
                                                          data
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return rets;
                                                  }
                                          
                                                  uint256[100] memory dy = abi.decode(data, (uint256[100]));
                                                  for (uint t = 0; t < parts; t++) {
                                                      rets[t] = dy[t];
                                                  }
                                              }
                                          
                                              function _linearInterpolation100(
                                                  uint256 value,
                                                  uint256 parts
                                              ) internal pure returns(uint256[100] memory rets) {
                                                  for (uint i = 0; i < parts; i++) {
                                                      rets[i] = value.mul(i + 1).div(parts);
                                                  }
                                              }
                                          
                                              function calculateCurveCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](2);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveCompound,
                                                      true,
                                                      tokens
                                                  ), 720_000);
                                              }
                                          
                                              function calculateCurveUSDT(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](3);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveUSDT,
                                                      true,
                                                      tokens
                                                  ), 720_000);
                                              }
                                          
                                              function calculateCurveY(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = tusd;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveY,
                                                      true,
                                                      tokens
                                                  ), 1_400_000);
                                              }
                                          
                                              function calculateCurveBinance(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = busd;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveBinance,
                                                      true,
                                                      tokens
                                                  ), 1_400_000);
                                              }
                                          
                                              function calculateCurveSynthetix(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = susd;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveSynthetix,
                                                      true,
                                                      tokens
                                                  ), 200_000);
                                              }
                                          
                                              function calculateCurvePAX(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](4);
                                                  tokens[0] = dai;
                                                  tokens[1] = usdc;
                                                  tokens[2] = usdt;
                                                  tokens[3] = pax;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curvePAX,
                                                      true,
                                                      tokens
                                                  ), 1_000_000);
                                              }
                                          
                                              function calculateCurveRenBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](2);
                                                  tokens[0] = renbtc;
                                                  tokens[1] = wbtc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveRenBTC,
                                                      false,
                                                      tokens
                                                  ), 130_000);
                                              }
                                          
                                              function calculateCurveTBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](3);
                                                  tokens[0] = tbtc;
                                                  tokens[1] = wbtc;
                                                  tokens[2] = hbtc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveTBTC,
                                                      false,
                                                      tokens
                                                  ), 145_000);
                                              }
                                          
                                              function calculateCurveSBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20[] memory tokens = new IERC20[](3);
                                                  tokens[0] = renbtc;
                                                  tokens[1] = wbtc;
                                                  tokens[2] = sbtc;
                                                  return (_calculateCurveSelector(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      curveSBTC,
                                                      false,
                                                      tokens
                                                  ), 150_000);
                                              }
                                          
                                              function calculateShell(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  (bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector(
                                                      shell.viewOriginTrade.selector,
                                                      fromToken,
                                                      destToken,
                                                      amount
                                                  ));
                                          
                                                  if (!success || data.length == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  uint256 maxRet = abi.decode(data, (uint256));
                                                  return (_linearInterpolation(maxRet, parts), 300_000);
                                              }
                                          
                                              function calculateDforceSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  (bool success, bytes memory data) = address(dforceSwap).staticcall(
                                                      abi.encodeWithSelector(
                                                          dforceSwap.getAmountByInput.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount
                                                      )
                                                  );
                                                  if (!success || data.length == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  uint256 maxRet = abi.decode(data, (uint256));
                                                  uint256 available = destToken.universalBalanceOf(address(dforceSwap));
                                                  if (maxRet > available) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return (_linearInterpolation(maxRet, parts), 160_000);
                                              }
                                          
                                              function _calculateUniswapFormula(uint256 fromBalance, uint256 toBalance, uint256 amount) internal pure returns(uint256) {
                                                  if (amount == 0) {
                                                      return 0;
                                                  }
                                                  return amount.mul(toBalance).mul(997).div(
                                                      fromBalance.mul(1000).add(amount.mul(997))
                                                  );
                                              }
                                          
                                              function _calculateUniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256[] memory amounts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = amounts;
                                          
                                                  if (!fromToken.isETH()) {
                                                      IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
                                                      if (fromExchange == IUniswapExchange(0)) {
                                                          return (new uint256[](rets.length), 0);
                                                      }
                                          
                                                      uint256 fromTokenBalance = fromToken.universalBalanceOf(address(fromExchange));
                                                      uint256 fromEtherBalance = address(fromExchange).balance;
                                          
                                                      for (uint i = 0; i < rets.length; i++) {
                                                          rets[i] = _calculateUniswapFormula(fromTokenBalance, fromEtherBalance, rets[i]);
                                                      }
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
                                                      if (toExchange == IUniswapExchange(0)) {
                                                          return (new uint256[](rets.length), 0);
                                                      }
                                          
                                                      uint256 toEtherBalance = address(toExchange).balance;
                                                      uint256 toTokenBalance = destToken.universalBalanceOf(address(toExchange));
                                          
                                                      for (uint i = 0; i < rets.length; i++) {
                                                          rets[i] = _calculateUniswapFormula(toEtherBalance, toTokenBalance, rets[i]);
                                                      }
                                                  }
                                          
                                                  return (rets, fromToken.isETH() || destToken.isETH() ? 60_000 : 100_000);
                                              }
                                          
                                              function calculateUniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateUniswap(
                                                      fromToken,
                                                      destToken,
                                                      _linearInterpolation(amount, parts),
                                                      flags
                                                  );
                                              }
                                          
                                              function _calculateUniswapWrapped(
                                                  IERC20 fromToken,
                                                  IERC20 midToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 midTokenPrice,
                                                  uint256 flags,
                                                  uint256 gas1,
                                                  uint256 gas2
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (!fromToken.isETH() && destToken.isETH()) {
                                                      (rets, gas) = _calculateUniswap(
                                                          midToken,
                                                          destToken,
                                                          _linearInterpolation(amount.mul(1e18).div(midTokenPrice), parts),
                                                          flags
                                                      );
                                                      return (rets, gas + gas1);
                                                  }
                                                  else if (fromToken.isETH() && !destToken.isETH()) {
                                                      (rets, gas) = _calculateUniswap(
                                                          fromToken,
                                                          midToken,
                                                          _linearInterpolation(amount, parts),
                                                          flags
                                                      );
                                          
                                                      for (uint i = 0; i < parts; i++) {
                                                          rets[i] = rets[i].mul(midTokenPrice).div(1e18);
                                                      }
                                                      return (rets, gas + gas2);
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateUniswapCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20 midPreToken;
                                                  if (!fromToken.isETH() && destToken.isETH()) {
                                                      midPreToken = fromToken;
                                                  }
                                                  else if (!destToken.isETH() && fromToken.isETH()) {
                                                      midPreToken = destToken;
                                                  }
                                          
                                                  if (!midPreToken.isETH()) {
                                                      ICompoundToken midToken = compoundRegistry.cTokenByToken(midPreToken);
                                                      if (midToken != ICompoundToken(0)) {
                                                          return _calculateUniswapWrapped(
                                                              fromToken,
                                                              midToken,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              midToken.exchangeRateStored(),
                                                              flags,
                                                              200_000,
                                                              200_000
                                                          );
                                                      }
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateUniswapChai(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken == dai && destToken.isETH() ||
                                                      fromToken.isETH() && destToken == dai)
                                                  {
                                                      return _calculateUniswapWrapped(
                                                          fromToken,
                                                          chai,
                                                          destToken,
                                                          amount,
                                                          parts,
                                                          chai.chaiPrice(),
                                                          flags,
                                                          180_000,
                                                          160_000
                                                      );
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateUniswapAave(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IERC20 midPreToken;
                                                  if (!fromToken.isETH() && destToken.isETH()) {
                                                      midPreToken = fromToken;
                                                  }
                                                  else if (!destToken.isETH() && fromToken.isETH()) {
                                                      midPreToken = destToken;
                                                  }
                                          
                                                  if (!midPreToken.isETH()) {
                                                      IAaveToken midToken = aaveRegistry.aTokenByToken(midPreToken);
                                                      if (midToken != IAaveToken(0)) {
                                                          return _calculateUniswapWrapped(
                                                              fromToken,
                                                              midToken,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              1e18,
                                                              flags,
                                                              310_000,
                                                              670_000
                                                          );
                                                      }
                                                  }
                                          
                                                  return (new uint256[](parts), 0);
                                              }
                                          
                                              function calculateKyber1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0xff4b796265722046707200000000000000000000000000000000000000000000 // 0x63825c174ab367968EC60f061753D3bbD36A0D8F
                                                  );
                                              }
                                          
                                              function calculateKyber2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0xffabcd0000000000000000000000000000000000000000000000000000000000 // 0x7a3370075a54B187d7bD5DceBf0ff2B5552d4F7D
                                                  );
                                              }
                                          
                                              function calculateKyber3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0xff4f6e65426974205175616e7400000000000000000000000000000000000000 // 0x4f32BbE8dFc9efD54345Fc936f9fEF1048746fCF
                                                  );
                                              }
                                          
                                              function calculateKyber4(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  bytes32 reserveId = _kyberReserveIdByTokens(fromToken, destToken);
                                                  if (reserveId == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      reserveId
                                                  );
                                              }
                                          
                                              function _kyberGetRate(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags,
                                                  bytes memory hint
                                              ) private view returns(uint256) {
                                                  (, bytes memory data) = address(kyberNetworkProxy).staticcall(
                                                      abi.encodeWithSelector(
                                                          kyberNetworkProxy.getExpectedRateAfterFee.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount,
                                                          flags.check(1 << 255) ? 10 : 0,
                                                          hint
                                                      )
                                                  );
                                          
                                                  return (data.length == 32) ? abi.decode(data, (uint256)) : 0;
                                              }
                                          
                                              function _calculateKyber(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  bytes32 reserveId
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  bytes memory fromHint;
                                                  bytes memory destHint;
                                                  {
                                                      bytes32[] memory reserveIds = new bytes32[](1);
                                                      reserveIds[0] = reserveId;
                                          
                                                      (bool success, bytes memory data) = address(kyberHintHandler).staticcall(
                                                          abi.encodeWithSelector(
                                                              kyberHintHandler.buildTokenToEthHint.selector,
                                                              fromToken,
                                                              IKyberHintHandler.TradeType.MaskIn,
                                                              reserveIds,
                                                              new uint256[](0)
                                                          )
                                                      );
                                                      fromHint = success ? abi.decode(data, (bytes)) : bytes("");
                                          
                                                      (success, data) = address(kyberHintHandler).staticcall(
                                                          abi.encodeWithSelector(
                                                              kyberHintHandler.buildEthToTokenHint.selector,
                                                              destToken,
                                                              IKyberHintHandler.TradeType.MaskIn,
                                                              reserveIds,
                                                              new uint256[](0)
                                                          )
                                                      );
                                                      destHint = success ? abi.decode(data, (bytes)) : bytes("");
                                                  }
                                          
                                                  uint256 fromTokenDecimals = 10 ** IERC20(fromToken).universalDecimals();
                                                  uint256 destTokenDecimals = 10 ** IERC20(destToken).universalDecimals();
                                                  rets = new uint256[](parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      if (i > 0 && rets[i - 1] == 0) {
                                                          break;
                                                      }
                                                      rets[i] = amount.mul(i + 1).div(parts);
                                          
                                                      if (!fromToken.isETH()) {
                                                          if (fromHint.length == 0) {
                                                              rets[i] = 0;
                                                              break;
                                                          }
                                                          uint256 rate = _kyberGetRate(
                                                              fromToken,
                                                              ETH_ADDRESS,
                                                              rets[i],
                                                              flags,
                                                              fromHint
                                                          );
                                                          rets[i] = rate.mul(rets[i]).div(fromTokenDecimals);
                                                      }
                                          
                                                      if (!destToken.isETH() && rets[i] > 0) {
                                                          if (destHint.length == 0) {
                                                              rets[i] = 0;
                                                              break;
                                                          }
                                                          uint256 rate = _kyberGetRate(
                                                              ETH_ADDRESS,
                                                              destToken,
                                                              rets[i],
                                                              flags.check(1 << 255) ? 10 : 0,
                                                              destHint
                                                          );
                                                          rets[i] = rate.mul(rets[i]).mul(destTokenDecimals).div(1e36);
                                                      }
                                                  }
                                          
                                                  return (rets, 100_000);
                                              }
                                          
                                              function calculateBancor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
                                          
                                                  address[] memory path = bancorFinder.buildBancorPath(
                                                      fromToken.isETH() ? bancorEtherToken : fromToken,
                                                      destToken.isETH() ? bancorEtherToken : destToken
                                                  );
                                          
                                                  rets = _linearInterpolation(amount, parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      (bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)(
                                                          abi.encodeWithSelector(
                                                              bancorNetwork.getReturnByPath.selector,
                                                              path,
                                                              rets[i]
                                                          )
                                                      );
                                                      if (!success || data.length == 0) {
                                                          for (; i < parts; i++) {
                                                              rets[i] = 0;
                                                          }
                                                          break;
                                                      } else {
                                                          (uint256 ret,) = abi.decode(data, (uint256,uint256));
                                                          rets[i] = ret;
                                                      }
                                                  }
                                          
                                                  return (rets, path.length.mul(150_000));
                                              }
                                          
                                              function calculateOasis(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = _linearInterpolation(amount, parts);
                                                  for (uint i = 0; i < parts; i++) {
                                                      (bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)(
                                                          abi.encodeWithSelector(
                                                              oasisExchange.getBuyAmount.selector,
                                                              destToken.isETH() ? weth : destToken,
                                                              fromToken.isETH() ? weth : fromToken,
                                                              rets[i]
                                                          )
                                                      );
                                          
                                                      if (!success || data.length == 0) {
                                                          for (; i < parts; i++) {
                                                              rets[i] = 0;
                                                          }
                                                          break;
                                                      } else {
                                                          rets[i] = abi.decode(data, (uint256));
                                                      }
                                                  }
                                          
                                                  return (rets, 500_000);
                                              }
                                          
                                              function calculateMooniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  IMooniswap mooniswap = mooniswapRegistry.target();
                                                  (bool success, bytes memory data) = address(mooniswap).staticcall.gas(1000000)(
                                                      abi.encodeWithSelector(
                                                          mooniswap.getReturn.selector,
                                                          fromToken,
                                                          destToken,
                                                          amount
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  uint256 maxRet = abi.decode(data, (uint256));
                                                  return (_linearInterpolation(maxRet, parts), 1_000_000);
                                              }
                                          
                                              function calculateUniswapV2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  return _calculateUniswapV2(
                                                      fromToken,
                                                      destToken,
                                                      _linearInterpolation(amount, parts),
                                                      flags
                                                  );
                                              }
                                          
                                              function calculateUniswapV2ETH(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken.isETH() || fromToken == weth || destToken.isETH() || destToken == weth) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateUniswapV2OverMidToken(
                                                      fromToken,
                                                      weth,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags
                                                  );
                                              }
                                          
                                              function calculateUniswapV2DAI(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken == dai || destToken == dai) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateUniswapV2OverMidToken(
                                                      fromToken,
                                                      dai,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags
                                                  );
                                              }
                                          
                                              function calculateUniswapV2USDC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  if (fromToken == usdc || destToken == usdc) {
                                                      return (new uint256[](parts), 0);
                                                  }
                                          
                                                  return _calculateUniswapV2OverMidToken(
                                                      fromToken,
                                                      usdc,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags
                                                  );
                                              }
                                          
                                              function _calculateUniswapV2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256[] memory amounts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = new uint256[](amounts.length);
                                          
                                                  IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
                                                  IERC20 destTokenReal = destToken.isETH() ? weth : destToken;
                                                  IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, destTokenReal);
                                                  if (exchange != IUniswapV2Exchange(0)) {
                                                      uint256 fromTokenBalance = fromTokenReal.universalBalanceOf(address(exchange));
                                                      uint256 destTokenBalance = destTokenReal.universalBalanceOf(address(exchange));
                                                      for (uint i = 0; i < amounts.length; i++) {
                                                          rets[i] = _calculateUniswapFormula(fromTokenBalance, destTokenBalance, amounts[i]);
                                                      }
                                                      return (rets, 50_000);
                                                  }
                                              }
                                          
                                              function _calculateUniswapV2OverMidToken(
                                                  IERC20 fromToken,
                                                  IERC20 midToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  rets = _linearInterpolation(amount, parts);
                                          
                                                  uint256 gas1;
                                                  uint256 gas2;
                                                  (rets, gas1) = _calculateUniswapV2(fromToken, midToken, rets, flags);
                                                  (rets, gas2) = _calculateUniswapV2(midToken, destToken, rets, flags);
                                                  return (rets, gas1 + gas2);
                                              }
                                          
                                              function _calculateNoReturn(
                                                  IERC20 /*fromToken*/,
                                                  IERC20 /*destToken*/,
                                                  uint256 /*amount*/,
                                                  uint256 parts,
                                                  uint256 /*flags*/
                                              ) internal view returns(uint256[] memory rets, uint256 gas) {
                                                  this;
                                                  return (new uint256[](parts), 0);
                                              }
                                          }
                                          
                                          
                                          contract OneSplitBaseWrap is IOneSplit, OneSplitRoot {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags // See constants in IOneSplit.sol
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  _swapFloor(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 /*flags*/ // See constants in IOneSplit.sol
                                              ) internal;
                                          }
                                          
                                          
                                          contract OneSplit is IOneSplit, OneSplitRoot {
                                              IOneSplitView public oneSplitView;
                                          
                                              constructor(IOneSplitView _oneSplitView) public {
                                                  oneSplitView = _oneSplitView;
                                              }
                                          
                                              function() external payable {
                                                  // solium-disable-next-line security/no-tx-origin
                                                  require(msg.sender != tx.origin);
                                              }
                                          
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return oneSplitView.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256 flags  // See constants in IOneSplit.sol
                                              ) public payable returns(uint256 returnAmount) {
                                                  if (fromToken == destToken) {
                                                      return amount;
                                                  }
                                          
                                                  function(IERC20,IERC20,uint256,uint256)[DEXES_COUNT] memory reserves = [
                                                      _swapOnUniswap,
                                                      _swapOnNowhere,
                                                      _swapOnBancor,
                                                      _swapOnOasis,
                                                      _swapOnCurveCompound,
                                                      _swapOnCurveUSDT,
                                                      _swapOnCurveY,
                                                      _swapOnCurveBinance,
                                                      _swapOnCurveSynthetix,
                                                      _swapOnUniswapCompound,
                                                      _swapOnUniswapChai,
                                                      _swapOnUniswapAave,
                                                      _swapOnMooniswap,
                                                      _swapOnUniswapV2,
                                                      _swapOnUniswapV2ETH,
                                                      _swapOnUniswapV2DAI,
                                                      _swapOnUniswapV2USDC,
                                                      _swapOnCurvePAX,
                                                      _swapOnCurveRenBTC,
                                                      _swapOnCurveTBTC,
                                                      _swapOnDforceSwap,
                                                      _swapOnShell,
                                                      _swapOnMStableMUSD,
                                                      _swapOnCurveSBTC,
                                                      _swapOnBalancer1,
                                                      _swapOnBalancer2,
                                                      _swapOnBalancer3,
                                                      _swapOnKyber1,
                                                      _swapOnKyber2,
                                                      _swapOnKyber3,
                                                      _swapOnKyber4
                                                  ];
                                          
                                                  require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size");
                                          
                                                  uint256 parts = 0;
                                                  uint256 lastNonZeroIndex = 0;
                                                  for (uint i = 0; i < distribution.length; i++) {
                                                      if (distribution[i] > 0) {
                                                          parts = parts.add(distribution[i]);
                                                          lastNonZeroIndex = i;
                                                      }
                                                  }
                                          
                                                  if (parts == 0) {
                                                      if (fromToken.isETH()) {
                                                          msg.sender.transfer(msg.value);
                                                          return msg.value;
                                                      }
                                                      return amount;
                                                  }
                                          
                                                  fromToken.universalTransferFrom(msg.sender, address(this), amount);
                                                  uint256 remainingAmount = fromToken.universalBalanceOf(address(this));
                                          
                                                  for (uint i = 0; i < distribution.length; i++) {
                                                      if (distribution[i] == 0) {
                                                          continue;
                                                      }
                                          
                                                      uint256 swapAmount = amount.mul(distribution[i]).div(parts);
                                                      if (i == lastNonZeroIndex) {
                                                          swapAmount = remainingAmount;
                                                      }
                                                      remainingAmount -= swapAmount;
                                                      reserves[i](fromToken, destToken, swapAmount, flags);
                                                  }
                                          
                                                  returnAmount = destToken.universalBalanceOf(address(this));
                                                  require(returnAmount >= minReturn, "OneSplit: Return amount was not enough");
                                                  destToken.universalTransfer(msg.sender, returnAmount);
                                                  fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
                                              }
                                          
                                              // Swap helpers
                                          
                                              function _swapOnCurveCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveCompound), amount);
                                                  curveCompound.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveUSDT(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveUSDT), amount);
                                                  curveUSDT.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveY(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == tusd ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == tusd ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveY), amount);
                                                  curveY.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveBinance(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == busd ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == busd ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveBinance), amount);
                                                  curveBinance.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveSynthetix(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == susd ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == susd ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveSynthetix), amount);
                                                  curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurvePAX(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == dai ? 1 : 0) +
                                                      (fromToken == usdc ? 2 : 0) +
                                                      (fromToken == usdt ? 3 : 0) +
                                                      (fromToken == pax ? 4 : 0);
                                                  int128 j = (destToken == dai ? 1 : 0) +
                                                      (destToken == usdc ? 2 : 0) +
                                                      (destToken == usdt ? 3 : 0) +
                                                      (destToken == pax ? 4 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curvePAX), amount);
                                                  curvePAX.exchange_underlying(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnShell(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  fromToken.universalApprove(address(shell), amount);
                                                  shell.swapByOrigin(
                                                      address(fromToken),
                                                      address(destToken),
                                                      amount,
                                                      0,
                                                      now + 50
                                                  );
                                              }
                                          
                                              function _swapOnMStableMUSD(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  fromToken.universalApprove(address(musd), amount);
                                                  musd.swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      address(this)
                                                  );
                                              }
                                          
                                              function _swapOnCurveRenBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == renbtc ? 1 : 0) +
                                                      (fromToken == wbtc ? 2 : 0);
                                                  int128 j = (destToken == renbtc ? 1 : 0) +
                                                      (destToken == wbtc ? 2 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveRenBTC), amount);
                                                  curveRenBTC.exchange(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveTBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == tbtc ? 1 : 0) +
                                                      (fromToken == wbtc ? 2 : 0) +
                                                      (fromToken == hbtc ? 3 : 0);
                                                  int128 j = (destToken == tbtc ? 1 : 0) +
                                                      (destToken == wbtc ? 2 : 0) +
                                                      (destToken == hbtc ? 3 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveTBTC), amount);
                                                  curveTBTC.exchange(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnCurveSBTC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  int128 i = (fromToken == renbtc ? 1 : 0) +
                                                      (fromToken == wbtc ? 2 : 0) +
                                                      (fromToken == sbtc ? 3 : 0);
                                                  int128 j = (destToken == renbtc ? 1 : 0) +
                                                      (destToken == wbtc ? 2 : 0) +
                                                      (destToken == sbtc ? 3 : 0);
                                                  if (i == 0 || j == 0) {
                                                      return;
                                                  }
                                          
                                                  fromToken.universalApprove(address(curveSBTC), amount);
                                                  curveSBTC.exchange(i - 1, j - 1, amount, 0);
                                              }
                                          
                                              function _swapOnDforceSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  fromToken.universalApprove(address(dforceSwap), amount);
                                                  dforceSwap.swap(fromToken, destToken, amount);
                                              }
                                          
                                              function _swapOnUniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  uint256 returnAmount = amount;
                                          
                                                  if (!fromToken.isETH()) {
                                                      IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
                                                      if (fromExchange != IUniswapExchange(0)) {
                                                          fromToken.universalApprove(address(fromExchange), returnAmount);
                                                          returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now);
                                                      }
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      IUniswapExchange toExchange = uniswapFactory.getExchange(destToken);
                                                      if (toExchange != IUniswapExchange(0)) {
                                                          returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now);
                                                      }
                                                  }
                                              }
                                          
                                              function _swapOnUniswapCompound(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  if (!fromToken.isETH()) {
                                                      ICompoundToken fromCompound = compoundRegistry.cTokenByToken(fromToken);
                                                      fromToken.universalApprove(address(fromCompound), amount);
                                                      fromCompound.mint(amount);
                                                      _swapOnUniswap(IERC20(fromCompound), destToken, IERC20(fromCompound).universalBalanceOf(address(this)), flags);
                                                      return;
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      ICompoundToken toCompound = compoundRegistry.cTokenByToken(destToken);
                                                      _swapOnUniswap(fromToken, IERC20(toCompound), amount, flags);
                                                      toCompound.redeem(IERC20(toCompound).universalBalanceOf(address(this)));
                                                      destToken.universalBalanceOf(address(this));
                                                      return;
                                                  }
                                              }
                                          
                                              function _swapOnUniswapChai(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == dai) {
                                                      fromToken.universalApprove(address(chai), amount);
                                                      chai.join(address(this), amount);
                                                      _swapOnUniswap(IERC20(chai), destToken, IERC20(chai).universalBalanceOf(address(this)), flags);
                                                      return;
                                                  }
                                          
                                                  if (destToken == dai) {
                                                      _swapOnUniswap(fromToken, IERC20(chai), amount, flags);
                                                      chai.exit(address(this), chai.balanceOf(address(this)));
                                                      return;
                                                  }
                                              }
                                          
                                              function _swapOnUniswapAave(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  if (!fromToken.isETH()) {
                                                      IAaveToken fromAave = aaveRegistry.aTokenByToken(fromToken);
                                                      fromToken.universalApprove(aave.core(), amount);
                                                      aave.deposit(fromToken, amount, 1101);
                                                      _swapOnUniswap(IERC20(fromAave), destToken, IERC20(fromAave).universalBalanceOf(address(this)), flags);
                                                      return;
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      IAaveToken toAave = aaveRegistry.aTokenByToken(destToken);
                                                      _swapOnUniswap(fromToken, IERC20(toAave), amount, flags);
                                                      toAave.redeem(toAave.balanceOf(address(this)));
                                                      return;
                                                  }
                                              }
                                          
                                              function _swapOnMooniswap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  IMooniswap mooniswap = mooniswapRegistry.target();
                                                  fromToken.universalApprove(address(mooniswap), amount);
                                                  mooniswap.swap.value(fromToken.isETH() ? amount : 0)(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      0
                                                  );
                                              }
                                          
                                              function _swapOnNowhere(
                                                  IERC20 /*fromToken*/,
                                                  IERC20 /*destToken*/,
                                                  uint256 /*amount*/,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  revert("This source was deprecated");
                                              }
                                          
                                              function _swapOnKyber1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      0xff4b796265722046707200000000000000000000000000000000000000000000
                                                  );
                                              }
                                          
                                              function _swapOnKyber2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      0xffabcd0000000000000000000000000000000000000000000000000000000000
                                                  );
                                              }
                                          
                                              function _swapOnKyber3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      0xff4f6e65426974205175616e7400000000000000000000000000000000000000
                                                  );
                                              }
                                          
                                              function _swapOnKyber4(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnKyber(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags,
                                                      _kyberReserveIdByTokens(fromToken, destToken)
                                                  );
                                              }
                                          
                                              function _swapOnKyber(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags,
                                                  bytes32 reserveId
                                              ) internal {
                                                  uint256 returnAmount = amount;
                                                  uint256 bps = flags.check(1 << 255) ? 10 : 0;
                                          
                                                  bytes32[] memory reserveIds = new bytes32[](1);
                                                  reserveIds[0] = reserveId;
                                          
                                                  if (!fromToken.isETH()) {
                                                      bytes memory fromHint = kyberHintHandler.buildTokenToEthHint(
                                                          fromToken,
                                                          IKyberHintHandler.TradeType.MaskIn,
                                                          reserveIds,
                                                          new uint256[](0)
                                                      );
                                          
                                                      fromToken.universalApprove(address(kyberNetworkProxy), amount);
                                                      returnAmount = kyberNetworkProxy.tradeWithHintAndFee(
                                                          fromToken,
                                                          returnAmount,
                                                          ETH_ADDRESS,
                                                          address(this),
                                                          uint256(-1),
                                                          0,
                                                          0x4D37f28D2db99e8d35A6C725a5f1749A085850a3,
                                                          bps,
                                                          fromHint
                                                      );
                                                  }
                                          
                                                  if (!destToken.isETH()) {
                                                      bytes memory destHint = kyberHintHandler.buildEthToTokenHint(
                                                          destToken,
                                                          IKyberHintHandler.TradeType.MaskIn,
                                                          reserveIds,
                                                          new uint256[](0)
                                                      );
                                          
                                                      returnAmount = kyberNetworkProxy.tradeWithHintAndFee.value(returnAmount)(
                                                          ETH_ADDRESS,
                                                          returnAmount,
                                                          destToken,
                                                          address(this),
                                                          uint256(-1),
                                                          0,
                                                          0x4D37f28D2db99e8d35A6C725a5f1749A085850a3,
                                                          bps,
                                                          destHint
                                                      );
                                                  }
                                              }
                                          
                                              function _swapOnBancor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
                                                  address[] memory path = bancorNetworkPathFinder.generatePath(
                                                      fromToken.isETH() ? bancorEtherToken : fromToken,
                                                      destToken.isETH() ? bancorEtherToken : destToken
                                                  );
                                                  fromToken.universalApprove(address(bancorNetwork), amount);
                                                  bancorNetwork.convert.value(fromToken.isETH() ? amount : 0)(path, amount, 1);
                                              }
                                          
                                              function _swapOnOasis(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal {
                                                  if (fromToken.isETH()) {
                                                      weth.deposit.value(amount)();
                                                  }
                                          
                                                  IERC20 approveToken = fromToken.isETH() ? weth : fromToken;
                                                  approveToken.universalApprove(address(oasisExchange), amount);
                                                  oasisExchange.sellAllAmount(
                                                      fromToken.isETH() ? weth : fromToken,
                                                      amount,
                                                      destToken.isETH() ? weth : destToken,
                                                      1
                                                  );
                                          
                                                  if (destToken.isETH()) {
                                                      weth.withdraw(weth.balanceOf(address(this)));
                                                  }
                                              }
                                          
                                              function _swapOnUniswapV2Internal(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/
                                              ) internal returns(uint256 returnAmount) {
                                                  if (fromToken.isETH()) {
                                                      weth.deposit.value(amount)();
                                                  }
                                          
                                                  IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken;
                                                  IERC20 toTokenReal = destToken.isETH() ? weth : destToken;
                                                  IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal);
                                                  returnAmount = exchange.getReturn(fromTokenReal, toTokenReal, amount);
                                          
                                                  fromTokenReal.universalTransfer(address(exchange), amount);
                                                  if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) {
                                                      exchange.swap(0, returnAmount, address(this), "");
                                                  } else {
                                                      exchange.swap(returnAmount, 0, address(this), "");
                                                  }
                                          
                                                  if (destToken.isETH()) {
                                                      weth.withdraw(weth.balanceOf(address(this)));
                                                  }
                                              }
                                          
                                              function _swapOnUniswapV2OverMid(
                                                  IERC20 fromToken,
                                                  IERC20 midToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2Internal(
                                                      midToken,
                                                      destToken,
                                                      _swapOnUniswapV2Internal(
                                                          fromToken,
                                                          midToken,
                                                          amount,
                                                          flags
                                                      ),
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2Internal(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2ETH(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2OverMid(
                                                      fromToken,
                                                      weth,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2DAI(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2OverMid(
                                                      fromToken,
                                                      dai,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnUniswapV2USDC(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnUniswapV2OverMid(
                                                      fromToken,
                                                      usdc,
                                                      destToken,
                                                      amount,
                                                      flags
                                                  );
                                              }
                                          
                                              function _swapOnBalancerX(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 /*flags*/,
                                                  uint256 poolIndex
                                              ) internal {
                                                  address[] memory pools = balancerRegistry.getBestPoolsWithLimit(
                                                      address(fromToken.isETH() ? weth : fromToken),
                                                      address(destToken.isETH() ? weth : destToken),
                                                      poolIndex + 1
                                                  );
                                          
                                                  if (fromToken.isETH()) {
                                                      weth.deposit.value(amount)();
                                                  }
                                          
                                                  (fromToken.isETH() ? weth : fromToken).universalApprove(pools[poolIndex], amount);
                                                  IBalancerPool(pools[poolIndex]).swapExactAmountIn(
                                                      fromToken.isETH() ? weth : fromToken,
                                                      amount,
                                                      destToken.isETH() ? weth : destToken,
                                                      0,
                                                      uint256(-1)
                                                  );
                                          
                                                  if (destToken.isETH()) {
                                                      weth.withdraw(weth.balanceOf(address(this)));
                                                  }
                                              }
                                          
                                              function _swapOnBalancer1(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnBalancerX(fromToken, destToken, amount, flags, 0);
                                              }
                                          
                                              function _swapOnBalancer2(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnBalancerX(fromToken, destToken, amount, flags, 1);
                                              }
                                          
                                              function _swapOnBalancer3(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 flags
                                              ) internal {
                                                  _swapOnBalancerX(fromToken, destToken, amount, flags, 2);
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitCompound.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitCompoundView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _compoundGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _compoundGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
                                                      IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored();
                                                          (returnAmount, estimateGasAmount, distribution) = _compoundGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount.mul(compoundRate).div(1e18),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 295_000, distribution);
                                                      }
                                          
                                                      underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                          uint256 compoundRate = ICompoundToken(address(destToken)).exchangeRateStored();
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              _destTokenEthPriceTimesGasPrice.mul(compoundRate).div(1e18)
                                                          );
                                                          return (returnAmount.mul(1e18).div(compoundRate), estimateGasAmount + 430_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitCompound is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _compoundSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _compoundSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) {
                                                      IERC20 underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          ICompoundToken(address(fromToken)).redeem(amount);
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          return _compoundSwap(
                                                              underlying,
                                                              destToken,
                                                              underlyingAmount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = compoundRegistry.tokenByCToken(ICompoundToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          super._swap(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          if (underlying.isETH()) {
                                                              cETH.mint.value(underlyingAmount)();
                                                          } else {
                                                              underlying.universalApprove(address(destToken), underlyingAmount);
                                                              ICompoundToken(address(destToken)).mint(underlyingAmount);
                                                          }
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/interface/IFulcrum.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IFulcrumToken is IERC20 {
                                              function tokenPrice() external view returns (uint256);
                                          
                                              function loanTokenAddress() external view returns (address);
                                          
                                              function mintWithEther(address receiver) external payable returns (uint256 mintAmount);
                                          
                                              function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
                                          
                                              function burnToEther(address receiver, uint256 burnAmount)
                                                  external
                                                  returns (uint256 loanAmountPaid);
                                          
                                              function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
                                          }
                                          
                                          // File: contracts/OneSplitFulcrum.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitFulcrumBase {
                                              using UniversalERC20 for IERC20;
                                          
                                              function _isFulcrumToken(IERC20 token) internal view returns(IERC20) {
                                                  if (token.isETH()) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  (bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSignature(
                                                      "name()"
                                                  ));
                                                  if (!success) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  bool foundBZX = false;
                                                  for (uint i = 0; i + 6 < data.length; i++) {
                                                      if (data[i + 0] == "F" &&
                                                          data[i + 1] == "u" &&
                                                          data[i + 2] == "l" &&
                                                          data[i + 3] == "c" &&
                                                          data[i + 4] == "r" &&
                                                          data[i + 5] == "u" &&
                                                          data[i + 6] == "m")
                                                      {
                                                          foundBZX = true;
                                                          break;
                                                      }
                                                  }
                                                  if (!foundBZX) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  (success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
                                                      IFulcrumToken(address(token)).loanTokenAddress.selector
                                                  ));
                                                  if (!success) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  return abi.decode(data, (IERC20));
                                              }
                                          }
                                          
                                          
                                          contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _fulcrumGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _fulcrumGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
                                                      IERC20 underlying = _isFulcrumToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice();
                                                          (returnAmount, estimateGasAmount, distribution) = _fulcrumGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount.mul(fulcrumRate).div(1e18),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 381_000, distribution);
                                                      }
                                          
                                                      underlying = _isFulcrumToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                          uint256 fulcrumRate = IFulcrumToken(address(destToken)).tokenPrice();
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              _destTokenEthPriceTimesGasPrice.mul(fulcrumRate).div(1e18)
                                                          );
                                                          return (returnAmount.mul(1e18).div(fulcrumRate), estimateGasAmount + 354_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _fulcrumSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _fulcrumSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) {
                                                      IERC20 underlying = _isFulcrumToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          if (underlying.isETH()) {
                                                              IFulcrumToken(address(fromToken)).burnToEther(address(this), amount);
                                                          } else {
                                                              IFulcrumToken(address(fromToken)).burn(address(this), amount);
                                                          }
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          return super._swap(
                                                              underlying,
                                                              destToken,
                                                              underlyingAmount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = _isFulcrumToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          super._swap(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          if (underlying.isETH()) {
                                                              IFulcrumToken(address(destToken)).mintWithEther.value(underlyingAmount)(address(this));
                                                          } else {
                                                              underlying.universalApprove(address(destToken), underlyingAmount);
                                                              IFulcrumToken(address(destToken)).mint(address(this), underlyingAmount);
                                                          }
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitChai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitChaiView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
                                                      if (fromToken == IERC20(chai)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              dai,
                                                              destToken,
                                                              chai.chaiToDai(amount),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 197_000, distribution);
                                                      }
                                          
                                                      if (destToken == IERC20(chai)) {
                                                          uint256 price = chai.chaiPrice();
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              dai,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice.mul(1e18).div(price)
                                                          );
                                                          return (returnAmount.mul(price).div(1e18), estimateGasAmount + 168_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitChai is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) {
                                                      if (fromToken == IERC20(chai)) {
                                                          chai.exit(address(this), amount);
                                          
                                                          return super._swap(
                                                              dai,
                                                              destToken,
                                                              dai.balanceOf(address(this)),
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      if (destToken == IERC20(chai)) {
                                                          super._swap(
                                                              fromToken,
                                                              dai,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 daiBalance = dai.balanceOf(address(this));
                                                          dai.universalApprove(address(chai), daiBalance);
                                                          chai.join(address(this), daiBalance);
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/interface/IBdai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IBdai is IERC20 {
                                              function join(uint256) external;
                                          
                                              function exit(uint256) external;
                                          }
                                          
                                          // File: contracts/OneSplitBdai.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitBdaiBase {
                                              IBdai internal constant bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8);
                                              IERC20 internal constant btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f);
                                          }
                                          
                                          
                                          contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
                                                      if (fromToken == IERC20(bdai)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              dai,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 227_000, distribution);
                                                      }
                                          
                                                      if (destToken == IERC20(bdai)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              dai,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 295_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) {
                                                      if (fromToken == IERC20(bdai)) {
                                                          bdai.exit(amount);
                                          
                                                          uint256 btuBalance = btu.balanceOf(address(this));
                                                          if (btuBalance > 0) {
                                                              (,uint256[] memory btuDistribution) = getExpectedReturn(
                                                                  btu,
                                                                  destToken,
                                                                  btuBalance,
                                                                  1,
                                                                  flags
                                                              );
                                          
                                                              _swap(
                                                                  btu,
                                                                  destToken,
                                                                  btuBalance,
                                                                  btuDistribution,
                                                                  flags
                                                              );
                                                          }
                                          
                                                          return super._swap(
                                                              dai,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      if (destToken == IERC20(bdai)) {
                                                          super._swap(fromToken, dai, amount, distribution, flags);
                                          
                                                          uint256 daiBalance = dai.balanceOf(address(this));
                                                          dai.universalApprove(address(bdai), daiBalance);
                                                          bdai.join(daiBalance);
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(fromToken, destToken, amount, distribution, flags);
                                              }
                                          }
                                          
                                          // File: contracts/interface/IIearn.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IIearn is IERC20 {
                                              function token() external view returns(IERC20);
                                          
                                              function calcPoolValueInToken() external view returns(uint256);
                                          
                                              function deposit(uint256 _amount) external;
                                          
                                              function withdraw(uint256 _shares) external;
                                          }
                                          
                                          // File: contracts/OneSplitIearn.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitIearnBase {
                                              function _yTokens() internal pure returns(IIearn[13] memory) {
                                                  return [
                                                      IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01),
                                                      IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9),
                                                      IIearn(0x73a052500105205d34Daf004eAb301916DA8190f),
                                                      IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D),
                                                      IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e),
                                                      IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600),
                                                      IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE),
                                                      IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32),
                                                      IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447),
                                                      IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951),
                                                      IIearn(0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc),
                                                      IIearn(0x9777d7E2b60bB01759D0E2f8be2095df444cb07E),
                                                      IIearn(0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59)
                                                  ];
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _iearnGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _iearnGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IEARN)) {
                                                      IIearn[13] memory yTokens = _yTokens();
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (fromToken == IERC20(yTokens[i])) {
                                                              (returnAmount, estimateGasAmount, distribution) = _iearnGetExpectedReturn(
                                                                  yTokens[i].token(),
                                                                  destToken,
                                                                  amount
                                                                      .mul(yTokens[i].calcPoolValueInToken())
                                                                      .div(yTokens[i].totalSupply()),
                                                                  parts,
                                                                  flags,
                                                                  destTokenEthPriceTimesGasPrice
                                                              );
                                                              return (returnAmount, estimateGasAmount + 260_000, distribution);
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (destToken == IERC20(yTokens[i])) {
                                                              uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                              IERC20 token = yTokens[i].token();
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  fromToken,
                                                                  token,
                                                                  amount,
                                                                  parts,
                                                                  flags,
                                                                  _destTokenEthPriceTimesGasPrice
                                                                      .mul(yTokens[i].calcPoolValueInToken())
                                                                      .div(yTokens[i].totalSupply())
                                                              );
                                          
                                                              return(
                                                                  returnAmount
                                                                      .mul(yTokens[i].totalSupply())
                                                                      .div(yTokens[i].calcPoolValueInToken()),
                                                                  estimateGasAmount + 743_000,
                                                                  distribution
                                                              );
                                                          }
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _iearnSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _iearnSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_IEARN)) {
                                                      IIearn[13] memory yTokens = _yTokens();
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (fromToken == IERC20(yTokens[i])) {
                                                              IERC20 underlying = yTokens[i].token();
                                                              yTokens[i].withdraw(amount);
                                                              _iearnSwap(underlying, destToken, underlying.balanceOf(address(this)), distribution, flags);
                                                              return;
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < yTokens.length; i++) {
                                                          if (destToken == IERC20(yTokens[i])) {
                                                              IERC20 underlying = yTokens[i].token();
                                                              super._swap(fromToken, underlying, amount, distribution, flags);
                                          
                                                              uint256 underlyingBalance = underlying.balanceOf(address(this));
                                                              underlying.universalApprove(address(yTokens[i]), underlyingBalance);
                                                              yTokens[i].deposit(underlyingBalance);
                                                              return;
                                                          }
                                                      }
                                                  }
                                          
                                                  return super._swap(fromToken, destToken, amount, distribution, flags);
                                              }
                                          }
                                          
                                          // File: contracts/interface/IIdle.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IIdle is IERC20 {
                                              function token()
                                                  external view returns (IERC20);
                                          
                                              function tokenPrice()
                                                  external view returns (uint256);
                                          
                                              function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts)
                                                  external returns (uint256 mintedTokens);
                                          
                                              function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts)
                                                  external returns (uint256 redeemedTokens);
                                          }
                                          
                                          // File: contracts/OneSplitIdle.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitIdleBase {
                                              function _idleTokens() internal pure returns(IIdle[8] memory) {
                                                  // https://developers.idle.finance/contracts-and-codebase
                                                  return [
                                                      // V3
                                                      IIdle(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934),
                                                      IIdle(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6),
                                                      IIdle(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D),
                                                      IIdle(0x1846bdfDB6A0f5c473dEc610144513bd071999fB),
                                                      IIdle(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C),
                                                      IIdle(0x42740698959761BAF1B06baa51EfBD88CB1D862B),
                                                      // V2
                                                      IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD),
                                                      IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991)
                                                  ];
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _idleGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _idleGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  internal
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
                                                      IIdle[8] memory tokens = _idleTokens();
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (fromToken == IERC20(tokens[i])) {
                                                              (returnAmount, estimateGasAmount, distribution) = _idleGetExpectedReturn(
                                                                  tokens[i].token(),
                                                                  destToken,
                                                                  amount.mul(tokens[i].tokenPrice()).div(1e18),
                                                                  parts,
                                                                  flags,
                                                                  destTokenEthPriceTimesGasPrice
                                                              );
                                                              return (returnAmount, estimateGasAmount + 2_400_000, distribution);
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (destToken == IERC20(tokens[i])) {
                                                              uint256 _destTokenEthPriceTimesGasPrice = destTokenEthPriceTimesGasPrice;
                                                              uint256 _price = tokens[i].tokenPrice();
                                                              IERC20 token = tokens[i].token();
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  fromToken,
                                                                  token,
                                                                  amount,
                                                                  parts,
                                                                  flags,
                                                                  _destTokenEthPriceTimesGasPrice.mul(_price).div(1e18)
                                                              );
                                                              return (returnAmount.mul(1e18).div(_price), estimateGasAmount + 1_300_000, distribution);
                                                          }
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _idleSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _idleSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) {
                                                      IIdle[8] memory tokens = _idleTokens();
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (fromToken == IERC20(tokens[i])) {
                                                              IERC20 underlying = tokens[i].token();
                                                              uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0));
                                                              _idleSwap(underlying, destToken, minted, distribution, flags);
                                                              return;
                                                          }
                                                      }
                                          
                                                      for (uint i = 0; i < tokens.length; i++) {
                                                          if (destToken == IERC20(tokens[i])) {
                                                              IERC20 underlying = tokens[i].token();
                                                              super._swap(fromToken, underlying, amount, distribution, flags);
                                          
                                                              uint256 underlyingBalance = underlying.balanceOf(address(this));
                                                              underlying.universalApprove(address(tokens[i]), underlyingBalance);
                                                              tokens[i].mintIdleToken(underlyingBalance, new uint256[](0));
                                                              return;
                                                          }
                                                      }
                                                  }
                                          
                                                  return super._swap(fromToken, destToken, amount, distribution, flags);
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitAave.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitAaveView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _aaveGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _aaveGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
                                                      IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          (returnAmount, estimateGasAmount, distribution) = _aaveGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 670_000, distribution);
                                                      }
                                          
                                                      underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 310_000, distribution);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitAave is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _aaveSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _aaveSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) {
                                                      IERC20 underlying = aaveRegistry.tokenByAToken(IAaveToken(address(fromToken)));
                                                      if (underlying != IERC20(0)) {
                                                          IAaveToken(address(fromToken)).redeem(amount);
                                          
                                                          return _aaveSwap(
                                                              underlying,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = aaveRegistry.tokenByAToken(IAaveToken(address(destToken)));
                                                      if (underlying != IERC20(0)) {
                                                          super._swap(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
                                          
                                                          underlying.universalApprove(aave.core(), underlyingAmount);
                                                          aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)(
                                                              underlying.isETH() ? ETH_ADDRESS : underlying,
                                                              underlyingAmount,
                                                              1101
                                                          );
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitWeth.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitWethView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _wethGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _wethGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
                                                      if (fromToken == weth || fromToken == bancorEtherToken) {
                                                          return super.getExpectedReturnWithGas(ETH_ADDRESS, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice);
                                                      }
                                          
                                                      if (destToken == weth || destToken == bancorEtherToken) {
                                                          return super.getExpectedReturnWithGas(fromToken, ETH_ADDRESS, amount, parts, flags, destTokenEthPriceTimesGasPrice);
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitWeth is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _wethSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _wethSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) {
                                                      if (fromToken == weth) {
                                                          weth.withdraw(weth.balanceOf(address(this)));
                                                          super._swap(
                                                              ETH_ADDRESS,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          return;
                                                      }
                                          
                                                      if (fromToken == bancorEtherToken) {
                                                          bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
                                                          super._swap(
                                                              ETH_ADDRESS,
                                                              destToken,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          return;
                                                      }
                                          
                                                      if (destToken == weth) {
                                                          _wethSwap(
                                                              fromToken,
                                                              ETH_ADDRESS,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          weth.deposit.value(address(this).balance)();
                                                          return;
                                                      }
                                          
                                                      if (destToken == bancorEtherToken) {
                                                          _wethSwap(
                                                              fromToken,
                                                              ETH_ADDRESS,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                                          bancorEtherToken.deposit.value(address(this).balance)();
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplitMStable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitMStableView is OneSplitViewWrapBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
                                                      if (fromToken == IERC20(musd)) {
                                                          if (destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd) {
                                                              (,, returnAmount) = musd_helper.getRedeemValidity(fromToken, amount, destToken);
                                                              return (returnAmount, 300_000, new uint256[](DEXES_COUNT));
                                                          }
                                                          else {
                                                              (,, returnAmount) = musd_helper.getRedeemValidity(fromToken, amount, dai);
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  dai,
                                                                  destToken,
                                                                  returnAmount,
                                                                  parts,
                                                                  flags,
                                                                  destTokenEthPriceTimesGasPrice
                                                              );
                                                              return (returnAmount, estimateGasAmount + 300_000, distribution);
                                                          }
                                                      }
                                          
                                                      if (destToken == IERC20(musd)) {
                                                          if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
                                                              (,, returnAmount) = musd.getSwapOutput(fromToken, destToken, amount);
                                                              return (returnAmount, 300_000, new uint256[](DEXES_COUNT));
                                                          }
                                                          else {
                                                              IERC20 _destToken = destToken;
                                                              (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                                  fromToken,
                                                                  dai,
                                                                  amount,
                                                                  parts,
                                                                  flags,
                                                                  _scaleDestTokenEthPriceTimesGasPrice(
                                                                      _destToken,
                                                                      dai,
                                                                      destTokenEthPriceTimesGasPrice
                                                                  )
                                                              );
                                                              (,, returnAmount) = musd_helper.getRedeemValidity(dai, returnAmount, destToken);
                                                              return (returnAmount, estimateGasAmount + 300_000, distribution);
                                                          }
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitMStable is OneSplitBaseWrap {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) {
                                                      if (fromToken == IERC20(musd)) {
                                                          if (destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd) {
                                                              (,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, destToken);
                                                              musd.redeem(
                                                                  destToken,
                                                                  result
                                                              );
                                                          }
                                                          else {
                                                              (,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, dai);
                                                              musd.redeem(
                                                                  dai,
                                                                  result
                                                              );
                                                              super._swap(
                                                                  dai,
                                                                  destToken,
                                                                  dai.balanceOf(address(this)),
                                                                  distribution,
                                                                  flags
                                                              );
                                                          }
                                                          return;
                                                      }
                                          
                                                      if (destToken == IERC20(musd)) {
                                                          if (fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd) {
                                                              fromToken.universalApprove(address(musd), amount);
                                                              musd.swap(
                                                                  fromToken,
                                                                  destToken,
                                                                  amount,
                                                                  address(this)
                                                              );
                                                          }
                                                          else {
                                                              super._swap(
                                                                  fromToken,
                                                                  dai,
                                                                  amount,
                                                                  distribution,
                                                                  flags
                                                              );
                                                              musd.swap(
                                                                  dai,
                                                                  destToken,
                                                                  dai.balanceOf(address(this)),
                                                                  address(this)
                                                              );
                                                          }
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/interface/IDMM.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IDMMController {
                                              function getUnderlyingTokenForDmm(IERC20 token) external view returns(IERC20);
                                          }
                                          
                                          
                                          contract IDMM is IERC20 {
                                              function getCurrentExchangeRate() public view returns(uint256);
                                              function mint(uint256 underlyingAmount) public returns(uint256);
                                              function redeem(uint256 amount) public returns(uint256);
                                          }
                                          
                                          // File: contracts/OneSplitDMM.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract OneSplitDMMBase {
                                              IDMMController internal constant _dmmController = IDMMController(0x4CB120Dd1D33C9A3De8Bc15620C7Cd43418d77E2);
                                          
                                              function _getDMMUnderlyingToken(IERC20 token) internal view returns(IERC20) {
                                                  (bool success, bytes memory data) = address(_dmmController).staticcall(
                                                      abi.encodeWithSelector(
                                                          _dmmController.getUnderlyingTokenForDmm.selector,
                                                          token
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return IERC20(-1);
                                                  }
                                          
                                                  return abi.decode(data, (IERC20));
                                              }
                                          
                                              function _getDMMExchangeRate(IDMM dmm) internal view returns(uint256) {
                                                  (bool success, bytes memory data) = address(dmm).staticcall(
                                                      abi.encodeWithSelector(
                                                          dmm.getCurrentExchangeRate.selector
                                                      )
                                                  );
                                          
                                                  if (!success || data.length == 0) {
                                                      return 0;
                                                  }
                                          
                                                  return abi.decode(data, (uint256));
                                              }
                                          }
                                          
                                          
                                          contract OneSplitDMMView is OneSplitViewWrapBase, OneSplitDMMBase {
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return _dmmGetExpectedReturn(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _dmmGetExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  private
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
                                                      IERC20 underlying = _getDMMUnderlyingToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          if (underlying == weth) {
                                                              underlying = ETH_ADDRESS;
                                                          }
                                                          IERC20 _fromToken = fromToken;
                                                          (returnAmount, estimateGasAmount, distribution) = _dmmGetExpectedReturn(
                                                              underlying,
                                                              destToken,
                                                              amount.mul(_getDMMExchangeRate(IDMM(address(_fromToken)))).div(1e18),
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice
                                                          );
                                                          return (returnAmount, estimateGasAmount + 295_000, distribution);
                                                      }
                                          
                                                      underlying = _getDMMUnderlyingToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          if (underlying == weth) {
                                                              underlying = ETH_ADDRESS;
                                                          }
                                                          uint256 price = _getDMMExchangeRate(IDMM(address(destToken)));
                                                          (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas(
                                                              fromToken,
                                                              underlying,
                                                              amount,
                                                              parts,
                                                              flags,
                                                              destTokenEthPriceTimesGasPrice.mul(price).div(1e18)
                                                          );
                                                          return (
                                                              returnAmount.mul(1e18).div(price),
                                                              estimateGasAmount + 430_000,
                                                              distribution
                                                          );
                                                      }
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitDMM is OneSplitBaseWrap, OneSplitDMMBase {
                                              function _swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  _dmmSwap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          
                                              function _dmmSwap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) private {
                                                  if (fromToken == destToken) {
                                                      return;
                                                  }
                                          
                                                  if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_DMM)) {
                                                      IERC20 underlying = _getDMMUnderlyingToken(fromToken);
                                                      if (underlying != IERC20(-1)) {
                                                          IDMM(address(fromToken)).redeem(amount);
                                                          uint256 balance = underlying.universalBalanceOf(address(this));
                                                          if (underlying == weth) {
                                                              weth.withdraw(balance);
                                                          }
                                                          _dmmSwap(
                                                              (underlying == weth) ? ETH_ADDRESS : underlying,
                                                              destToken,
                                                              balance,
                                                              distribution,
                                                              flags
                                                          );
                                                      }
                                          
                                                      underlying = _getDMMUnderlyingToken(destToken);
                                                      if (underlying != IERC20(-1)) {
                                                          super._swap(
                                                              fromToken,
                                                              (underlying == weth) ? ETH_ADDRESS : underlying,
                                                              amount,
                                                              distribution,
                                                              flags
                                                          );
                                          
                                                          uint256 underlyingAmount = ((underlying == weth) ? ETH_ADDRESS : underlying).universalBalanceOf(address(this));
                                                          if (underlying == weth) {
                                                              weth.deposit.value(underlyingAmount);
                                                          }
                                          
                                                          underlying.universalApprove(address(destToken), underlyingAmount);
                                                          IDMM(address(destToken)).mint(underlyingAmount);
                                                          return;
                                                      }
                                                  }
                                          
                                                  return super._swap(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }
                                          
                                          // File: contracts/OneSplit.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract OneSplitViewWrap is
                                              OneSplitViewWrapBase,
                                              OneSplitMStableView,
                                              OneSplitChaiView,
                                              OneSplitBdaiView,
                                              OneSplitAaveView,
                                              OneSplitFulcrumView,
                                              OneSplitCompoundView,
                                              OneSplitIearnView,
                                              OneSplitIdleView,
                                              OneSplitWethView,
                                              OneSplitDMMView
                                          {
                                              IOneSplitView public oneSplitView;
                                          
                                              constructor(IOneSplitView _oneSplit) public {
                                                  oneSplitView = _oneSplit;
                                              }
                                          
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags, // See constants in IOneSplit.sol
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  if (fromToken == destToken) {
                                                      return (amount, 0, new uint256[](DEXES_COUNT));
                                                  }
                                          
                                                  return super.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function _getExpectedReturnRespectingGasFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  internal
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return oneSplitView.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          }
                                          
                                          
                                          contract OneSplitWrap is
                                              OneSplitBaseWrap,
                                              OneSplitMStable,
                                              OneSplitChai,
                                              OneSplitBdai,
                                              OneSplitAave,
                                              OneSplitFulcrum,
                                              OneSplitCompound,
                                              OneSplitIearn,
                                              OneSplitIdle,
                                              OneSplitWeth,
                                              OneSplitDMM
                                          {
                                              IOneSplitView public oneSplitView;
                                              IOneSplit public oneSplit;
                                          
                                              constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public {
                                                  oneSplitView = _oneSplitView;
                                                  oneSplit = _oneSplit;
                                              }
                                          
                                              function() external payable {
                                                  // solium-disable-next-line security/no-tx-origin
                                                  require(msg.sender != tx.origin);
                                              }
                                          
                                              function getExpectedReturn(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  (returnAmount, , distribution) = getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      0
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGas(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 parts,
                                                  uint256 flags,
                                                  uint256 destTokenEthPriceTimesGasPrice
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256 returnAmount,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  return oneSplitView.getExpectedReturnWithGas(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      parts,
                                                      flags,
                                                      destTokenEthPriceTimesGasPrice
                                                  );
                                              }
                                          
                                              function getExpectedReturnWithGasMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256[] memory parts,
                                                  uint256[] memory flags,
                                                  uint256[] memory destTokenEthPriceTimesGasPrices
                                              )
                                                  public
                                                  view
                                                  returns(
                                                      uint256[] memory returnAmounts,
                                                      uint256 estimateGasAmount,
                                                      uint256[] memory distribution
                                                  )
                                              {
                                                  uint256[] memory dist;
                                          
                                                  returnAmounts = new uint256[](tokens.length - 1);
                                                  for (uint i = 1; i < tokens.length; i++) {
                                                      if (tokens[i - 1] == tokens[i]) {
                                                          returnAmounts[i - 1] = (i == 1) ? amount : returnAmounts[i - 2];
                                                          continue;
                                                      }
                                          
                                                      IERC20[] memory _tokens = tokens;
                                          
                                                      (
                                                          returnAmounts[i - 1],
                                                          amount,
                                                          dist
                                                      ) = getExpectedReturnWithGas(
                                                          _tokens[i - 1],
                                                          _tokens[i],
                                                          (i == 1) ? amount : returnAmounts[i - 2],
                                                          parts[i],
                                                          flags[i],
                                                          destTokenEthPriceTimesGasPrices[i]
                                                      );
                                                      estimateGasAmount = estimateGasAmount.add(amount);
                                          
                                                      if (distribution.length == 0) {
                                                          distribution = new uint256[](dist.length);
                                                      }
                                                      for (uint j = 0; j < distribution.length; j++) {
                                                          distribution[j] = distribution[j].add(dist[j] << (8 * (i - 1)));
                                                      }
                                                  }
                                              }
                                          
                                              function swap(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) public payable returns(uint256 returnAmount) {
                                                  fromToken.universalTransferFrom(msg.sender, address(this), amount);
                                                  uint256 confirmed = fromToken.universalBalanceOf(address(this));
                                                  _swap(fromToken, destToken, confirmed, distribution, flags);
                                          
                                                  returnAmount = destToken.universalBalanceOf(address(this));
                                                  require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
                                                  destToken.universalTransfer(msg.sender, returnAmount);
                                                  fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
                                              }
                                          
                                              function swapMulti(
                                                  IERC20[] memory tokens,
                                                  uint256 amount,
                                                  uint256 minReturn,
                                                  uint256[] memory distribution,
                                                  uint256[] memory flags
                                              ) public payable returns(uint256 returnAmount) {
                                                  tokens[0].universalTransferFrom(msg.sender, address(this), amount);
                                          
                                                  returnAmount = tokens[0].universalBalanceOf(address(this));
                                                  for (uint i = 1; i < tokens.length; i++) {
                                                      if (tokens[i - 1] == tokens[i]) {
                                                          continue;
                                                      }
                                          
                                                      uint256[] memory dist = new uint256[](distribution.length);
                                                      for (uint j = 0; j < distribution.length; j++) {
                                                          dist[j] = (distribution[j] >> (8 * (i - 1))) & 0xFF;
                                                      }
                                          
                                                      _swap(
                                                          tokens[i - 1],
                                                          tokens[i],
                                                          returnAmount,
                                                          dist,
                                                          flags[i]
                                                      );
                                                      returnAmount = tokens[i].universalBalanceOf(address(this));
                                                      tokens[i - 1].universalTransfer(msg.sender, tokens[i - 1].universalBalanceOf(address(this)));
                                                  }
                                          
                                                  require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
                                                  tokens[tokens.length - 1].universalTransfer(msg.sender, returnAmount);
                                              }
                                          
                                              function _swapFloor(
                                                  IERC20 fromToken,
                                                  IERC20 destToken,
                                                  uint256 amount,
                                                  uint256[] memory distribution,
                                                  uint256 flags
                                              ) internal {
                                                  fromToken.universalApprove(address(oneSplit), amount);
                                                  oneSplit.swap.value(fromToken.isETH() ? amount : 0)(
                                                      fromToken,
                                                      destToken,
                                                      amount,
                                                      0,
                                                      distribution,
                                                      flags
                                                  );
                                              }
                                          }

                                          File 9 of 15: DmmController
                                          // File: @openzeppelin/contracts/GSN/Context.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /*
                                           * @dev Provides information about the current execution context, including the
                                           * sender of the transaction and its data. While these are generally available
                                           * via msg.sender and msg.data, they should not be accessed in such a direct
                                           * manner, since when dealing with GSN meta-transactions the account sending and
                                           * paying for execution may not be the actual sender (as far as an application
                                           * is concerned).
                                           *
                                           * This contract is only required for intermediate, library-like contracts.
                                           */
                                          contract Context {
                                              // Empty internal constructor, to prevent people from mistakenly deploying
                                              // an instance of this contract, which should be used via inheritance.
                                              constructor () internal { }
                                              // solhint-disable-previous-line no-empty-blocks
                                          
                                              function _msgSender() internal view returns (address payable) {
                                                  return msg.sender;
                                              }
                                          
                                              function _msgData() internal view returns (bytes memory) {
                                                  this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                                  return msg.data;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/access/Roles.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @title Roles
                                           * @dev Library for managing addresses assigned to a Role.
                                           */
                                          library Roles {
                                              struct Role {
                                                  mapping (address => bool) bearer;
                                              }
                                          
                                              /**
                                               * @dev Give an account access to this role.
                                               */
                                              function add(Role storage role, address account) internal {
                                                  require(!has(role, account), "Roles: account already has role");
                                                  role.bearer[account] = true;
                                              }
                                          
                                              /**
                                               * @dev Remove an account's access to this role.
                                               */
                                              function remove(Role storage role, address account) internal {
                                                  require(has(role, account), "Roles: account does not have role");
                                                  role.bearer[account] = false;
                                              }
                                          
                                              /**
                                               * @dev Check if an account has this role.
                                               * @return bool
                                               */
                                              function has(Role storage role, address account) internal view returns (bool) {
                                                  require(account != address(0), "Roles: account is the zero address");
                                                  return role.bearer[account];
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/access/roles/PauserRole.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract PauserRole is Context {
                                              using Roles for Roles.Role;
                                          
                                              event PauserAdded(address indexed account);
                                              event PauserRemoved(address indexed account);
                                          
                                              Roles.Role private _pausers;
                                          
                                              constructor () internal {
                                                  _addPauser(_msgSender());
                                              }
                                          
                                              modifier onlyPauser() {
                                                  require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
                                                  _;
                                              }
                                          
                                              function isPauser(address account) public view returns (bool) {
                                                  return _pausers.has(account);
                                              }
                                          
                                              function addPauser(address account) public onlyPauser {
                                                  _addPauser(account);
                                              }
                                          
                                              function renouncePauser() public {
                                                  _removePauser(_msgSender());
                                              }
                                          
                                              function _addPauser(address account) internal {
                                                  _pausers.add(account);
                                                  emit PauserAdded(account);
                                              }
                                          
                                              function _removePauser(address account) internal {
                                                  _pausers.remove(account);
                                                  emit PauserRemoved(account);
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/lifecycle/Pausable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          /**
                                           * @dev Contract module which allows children to implement an emergency stop
                                           * mechanism that can be triggered by an authorized account.
                                           *
                                           * This module is used through inheritance. It will make available the
                                           * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
                                           * the functions of your contract. Note that they will not be pausable by
                                           * simply including this module, only once the modifiers are put in place.
                                           */
                                          contract Pausable is Context, PauserRole {
                                              /**
                                               * @dev Emitted when the pause is triggered by a pauser (`account`).
                                               */
                                              event Paused(address account);
                                          
                                              /**
                                               * @dev Emitted when the pause is lifted by a pauser (`account`).
                                               */
                                              event Unpaused(address account);
                                          
                                              bool private _paused;
                                          
                                              /**
                                               * @dev Initializes the contract in unpaused state. Assigns the Pauser role
                                               * to the deployer.
                                               */
                                              constructor () internal {
                                                  _paused = false;
                                              }
                                          
                                              /**
                                               * @dev Returns true if the contract is paused, and false otherwise.
                                               */
                                              function paused() public view returns (bool) {
                                                  return _paused;
                                              }
                                          
                                              /**
                                               * @dev Modifier to make a function callable only when the contract is not paused.
                                               */
                                              modifier whenNotPaused() {
                                                  require(!_paused, "Pausable: paused");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Modifier to make a function callable only when the contract is paused.
                                               */
                                              modifier whenPaused() {
                                                  require(_paused, "Pausable: not paused");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Called by a pauser to pause, triggers stopped state.
                                               */
                                              function pause() public onlyPauser whenNotPaused {
                                                  _paused = true;
                                                  emit Paused(_msgSender());
                                              }
                                          
                                              /**
                                               * @dev Called by a pauser to unpause, returns to normal state.
                                               */
                                              function unpause() public onlyPauser whenPaused {
                                                  _paused = false;
                                                  emit Unpaused(_msgSender());
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.5.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, 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) {
                                                  return sub(a, b, "SafeMath: subtraction overflow");
                                              }
                                          
                                              /**
                                               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                               * overflow (when the result is negative).
                                               *
                                               * Counterpart to Solidity's `-` operator.
                                               *
                                               * Requirements:
                                               * - Subtraction cannot overflow.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b <= a, errorMessage);
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  return div(a, b, "SafeMath: division by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, errorMessage);
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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) {
                                                  return mod(a, b, "SafeMath: modulo by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b != 0, errorMessage);
                                                  return a % b;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/ownership/Ownable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Contract module which provides a basic access control mechanism, where
                                           * there is an account (an owner) that can be granted exclusive access to
                                           * specific functions.
                                           *
                                           * This module is used through inheritance. It will make available the modifier
                                           * `onlyOwner`, which can be applied to your functions to restrict their use to
                                           * the owner.
                                           */
                                          contract Ownable is Context {
                                              address private _owner;
                                          
                                              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                          
                                              /**
                                               * @dev Initializes the contract setting the deployer as the initial owner.
                                               */
                                              constructor () internal {
                                                  _owner = _msgSender();
                                                  emit OwnershipTransferred(address(0), _owner);
                                              }
                                          
                                              /**
                                               * @dev Returns the address of the current owner.
                                               */
                                              function owner() public view returns (address) {
                                                  return _owner;
                                              }
                                          
                                              /**
                                               * @dev Throws if called by any account other than the owner.
                                               */
                                              modifier onlyOwner() {
                                                  require(isOwner(), "Ownable: caller is not the owner");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Returns true if the caller is the current owner.
                                               */
                                              function isOwner() public view returns (bool) {
                                                  return _msgSender() == _owner;
                                              }
                                          
                                              /**
                                               * @dev Leaves the contract without owner. It will not be possible to call
                                               * `onlyOwner` functions anymore. Can only be called by the current owner.
                                               *
                                               * NOTE: Renouncing ownership will leave the contract without an owner,
                                               * thereby removing any functionality that is only available to the owner.
                                               */
                                              function renounceOwnership() public onlyOwner {
                                                  emit OwnershipTransferred(_owner, address(0));
                                                  _owner = address(0);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               * Can only be called by the current owner.
                                               */
                                              function transferOwnership(address newOwner) public onlyOwner {
                                                  _transferOwnership(newOwner);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               */
                                              function _transferOwnership(address newOwner) internal {
                                                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                                                  emit OwnershipTransferred(_owner, newOwner);
                                                  _owner = newOwner;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see {ERC20Detailed}.
                                           */
                                          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.5.5;
                                          
                                          /**
                                           * @dev Collection of functions related to the address type
                                           */
                                          library Address {
                                              /**
                                               * @dev Returns true if `account` is a contract.
                                               *
                                               * This test is non-exhaustive, and there may be false-negatives: during the
                                               * execution of a contract's constructor, its address will be reported as
                                               * not containing 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.
                                               */
                                              function isContract(address account) internal view returns (bool) {
                                                  // This method relies in extcodesize, which returns 0 for contracts in
                                                  // construction, since the code is only stored at the end of the
                                                  // constructor execution.
                                          
                                                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                                  // for accounts without code, i.e. `keccak256('')`
                                                  bytes32 codehash;
                                                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                                  // solhint-disable-next-line no-inline-assembly
                                                  assembly { codehash := extcodehash(account) }
                                                  return (codehash != 0x0 && codehash != accountHash);
                                              }
                                          
                                              /**
                                               * @dev Converts an `address` into `address payable`. Note that this is
                                               * simply a type cast: the actual underlying value is not changed.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function toPayable(address account) internal pure returns (address payable) {
                                                  return address(uint160(account));
                                              }
                                          
                                              /**
                                               * @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].
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sendValue(address payable recipient, uint256 amount) internal {
                                                  require(address(this).balance >= amount, "Address: insufficient balance");
                                          
                                                  // solhint-disable-next-line avoid-call-value
                                                  (bool success, ) = recipient.call.value(amount)("");
                                                  require(success, "Address: unable to send value, recipient may have reverted");
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                                          
                                          pragma solidity ^0.5.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 ERC20;` 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));
                                              }
                                          
                                              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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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: contracts/constants/CommonConstants.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          contract CommonConstants {
                                          
                                              uint public constant EXCHANGE_RATE_BASE_RATE = 1e18;
                                          
                                          }
                                          
                                          // File: contracts/utils/Blacklistable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          /**
                                           * @dev Allows accounts to be blacklisted by the owner of the contract.
                                           *
                                           *  Taken from USDC's contract for blacklisting certain addresses from owning and interacting with the token.
                                           */
                                          contract Blacklistable is Ownable {
                                          
                                              string public constant BLACKLISTED = "BLACKLISTED";
                                          
                                              mapping(address => bool) internal blacklisted;
                                          
                                              event Blacklisted(address indexed account);
                                              event UnBlacklisted(address indexed account);
                                              event BlacklisterChanged(address indexed newBlacklister);
                                          
                                              /**
                                               * @dev Throws if called by any account other than the creator of this contract
                                              */
                                              modifier onlyBlacklister() {
                                                  require(msg.sender == owner(), "MUST_BE_BLACKLISTER");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Throws if `account` is blacklisted
                                               *
                                               * @param account The address to check
                                              */
                                              modifier notBlacklisted(address account) {
                                                  require(blacklisted[account] == false, BLACKLISTED);
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Checks if `account` is blacklisted. Reverts with `BLACKLISTED` if blacklisted.
                                              */
                                              function checkNotBlacklisted(address account) public view {
                                                  require(!blacklisted[account], BLACKLISTED);
                                              }
                                          
                                              /**
                                               * @dev Checks if `account` is blacklisted
                                               *
                                               * @param account The address to check
                                              */
                                              function isBlacklisted(address account) public view returns (bool) {
                                                  return blacklisted[account];
                                              }
                                          
                                              /**
                                               * @dev Adds `account` to blacklist
                                               *
                                               * @param account The address to blacklist
                                              */
                                              function blacklist(address account) public onlyBlacklister {
                                                  blacklisted[account] = true;
                                                  emit Blacklisted(account);
                                              }
                                          
                                              /**
                                               * @dev Removes account from blacklist
                                               *
                                               * @param account The address to remove from the blacklist
                                              */
                                              function unBlacklist(address account) public onlyBlacklister {
                                                  blacklisted[account] = false;
                                                  emit UnBlacklisted(account);
                                              }
                                          
                                          }
                                          
                                          // File: contracts/impl/DmmBlacklistable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          contract DmmBlacklistable is Blacklistable {
                                          
                                              constructor() public {
                                              }
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IOffChainAssetValuator.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          interface IOffChainAssetValuator {
                                          
                                              event AssetsValueUpdated(uint newAssetsValue);
                                          
                                              /**
                                               * @dev Gets the DMM ecosystem's collateral's value from Chainlink's on-chain data feed.
                                               *
                                               * @return The value of the ecosystem's collateral, as a number with 18 decimals
                                               */
                                              function getOffChainAssetsValue() external view returns (uint);
                                          
                                          }
                                          
                                          // File: contracts/interfaces/InterestRateInterface.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          interface InterestRateInterface {
                                          
                                              /**
                                                * @dev Returns the current interest rate for the given DMMA and corresponding total supply & active supply
                                                *
                                                * @param dmmTokenId The DMMA whose interest should be retrieved
                                                * @param totalSupply The total supply fot he DMM token
                                                * @param activeSupply The supply that's currently being lent by users
                                                * @return The interest rate in APY, which is a number with 18 decimals
                                                */
                                              function getInterestRate(uint dmmTokenId, uint totalSupply, uint activeSupply) external view returns (uint);
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IDmmController.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          interface IDmmController {
                                          
                                              event TotalSupplyIncreased(uint oldTotalSupply, uint newTotalSupply);
                                              event TotalSupplyDecreased(uint oldTotalSupply, uint newTotalSupply);
                                          
                                              event AdminDeposit(address indexed sender, uint amount);
                                              event AdminWithdraw(address indexed receiver, uint amount);
                                          
                                              function blacklistable() external view returns (Blacklistable);
                                          
                                              /**
                                               * @dev Creates a new mToken using the provided data.
                                               *
                                               * @param underlyingToken   The token that should be wrapped to create a new DMMA
                                               * @param symbol            The symbol of the new DMMA, IE mDAI or mUSDC
                                               * @param name              The name of this token, IE `DMM: DAI`
                                               * @param decimals          The number of decimals of the underlying token, and therefore the number for this DMMA
                                               * @param minMintAmount     The minimum amount that can be minted for any given transaction.
                                               * @param minRedeemAmount   The minimum amount that can be redeemed any given transaction.
                                               * @param totalSupply       The initial total supply for this market.
                                               */
                                              function addMarket(
                                                  address underlyingToken,
                                                  string calldata symbol,
                                                  string calldata name,
                                                  uint8 decimals,
                                                  uint minMintAmount,
                                                  uint minRedeemAmount,
                                                  uint totalSupply
                                              ) external;
                                          
                                              /**
                                               * @dev Creates a new mToken using the already-existing token.
                                               *
                                               * @param dmmToken          The token that should be added to this controller.
                                               * @param underlyingToken   The token that should be wrapped to create a new DMMA.
                                               */
                                              function addMarketFromExistingDmmToken(
                                                  address dmmToken,
                                                  address underlyingToken
                                              ) external;
                                          
                                              /**
                                               * @param newController The new controller who should receive ownership of the provided DMM token IDs.
                                               */
                                              function transferOwnershipToNewController(
                                                  address newController
                                              ) external;
                                          
                                              /**
                                               * @dev Enables the corresponding DMMA to allow minting new tokens.
                                               *
                                               * @param dmmTokenId  The DMMA that should be enabled.
                                               */
                                              function enableMarket(uint dmmTokenId) external;
                                          
                                              /**
                                               * @dev Disables the corresponding DMMA from minting new tokens. This allows the market to close over time, since
                                               *      users are only able to redeem tokens.
                                               *
                                               * @param dmmTokenId  The DMMA that should be disabled.
                                               */
                                              function disableMarket(uint dmmTokenId) external;
                                          
                                              /**
                                               * @dev Sets a new contract that implements the `InterestRateInterface` interface.
                                               *
                                               * @param newInterestRateInterface  The new contract that implements the `InterestRateInterface` interface.
                                               */
                                              function setInterestRateInterface(address newInterestRateInterface) external;
                                          
                                              /**
                                               * @dev Sets a new contract that implements the `IOffChainAssetValuator` interface.
                                               *
                                               * @param newOffChainAssetValuator The new contract that implements the `IOffChainAssetValuator` interface.
                                               */
                                              function setOffChainAssetValuator(address newOffChainAssetValuator) external;
                                          
                                              /**
                                               * @dev Sets a new contract that implements the `IOffChainAssetValuator` interface.
                                               *
                                               * @param newOffChainCurrencyValuator The new contract that implements the `IOffChainAssetValuator` interface.
                                               */
                                              function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) external;
                                          
                                              /**
                                               * @dev Sets a new contract that implements the `UnderlyingTokenValuator` interface
                                               *
                                               * @param newUnderlyingTokenValuator The new contract that implements the `UnderlyingTokenValuator` interface
                                               */
                                              function setUnderlyingTokenValuator(address newUnderlyingTokenValuator) external;
                                          
                                              /**
                                               * @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
                                               *      allocated to real-world assets that will be used to pay interest into the DMMA.
                                               *
                                               * @param newMinCollateralization   The new min collateralization (with 18 decimals) at which the DMME must be in
                                               *                                  order to add to the total supply of DMM.
                                               */
                                              function setMinCollateralization(uint newMinCollateralization) external;
                                          
                                              /**
                                               * @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
                                               *      allocated to real-world assets that will be used to pay interest into the DMMA.
                                               *
                                               * @param newMinReserveRatio   The new ratio (with 18 decimals) that is used to enforce a certain percentage of assets
                                               *                          are kept in each DMMA.
                                               */
                                              function setMinReserveRatio(uint newMinReserveRatio) external;
                                          
                                              /**
                                               * @dev Increases the max supply for the provided `dmmTokenId` by `amount`. This call reverts with
                                               *      INSUFFICIENT_COLLATERAL if there isn't enough collateral in the Chainlink contract to cover the controller's
                                               *      requirements for minimum collateral.
                                               */
                                              function increaseTotalSupply(uint dmmTokenId, uint amount) external;
                                          
                                              /**
                                               * @dev Increases the max supply for the provided `dmmTokenId` by `amount`.
                                               */
                                              function decreaseTotalSupply(uint dmmTokenId, uint amount) external;
                                          
                                              /**
                                               * @dev Allows the owners of the DMM Ecosystem to withdraw funds from a DMMA. These withdrawn funds are then
                                               *      allocated to real-world assets that will be used to pay interest into the DMMA.
                                               *
                                               * @param dmmTokenId        The ID of the DMM token whose underlying will be funded.
                                               * @param underlyingAmount  The amount underlying the DMM token that will be deposited into the DMMA.
                                               */
                                              function adminWithdrawFunds(uint dmmTokenId, uint underlyingAmount) external;
                                          
                                              /**
                                               * @dev Allows the owners of the DMM Ecosystem to deposit funds into a DMMA. These funds are used to disburse
                                               *      interest payments and add more liquidity to the specific market.
                                               *
                                               * @param dmmTokenId        The ID of the DMM token whose underlying will be funded.
                                               * @param underlyingAmount  The amount underlying the DMM token that will be deposited into the DMMA.
                                               */
                                              function adminDepositFunds(uint dmmTokenId, uint underlyingAmount) external;
                                          
                                              /**
                                               * @dev Gets the collateralization of the system assuming 1-year's worth of interest payments are due by dividing
                                               *      the total value of all the collateralized assets plus the value of the underlying tokens in each DMMA by the
                                               *      aggregate interest owed (plus the principal), assuming each DMMA was at maximum usage.
                                               *
                                               * @return  The 1-year collateralization of the system, as a number with 18 decimals. For example
                                               *          `1010000000000000000` is 101% or 1.01.
                                               */
                                              function getTotalCollateralization() external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the current collateralization of the system assuming by dividing the total value of all the
                                               *      collateralized assets plus the value of the underlying tokens in each DMMA by the aggregate interest owed
                                               *      (plus the principal), using the current usage of each DMMA.
                                               *
                                               * @return  The active collateralization of the system, as a number with 18 decimals. For example
                                               *          `1010000000000000000` is 101% or 1.01.
                                               */
                                              function getActiveCollateralization() external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the interest rate from the underlying token, IE DAI or USDC.
                                               *
                                               * @return  The current interest rate, represented using 18 decimals. Meaning `65000000000000000` is 6.5% APY or
                                               *          0.065.
                                               */
                                              function getInterestRateByUnderlyingTokenAddress(address underlyingToken) external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the interest rate from the DMM token, IE DMM: DAI or DMM: USDC.
                                               *
                                               * @return  The current interest rate, represented using 18 decimals. Meaning, `65000000000000000` is 6.5% APY or
                                               *          0.065.
                                               */
                                              function getInterestRateByDmmTokenId(uint dmmTokenId) external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the interest rate from the DMM token, IE DMM: DAI or DMM: USDC.
                                               *
                                               * @return  The current interest rate, represented using 18 decimals. Meaning, `65000000000000000` is 6.5% APY or
                                               *          0.065.
                                               */
                                              function getInterestRateByDmmTokenAddress(address dmmToken) external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the exchange rate from the underlying to the DMM token, such that
                                               *      `DMM: Token = underlying / exchangeRate`
                                               *
                                               * @return  The current exchange rate, represented using 18 decimals. Meaning, `200000000000000000` is 0.2.
                                               */
                                              function getExchangeRateByUnderlying(address underlyingToken) external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the exchange rate from the underlying to the DMM token, such that
                                               *      `DMM: Token = underlying / exchangeRate`
                                               *
                                               * @return  The current exchange rate, represented using 18 decimals. Meaning, `200000000000000000` is 0.2.
                                               */
                                              function getExchangeRate(address dmmToken) external view returns (uint);
                                          
                                              /**
                                               * @dev Gets the DMM token for the provided underlying token. For example, sending DAI returns DMM: DAI.
                                               */
                                              function getDmmTokenForUnderlying(address underlyingToken) external view returns (address);
                                          
                                              /**
                                               * @dev Gets the underlying token for the provided DMM token. For example, sending DMM: DAI returns DAI.
                                               */
                                              function getUnderlyingTokenForDmm(address dmmToken) external view returns (address);
                                          
                                              /**
                                               * @return True if the market is enabled for this DMMA or false if it is not enabled.
                                               */
                                              function isMarketEnabledByDmmTokenId(uint dmmTokenId) external view returns (bool);
                                          
                                              /**
                                               * @return True if the market is enabled for this DMM token (IE DMM: DAI) or false if it is not enabled.
                                               */
                                              function isMarketEnabledByDmmTokenAddress(address dmmToken) external view returns (bool);
                                          
                                              /**
                                               * @return True if the market is enabled for this underlying token (IE DAI) or false if it is not enabled.
                                               */
                                              function getTokenIdFromDmmTokenAddress(address dmmTokenAddress) external view returns (uint);
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IDmmToken.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          /**
                                           * Basically an interface except, contains the implementation of the type-hashes for offline signature generation.
                                           *
                                           * This contract contains the signatures and documentation for all publicly-implemented functions in the DMM token.
                                           */
                                          interface IDmmToken {
                                          
                                              /*****************
                                               * Events
                                               */
                                          
                                              event Mint(address indexed minter, address indexed recipient, uint amount);
                                              event Redeem(address indexed redeemer, address indexed recipient, uint amount);
                                              event FeeTransfer(address indexed owner, address indexed recipient, uint amount);
                                          
                                              event TotalSupplyIncreased(uint oldTotalSupply, uint newTotalSupply);
                                              event TotalSupplyDecreased(uint oldTotalSupply, uint newTotalSupply);
                                          
                                              event OffChainRequestValidated(address indexed owner, address indexed feeRecipient, uint nonce, uint expiry, uint feeAmount);
                                          
                                              /*****************
                                               * Functions
                                               */
                                          
                                              /**
                                               * @dev The controller that deployed this parent
                                               */
                                              function controller() external view returns (IDmmController);
                                          
                                              /**
                                               * @dev Returns the name of the token.
                                               */
                                              function name() external view returns (string memory);
                                          
                                              /**
                                               * @dev Returns the symbol of the token, usually a shorter version of the
                                               * name.
                                               */
                                              function symbol() external view returns (string memory);
                                          
                                              /**
                                               * @dev Returns the number of decimals used to get its user representation.
                                               * For example, if `decimals` equals `2`, a balance of `505` tokens should
                                               * be displayed to a user as `5,05` (`505 / 10 ** 2`).
                                               *
                                               * Tokens usually opt for a value of 18, imitating the relationship between
                                               * Ether and Wei.
                                               *
                                               * NOTE: This information is only used for _display_ purposes: it in
                                               * no way affects any of the arithmetic of the contract, including
                                               * {IERC20-balanceOf} and {IERC20-transfer}.
                                               */
                                              function decimals() external view returns (uint8);
                                          
                                              /**
                                               * @return  The min amount that can be minted in a single transaction. This amount corresponds with the number of
                                               *          decimals that this token has.
                                               */
                                              function minMintAmount() external view returns (uint);
                                          
                                              /**
                                               * @return  The min amount that can be redeemed from DMM to underlying in a single transaction. This amount
                                               *          corresponds with the number of decimals that this token has.
                                               */
                                              function minRedeemAmount() external view returns (uint);
                                          
                                              /**
                                                * @dev The amount of DMM that is in circulation (outside of this contract)
                                                */
                                              function activeSupply() external view returns (uint);
                                          
                                              /**
                                               * @dev Attempts to add `amount` to the total supply by issuing the tokens to this contract. This call fires a
                                               *      Transfer event from the 0x0 address to this contract.
                                               */
                                              function increaseTotalSupply(uint amount) external;
                                          
                                              /**
                                               * @dev Attempts to remove `amount` from the total supply by destroying those tokens that are held in this
                                               *      contract. This call reverts with TOO_MUCH_ACTIVE_SUPPLY if `amount` is not held in this contract.
                                               */
                                              function decreaseTotalSupply(uint amount) external;
                                          
                                              /**
                                               * @dev An admin function that lets the ecosystem's organizers deposit the underlying token around which this DMMA
                                               *      wraps to this contract. This is used to replenish liquidity and after interest payouts are made from the
                                               *      real-world assets.
                                               */
                                              function depositUnderlying(uint underlyingAmount) external returns (bool);
                                          
                                              /**
                                               * @dev An admin function that lets the ecosystem's organizers withdraw the underlying token around which this DMMA
                                               *      wraps from this contract. This is used to withdraw deposited tokens, to be allocated to real-world assets
                                               *      that produce income streams and can cover interest payments.
                                               */
                                              function withdrawUnderlying(uint underlyingAmount) external returns (bool);
                                          
                                              /**
                                                * @dev The timestamp at which the exchange rate was last updated.
                                                */
                                              function exchangeRateLastUpdatedTimestamp() external view returns (uint);
                                          
                                              /**
                                                * @dev The timestamp at which the exchange rate was last updated.
                                                */
                                              function exchangeRateLastUpdatedBlockNumber() external view returns (uint);
                                          
                                              /**
                                               * @dev The exchange rate from underlying to DMM. Invert this number to go from DMM to underlying. This number
                                               *      has 18 decimals.
                                               */
                                              function getCurrentExchangeRate() external view returns (uint);
                                          
                                              /**
                                               * @dev The current nonce of the provided `owner`. This `owner` should be the signer for any gasless transactions.
                                               */
                                              function nonceOf(address owner) external view returns (uint);
                                          
                                              /**
                                               * @dev Transfers the token around which this DMMA wraps from msg.sender to the DMMA contract. Then, sends the
                                               *      corresponding amount of DMM to the msg.sender. Note, this call reverts with INSUFFICIENT_DMM_LIQUIDITY if
                                               *      there is not enough DMM available to be minted.
                                               *
                                               * @param amount The amount of underlying to send to this DMMA for conversion to DMM.
                                               * @return The amount of DMM minted.
                                               */
                                              function mint(uint amount) external returns (uint);
                                          
                                              /**
                                               * @dev Transfers the token around which this DMMA wraps from sender to the DMMA contract. Then, sends the
                                               *      corresponding amount of DMM to recipient. Note, an allowance must be set for sender for the underlying
                                               *      token that is at least of size `amount` / `exchangeRate`. This call reverts with INSUFFICIENT_DMM_LIQUIDITY
                                               *      if there is not enough DMM available to be minted. See #MINT_TYPE_HASH. This function gives the `owner` the
                                               *      illusion of committing a gasless transaction, allowing a relayer to broadcast the transaction and
                                               *      potentially collect a fee for doing so.
                                               *
                                               * @param owner         The user that signed the off-chain message.
                                               * @param recipient     The address that will receive the newly-minted DMM tokens.
                                               * @param nonce         An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
                                               *                      owner's current nonce.
                                               * @param expiry        The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
                                               *                      means there is no expiration.
                                               * @param amount        The amount of underlying that should be minted by `owner` and sent to `recipient`.
                                               * @param feeAmount     The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
                                               *                      owner. Can be 0, which means the user won't be charged a fee. Must be <= `amount`.
                                               * @param feeRecipient  The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
                                               *                      Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
                                               * @param v             The ECDSA V parameter.
                                               * @param r             The ECDSA R parameter.
                                               * @param s             The ECDSA S parameter.
                                               * @return  The amount of DMM minted, minus the fees paid. To get the total amount minted, add the `feeAmount` to
                                               *          the returned amount from this function call.
                                               */
                                              function mintFromGaslessRequest(
                                                  address owner,
                                                  address recipient,
                                                  uint nonce,
                                                  uint expiry,
                                                  uint amount,
                                                  uint feeAmount,
                                                  address feeRecipient,
                                                  uint8 v,
                                                  bytes32 r,
                                                  bytes32 s
                                              ) external returns (uint);
                                          
                                              /**
                                               * @dev Transfers DMM from msg.sender to this DMMA contract. Then, sends the corresponding amount of token around
                                               *      which this DMMA wraps to the msg.sender. Note, this call reverts with INSUFFICIENT_UNDERLYING_LIQUIDITY if
                                               *      there is not enough DMM available to be redeemed.
                                               *
                                               * @param amount    The amount of DMM to be transferred from msg.sender to this DMMA.
                                               * @return          The amount of underlying redeemed.
                                               */
                                              function redeem(uint amount) external returns (uint);
                                          
                                              /**
                                               * @dev Transfers DMM from `owner` to the DMMA contract. Then, sends the corresponding amount of token around which
                                               *      this DMMA wraps to `recipient`. Note, an allowance must be set for sender for the underlying
                                               *      token that is at least of size `amount`. This call reverts with INSUFFICIENT_UNDERLYING_LIQUIDITY
                                               *      if there is not enough underlying available to be redeemed. See #REDEEM_TYPE_HASH. This function gives the
                                               *      `owner` the illusion of committing a gasless transaction, allowing a relayer to broadcast the transaction
                                               *      and potentially collect a fee for doing so.
                                               *
                                               * @param owner         The user that signed the off-chain message.
                                               * @param recipient     The address that will receive the newly-redeemed DMM tokens.
                                               * @param nonce         An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
                                               *                      owner's current nonce.
                                               * @param expiry        The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
                                               *                      means there is no expiration.
                                               * @param amount        The amount of DMM that should be redeemed for `owner` and sent to `recipient`.
                                               * @param feeAmount     The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
                                               *                      owner. Can be 0, which means the user won't be charged a fee. Must be <= `amount`
                                               * @param feeRecipient  The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
                                               *                      Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
                                               * @param v             The ECDSA V parameter.
                                               * @param r             The ECDSA R parameter.
                                               * @param s             The ECDSA S parameter.
                                               * @return  The amount of underlying redeemed.
                                               */
                                              function redeemFromGaslessRequest(
                                                  address owner,
                                                  address recipient,
                                                  uint nonce,
                                                  uint expiry,
                                                  uint amount,
                                                  uint feeAmount,
                                                  address feeRecipient,
                                                  uint8 v,
                                                  bytes32 r,
                                                  bytes32 s
                                              ) external returns (uint);
                                          
                                              /**
                                               * @dev Sets an allowance for owner with spender using an offline-generated signature. This function allows a
                                               *      relayer to send the transaction, giving the owner the illusion of committing a gasless transaction. See
                                               *      #PERMIT_TYPEHASH.
                                               *
                                               * @param owner         The user that signed the off-chain message.
                                               * @param spender       The contract/wallet that can spend DMM tokens on behalf of owner.
                                               * @param nonce         An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
                                               *                      owner's current nonce.
                                               * @param expiry        The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
                                               *                      means there is no expiration.
                                               * @param allowed       True if the spender can spend funds on behalf of owner or false to revoke this privilege.
                                               * @param feeAmount     The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
                                               *                      owner. Can be 0, which means the user won't be charged a fee.
                                               * @param feeRecipient  The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
                                               *                      Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
                                               * @param v             The ECDSA V parameter.
                                               * @param r             The ECDSA R parameter.
                                               * @param s             The ECDSA S parameter.
                                               */
                                              function permit(
                                                  address owner,
                                                  address spender,
                                                  uint nonce,
                                                  uint expiry,
                                                  bool allowed,
                                                  uint feeAmount,
                                                  address feeRecipient,
                                                  uint8 v,
                                                  bytes32 r,
                                                  bytes32 s
                                              ) external;
                                          
                                              /**
                                               * @dev Transfers DMM from the `owner` to `recipient` using an offline-generated signature. This function allows a
                                               *      relayer to send the transaction, giving the owner the illusion of committing a gasless transaction. See
                                               *      #TRANSFER_TYPEHASH. This function gives the `owner` the illusion of committing a gasless transaction,
                                               *      allowing a relayer to broadcast the transaction and potentially collect a fee for doing so.
                                               *
                                               * @param owner         The user that signed the off-chain message and originator of the transfer.
                                               * @param recipient     The address that will receive the transferred DMM tokens.
                                               * @param nonce         An auto-incrementing integer that prevents replay attacks. See #nonceOf(address) to get the
                                               *                      owner's current nonce.
                                               * @param expiry        The timestamp, in unix seconds, at which the signed off-chain message expires. A value of 0
                                               *                      means there is no expiration.
                                               * @param amount        The amount of DMM that should be transferred from `owner` and sent to `recipient`.
                                               * @param feeAmount     The amount of DMM to be sent to feeRecipient for sending this transaction on behalf of
                                               *                      owner. Can be 0, which means the user won't be charged a fee.
                                               * @param feeRecipient  The address that should receive the fee. A value of 0x0 will send the fees to `msg.sender`.
                                               *                      Note, no fees are sent if the feeAmount is 0, regardless of what feeRecipient is.
                                               * @param v             The ECDSA V parameter.
                                               * @param r             The ECDSA R parameter.
                                               * @param s             The ECDSA S parameter.
                                               * @return              True if the transfer was successful or false if it failed.
                                               */
                                              function transferFromGaslessRequest(
                                                  address owner,
                                                  address recipient,
                                                  uint nonce,
                                                  uint expiry,
                                                  uint amount,
                                                  uint feeAmount,
                                                  address feeRecipient,
                                                  uint8 v,
                                                  bytes32 r,
                                                  bytes32 s
                                              ) external;
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IUnderlyingTokenValuator.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          interface IUnderlyingTokenValuator {
                                          
                                              /**
                                                * @dev Gets the tokens value in terms of USD.
                                                *
                                                * @return The value of the `amount` of `token`, as a number with 18 decimals
                                                */
                                              function getTokenValue(address token, uint amount) external view returns (uint);
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IDmmTokenFactory.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          interface IDmmTokenFactory {
                                          
                                              function deployToken(
                                                  string calldata symbol,
                                                  string calldata name,
                                                  uint8 decimals,
                                                  uint minMintAmount,
                                                  uint minRedeemAmount,
                                                  uint totalSupply,
                                                  address controller
                                              ) external returns (IDmmToken);
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IPausable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          interface IPausable {
                                          
                                              function paused() external view returns (bool);
                                          
                                          }
                                          
                                          // File: contracts/interfaces/IOffChainCurrencyValuator.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * Gets the value of any currencies that are residing off-chain, but are NOT yet allocated to a revenue-producing asset.
                                           */
                                          interface IOffChainCurrencyValuator {
                                          
                                              /**
                                               * @return The value of the off-chain assets. The number returned uses 18 decimal places.
                                               */
                                              function getOffChainCurrenciesValue() external view returns (uint);
                                          
                                          }
                                          
                                          // File: contracts/impl/DmmController.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract DmmController is IPausable, Pausable, CommonConstants, IDmmController, Ownable {
                                          
                                              using SafeMath for uint;
                                              using SafeERC20 for IERC20;
                                              using Address for address;
                                          
                                              /********************************
                                               * Events
                                               */
                                          
                                              event InterestRateInterfaceChanged(address previousInterestRateInterface, address newInterestRateInterface);
                                              event OffChainAssetValuatorChanged(address previousOffChainAssetValuator, address newOffChainAssetValuator);
                                              event OffChainCurrencyValuatorChanged(address previousOffChainCurrencyValuator, address newOffChainCurrencyValuator);
                                              event UnderlyingTokenValuatorChanged(address previousUnderlyingTokenValuator, address newUnderlyingTokenValuator);
                                          
                                              event MarketAdded(uint indexed dmmTokenId, address indexed dmmToken, address indexed underlyingToken);
                                          
                                              event DisableMarket(uint indexed dmmTokenId);
                                              event EnableMarket(uint indexed dmmTokenId);
                                          
                                              event MinCollateralizationChanged(uint previousMinCollateralization, uint newMinCollateralization);
                                              event MinReserveRatioChanged(uint previousMinReserveRatio, uint newMinReserveRatio);
                                          
                                              /********************************
                                               * Controller Fields
                                               */
                                          
                                              DmmBlacklistable public dmmBlacklistable;
                                              InterestRateInterface public interestRateInterface;
                                              IOffChainCurrencyValuator public offChainCurrencyValuator;
                                              IOffChainAssetValuator public offChainAssetsValuator;
                                              IUnderlyingTokenValuator public underlyingTokenValuator;
                                              IDmmTokenFactory public dmmTokenFactory;
                                              IDmmTokenFactory public dmmEtherFactory;
                                              uint public minCollateralization;
                                              uint public minReserveRatio;
                                              address public wethToken;
                                          
                                              /********************************
                                               * DMM Account Management
                                               */
                                          
                                              mapping(uint => address) public dmmTokenIdToDmmTokenAddressMap;
                                              mapping(address => uint) public dmmTokenAddressToDmmTokenIdMap;
                                          
                                              mapping(address => uint) public underlyingTokenAddressToDmmTokenIdMap;
                                              mapping(uint => address) public dmmTokenIdToUnderlyingTokenAddressMap;
                                          
                                              mapping(uint => bool) public dmmTokenIdToIsDisabledMap;
                                              uint[] public dmmTokenIds;
                                          
                                              /********************************
                                               * Constants
                                               */
                                          
                                              uint public constant COLLATERALIZATION_BASE_RATE = 1e18;
                                              uint public constant INTEREST_RATE_BASE_RATE = 1e18;
                                              uint public constant MIN_RESERVE_RATIO_BASE_RATE = 1e18;
                                          
                                              constructor(
                                                  address _interestRateInterface,
                                                  address _offChainAssetsValuator,
                                                  address _offChainCurrencyValuator,
                                                  address _underlyingTokenValuator,
                                                  address _dmmEtherFactory,
                                                  address _dmmTokenFactory,
                                                  address _dmmBlacklistable,
                                                  uint _minCollateralization,
                                                  uint _minReserveRatio,
                                                  address _wethToken
                                              ) public {
                                                  interestRateInterface = InterestRateInterface(_interestRateInterface);
                                                  offChainAssetsValuator = IOffChainAssetValuator(_offChainAssetsValuator);
                                                  offChainCurrencyValuator = IOffChainCurrencyValuator(_offChainCurrencyValuator);
                                                  underlyingTokenValuator = IUnderlyingTokenValuator(_underlyingTokenValuator);
                                                  dmmTokenFactory = IDmmTokenFactory(_dmmTokenFactory);
                                                  dmmEtherFactory = IDmmTokenFactory(_dmmEtherFactory);
                                                  dmmBlacklistable = DmmBlacklistable(_dmmBlacklistable);
                                                  minCollateralization = _minCollateralization;
                                                  minReserveRatio = _minReserveRatio;
                                                  wethToken = _wethToken;
                                              }
                                          
                                              /*****************
                                               * Modifiers
                                               */
                                          
                                              modifier whenNotPaused() {
                                                  require(!paused(), "ECOSYSTEM_PAUSED");
                                                  _;
                                              }
                                          
                                              modifier whenPaused() {
                                                  require(paused(), "ECOSYSTEM_NOT_PAUSED");
                                                  _;
                                              }
                                          
                                              modifier checkTokenExists(uint dmmTokenId) {
                                                  require(dmmTokenIdToDmmTokenAddressMap[dmmTokenId] != address(0x0), "TOKEN_DOES_NOT_EXIST");
                                                  _;
                                              }
                                          
                                              /**********************
                                               * Public Functions
                                               */
                                          
                                              function transferOwnership(address newOwner) public onlyOwner {
                                                  address oldOwner = owner();
                                                  super.transferOwnership(newOwner);
                                                  _removePauser(oldOwner);
                                                  _addPauser(newOwner);
                                              }
                                          
                                              function blacklistable() public view returns (Blacklistable) {
                                                  return dmmBlacklistable;
                                              }
                                          
                                              function addMarket(
                                                  address underlyingToken,
                                                  string memory symbol,
                                                  string memory name,
                                                  uint8 decimals,
                                                  uint minMintAmount,
                                                  uint minRedeemAmount,
                                                  uint totalSupply
                                              ) public onlyOwner {
                                                  require(underlyingTokenAddressToDmmTokenIdMap[underlyingToken] == 0, "TOKEN_ALREADY_EXISTS");
                                          
                                                  IDmmToken dmmToken;
                                                  address controller = address(this);
                                                  if (underlyingToken == wethToken) {
                                                      dmmToken = dmmEtherFactory.deployToken(
                                                          symbol,
                                                          name,
                                                          decimals,
                                                          minMintAmount,
                                                          minRedeemAmount,
                                                          totalSupply,
                                                          controller
                                                      );
                                                  } else {
                                                      dmmToken = dmmTokenFactory.deployToken(
                                                          symbol,
                                                          name,
                                                          decimals,
                                                          minMintAmount,
                                                          minRedeemAmount,
                                                          totalSupply,
                                                          controller
                                                      );
                                                  }
                                          
                                                  _addMarket(address(dmmToken), underlyingToken);
                                              }
                                          
                                              function addMarketFromExistingDmmToken(
                                                  address dmmToken,
                                                  address underlyingToken
                                              )
                                              onlyOwner
                                              public {
                                                  require(underlyingTokenAddressToDmmTokenIdMap[underlyingToken] == 0, "TOKEN_ALREADY_EXISTS");
                                                  require(dmmToken.isContract(), "DMM_TOKEN_IS_NOT_CONTRACT");
                                                  require(underlyingToken.isContract(), "UNDERLYING_TOKEN_IS_NOT_CONTRACT");
                                                  require(Ownable(dmmToken).owner() == address(this), "INVALID_DMM_TOKEN_OWNERSHIP");
                                          
                                                  _addMarket(dmmToken, underlyingToken);
                                              }
                                          
                                              function transferOwnershipToNewController(
                                                  address newController
                                              )
                                              onlyOwner
                                              public {
                                                  require(newController.isContract(), "NEW_CONTROLLER_IS_NOT_CONTRACT");
                                                  // All of the following contracts are owned by the controller. All other ownable contracts are owned by the
                                                  // same owner as this controller.
                                                  for (uint i = 0; i < dmmTokenIds.length; i++) {
                                                      address dmmToken = dmmTokenIdToDmmTokenAddressMap[dmmTokenIds[i]];
                                                      Ownable(dmmToken).transferOwnership(newController);
                                                  }
                                                  Ownable(address(dmmEtherFactory)).transferOwnership(newController);
                                                  Ownable(address(dmmTokenFactory)).transferOwnership(newController);
                                              }
                                          
                                              function enableMarket(uint dmmTokenId) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
                                                  require(dmmTokenIdToIsDisabledMap[dmmTokenId], "MARKET_ALREADY_ENABLED");
                                                  dmmTokenIdToIsDisabledMap[dmmTokenId] = false;
                                                  emit EnableMarket(dmmTokenId);
                                              }
                                          
                                              function disableMarket(uint dmmTokenId) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
                                                  require(!dmmTokenIdToIsDisabledMap[dmmTokenId], "MARKET_ALREADY_DISABLED");
                                                  dmmTokenIdToIsDisabledMap[dmmTokenId] = true;
                                                  emit DisableMarket(dmmTokenId);
                                              }
                                          
                                              function setInterestRateInterface(address newInterestRateInterface) public whenNotPaused onlyOwner {
                                                  address oldInterestRateInterface = address(interestRateInterface);
                                                  interestRateInterface = InterestRateInterface(newInterestRateInterface);
                                                  emit InterestRateInterfaceChanged(oldInterestRateInterface, address(interestRateInterface));
                                              }
                                          
                                              function setOffChainAssetValuator(address newOffChainAssetValuator) public whenNotPaused onlyOwner {
                                                  address oldOffChainAssetValuator = address(offChainAssetsValuator);
                                                  offChainAssetsValuator = IOffChainAssetValuator(newOffChainAssetValuator);
                                                  emit OffChainAssetValuatorChanged(oldOffChainAssetValuator, address(offChainAssetsValuator));
                                              }
                                          
                                              function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) public whenNotPaused onlyOwner {
                                                  address oldOffChainCurrencyValuator = address(offChainCurrencyValuator);
                                                  offChainCurrencyValuator = IOffChainCurrencyValuator(newOffChainCurrencyValuator);
                                                  emit OffChainCurrencyValuatorChanged(oldOffChainCurrencyValuator, address(offChainCurrencyValuator));
                                              }
                                          
                                              function setUnderlyingTokenValuator(address newUnderlyingTokenValuator) public whenNotPaused onlyOwner {
                                                  address oldUnderlyingTokenValuator = address(underlyingTokenValuator);
                                                  underlyingTokenValuator = IUnderlyingTokenValuator(newUnderlyingTokenValuator);
                                                  emit UnderlyingTokenValuatorChanged(oldUnderlyingTokenValuator, address(underlyingTokenValuator));
                                              }
                                          
                                              function setMinCollateralization(uint newMinCollateralization) public whenNotPaused onlyOwner {
                                                  uint oldMinCollateralization = minCollateralization;
                                                  minCollateralization = newMinCollateralization;
                                                  emit MinCollateralizationChanged(oldMinCollateralization, minCollateralization);
                                              }
                                          
                                              function setMinReserveRatio(uint newMinReserveRatio) public whenNotPaused onlyOwner {
                                                  uint oldMinReserveRatio = minReserveRatio;
                                                  minReserveRatio = newMinReserveRatio;
                                                  emit MinReserveRatioChanged(oldMinReserveRatio, minReserveRatio);
                                              }
                                          
                                              function increaseTotalSupply(
                                                  uint dmmTokenId,
                                                  uint amount
                                              ) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
                                                  IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenId]).increaseTotalSupply(amount);
                                                  require(getTotalCollateralization() >= minCollateralization, "INSUFFICIENT_COLLATERAL");
                                              }
                                          
                                              function decreaseTotalSupply(
                                                  uint dmmTokenId,
                                                  uint amount
                                              ) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
                                                  IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenId]).decreaseTotalSupply(amount);
                                              }
                                          
                                              function adminWithdrawFunds(
                                                  uint dmmTokenId,
                                                  uint underlyingAmount
                                              ) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
                                                  // Attempt to pull from the DMM contract into this contract, then send from this contract to sender.
                                                  IDmmToken token = IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenId]);
                                                  token.withdrawUnderlying(underlyingAmount);
                                                  IERC20 underlyingToken = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]);
                                                  underlyingToken.safeTransfer(_msgSender(), underlyingAmount);
                                          
                                                  // This is the amount owed by the system in terms of underlying
                                                  uint totalOwedAmount = token.activeSupply().mul(token.getCurrentExchangeRate()).div(EXCHANGE_RATE_BASE_RATE);
                                                  uint underlyingBalance = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]).balanceOf(address(token));
                                          
                                                  if (totalOwedAmount > 0) {
                                                      // IE if we owe 100 and have an underlying balance of 10 --> reserve ratio is 0.1
                                                      uint actualReserveRatio = underlyingBalance.mul(MIN_RESERVE_RATIO_BASE_RATE).div(totalOwedAmount);
                                                      require(actualReserveRatio >= minReserveRatio, "INSUFFICIENT_LEFTOVER_RESERVES");
                                                  }
                                          
                                                  emit AdminWithdraw(_msgSender(), underlyingAmount);
                                              }
                                          
                                              function adminDepositFunds(
                                                  uint dmmTokenId,
                                                  uint underlyingAmount
                                              ) public checkTokenExists(dmmTokenId) whenNotPaused onlyOwner {
                                                  // Attempt to pull from the sender into this contract, then have the DMM token pull from here.
                                                  IERC20 underlyingToken = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]);
                                                  underlyingToken.safeTransferFrom(_msgSender(), address(this), underlyingAmount);
                                          
                                                  address dmmTokenAddress = dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
                                                  underlyingToken.approve(dmmTokenAddress, underlyingAmount);
                                                  IDmmToken(dmmTokenAddress).depositUnderlying(underlyingAmount);
                                                  emit AdminDeposit(_msgSender(), underlyingAmount);
                                              }
                                          
                                              function getTotalCollateralization() public view returns (uint) {
                                                  uint totalLiabilities = 0;
                                                  uint totalAssets = 0;
                                                  for (uint i = 0; i < dmmTokenIds.length; i++) {
                                                      IDmmToken token = IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenIds[i]]);
                                          
                                                      uint currentExchangeRate = token.getCurrentExchangeRate();
                                          
                                                      // The interest rate is annualized, so figuring out the exchange rate 1-year from now is as simple as
                                                      // applying the current interest rate to the current exchange rate.
                                                      uint futureExchangeRate = currentExchangeRate.mul(INTEREST_RATE_BASE_RATE.add(getInterestRateByDmmTokenAddress(address(token)))).div(INTEREST_RATE_BASE_RATE);
                                          
                                                      uint totalSupply = IERC20(address(token)).totalSupply();
                                          
                                                      uint underlyingLiabilitiesForTotalSupply = getDmmSupplyValue(token, totalSupply, futureExchangeRate);
                                                      totalLiabilities = totalLiabilities.add(underlyingLiabilitiesForTotalSupply);
                                          
                                                      uint underlyingAssetsForTotalSupply = getDmmSupplyValue(token, totalSupply, currentExchangeRate);
                                                      totalAssets = totalAssets.add(underlyingAssetsForTotalSupply);
                                                  }
                                                  return getCollateralization(totalLiabilities, totalAssets);
                                              }
                                          
                                              function getActiveCollateralization() public view returns (uint) {
                                                  uint totalLiabilities = 0;
                                                  uint totalAssetsInDmmContract = 0;
                                                  for (uint i = 0; i < dmmTokenIds.length; i++) {
                                                      IDmmToken token = IDmmToken(dmmTokenIdToDmmTokenAddressMap[dmmTokenIds[i]]);
                                                      uint underlyingLiabilitiesValue = getDmmSupplyValue(token, token.activeSupply(), token.getCurrentExchangeRate());
                                                      totalLiabilities = totalLiabilities.add(underlyingLiabilitiesValue);
                                          
                                                      IERC20 underlyingToken = IERC20(getUnderlyingTokenForDmm(address(token)));
                                                      uint underlyingAssetsValue = getUnderlyingSupplyValue(underlyingToken, underlyingToken.balanceOf(address(token)), token.decimals());
                                                      totalAssetsInDmmContract = totalAssetsInDmmContract.add(underlyingAssetsValue);
                                                  }
                                                  return getCollateralization(totalLiabilities, totalAssetsInDmmContract);
                                              }
                                          
                                              function getInterestRateByUnderlyingTokenAddress(address underlyingToken) public view returns (uint) {
                                                  uint dmmTokenId = underlyingTokenAddressToDmmTokenIdMap[underlyingToken];
                                                  return getInterestRateByDmmTokenId(dmmTokenId);
                                              }
                                          
                                              function getInterestRateByDmmTokenId(uint dmmTokenId) checkTokenExists(dmmTokenId) public view returns (uint) {
                                                  address dmmToken = dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
                                                  uint totalSupply = IERC20(dmmToken).totalSupply();
                                                  uint activeSupply = IDmmToken(dmmToken).activeSupply();
                                                  return interestRateInterface.getInterestRate(dmmTokenId, totalSupply, activeSupply);
                                              }
                                          
                                              function getInterestRateByDmmTokenAddress(address dmmToken) public view returns (uint) {
                                                  uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
                                                  require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
                                          
                                                  uint totalSupply = IERC20(dmmToken).totalSupply();
                                                  uint activeSupply = IDmmToken(dmmToken).activeSupply();
                                                  return interestRateInterface.getInterestRate(dmmTokenId, totalSupply, activeSupply);
                                              }
                                          
                                              function getExchangeRateByUnderlying(address underlyingToken) public view returns (uint) {
                                                  address dmmToken = getDmmTokenForUnderlying(underlyingToken);
                                                  return IDmmToken(dmmToken).getCurrentExchangeRate();
                                              }
                                          
                                              function getExchangeRate(address dmmToken) public view returns (uint) {
                                                  uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
                                                  require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
                                          
                                                  return IDmmToken(dmmToken).getCurrentExchangeRate();
                                              }
                                          
                                              function getDmmTokenForUnderlying(address underlyingToken) public view returns (address) {
                                                  uint dmmTokenId = underlyingTokenAddressToDmmTokenIdMap[underlyingToken];
                                                  require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
                                          
                                                  return dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
                                              }
                                          
                                              function getUnderlyingTokenForDmm(address dmmToken) public view returns (address) {
                                                  uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
                                                  require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
                                          
                                                  return dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId];
                                              }
                                          
                                              function isMarketEnabledByDmmTokenId(uint dmmTokenId) checkTokenExists(dmmTokenId) public view returns (bool) {
                                                  return !dmmTokenIdToIsDisabledMap[dmmTokenId];
                                              }
                                          
                                              function isMarketEnabledByDmmTokenAddress(address dmmToken) public view returns (bool) {
                                                  uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
                                                  require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
                                          
                                                  return !dmmTokenIdToIsDisabledMap[dmmTokenId];
                                              }
                                          
                                              function getTokenIdFromDmmTokenAddress(address dmmToken) public view returns (uint) {
                                                  uint dmmTokenId = dmmTokenAddressToDmmTokenIdMap[dmmToken];
                                                  require(dmmTokenId != 0, "TOKEN_DOES_NOT_EXIST");
                                          
                                                  return dmmTokenId;
                                              }
                                          
                                              function getDmmTokenIds() public view returns (uint[] memory) {
                                                  return dmmTokenIds;
                                              }
                                          
                                              /**********************
                                               * Private Functions
                                               */
                                          
                                              function _addMarket(address dmmToken, address underlyingToken) private {
                                                  // Start the IDs at 1. Zero is reserved for the empty case when it doesn't exist.
                                                  uint dmmTokenId = dmmTokenIds.length + 1;
                                          
                                                  // Update the maps
                                                  dmmTokenIdToDmmTokenAddressMap[dmmTokenId] = dmmToken;
                                                  dmmTokenAddressToDmmTokenIdMap[dmmToken] = dmmTokenId;
                                                  underlyingTokenAddressToDmmTokenIdMap[underlyingToken] = dmmTokenId;
                                                  dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId] = underlyingToken;
                                          
                                                  // Misc. Structures
                                                  dmmTokenIdToIsDisabledMap[dmmTokenId] = false;
                                                  dmmTokenIds.push(dmmTokenId);
                                          
                                                  emit MarketAdded(dmmTokenId, dmmToken, underlyingToken);
                                              }
                                          
                                              function getCollateralization(uint totalLiabilities, uint totalAssets) private view returns (uint) {
                                                  if (totalLiabilities == 0) {
                                                      return 0;
                                                  }
                                                  uint collateralValue = offChainAssetsValuator.getOffChainAssetsValue().add(totalAssets).add(offChainCurrencyValuator.getOffChainCurrenciesValue());
                                                  return collateralValue.mul(COLLATERALIZATION_BASE_RATE).div(totalLiabilities);
                                              }
                                          
                                              function getDmmSupplyValue(IDmmToken dmmToken, uint dmmSupply, uint currentExchangeRate) private view returns (uint) {
                                                  uint underlyingTokenAmount = dmmSupply.mul(currentExchangeRate).div(EXCHANGE_RATE_BASE_RATE);
                                                  // The amount returned must use 18 decimal places, regardless of the # of decimals this token has.
                                                  uint standardizedUnderlyingTokenAmount;
                                                  if (dmmToken.decimals() == 18) {
                                                      standardizedUnderlyingTokenAmount = underlyingTokenAmount;
                                                  } else if (dmmToken.decimals() < 18) {
                                                      standardizedUnderlyingTokenAmount = underlyingTokenAmount.mul((10 ** (18 - uint(dmmToken.decimals()))));
                                                  } else /* decimals > 18 */ {
                                                      standardizedUnderlyingTokenAmount = underlyingTokenAmount.div((10 ** (uint(dmmToken.decimals()) - 18)));
                                                  }
                                                  address underlyingToken = getUnderlyingTokenForDmm(address(dmmToken));
                                                  return underlyingTokenValuator.getTokenValue(underlyingToken, standardizedUnderlyingTokenAmount);
                                              }
                                          
                                              function getUnderlyingSupplyValue(IERC20 underlyingToken, uint underlyingSupply, uint8 decimals) private view returns (uint) {
                                                  // The amount returned must use 18 decimal places, regardless of the # of decimals this token has.
                                                  uint standardizedUnderlyingTokenAmount;
                                                  if (decimals == 18) {
                                                      standardizedUnderlyingTokenAmount = underlyingSupply;
                                                  } else if (decimals < 18) {
                                                      standardizedUnderlyingTokenAmount = underlyingSupply.mul((10 ** (18 - uint(decimals))));
                                                  } else /* decimals > 18 */ {
                                                      standardizedUnderlyingTokenAmount = underlyingSupply.div((10 ** (uint(decimals) - 18)));
                                                  }
                                                  return underlyingTokenValuator.getTokenValue(address(underlyingToken), standardizedUnderlyingTokenAmount);
                                              }
                                          
                                          }

                                          File 10 of 15: CompoundRegistry
                                          // File: @openzeppelin/contracts/GSN/Context.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /*
                                           * @dev Provides information about the current execution context, including the
                                           * sender of the transaction and its data. While these are generally available
                                           * via msg.sender and msg.data, they should not be accessed in such a direct
                                           * manner, since when dealing with GSN meta-transactions the account sending and
                                           * paying for execution may not be the actual sender (as far as an application
                                           * is concerned).
                                           *
                                           * This contract is only required for intermediate, library-like contracts.
                                           */
                                          contract Context {
                                              // Empty internal constructor, to prevent people from mistakenly deploying
                                              // an instance of this contract, which should be used via inheritance.
                                              constructor () internal { }
                                              // solhint-disable-previous-line no-empty-blocks
                                          
                                              function _msgSender() internal view returns (address payable) {
                                                  return msg.sender;
                                              }
                                          
                                              function _msgData() internal view returns (bytes memory) {
                                                  this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                                  return msg.data;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/ownership/Ownable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Contract module which provides a basic access control mechanism, where
                                           * there is an account (an owner) that can be granted exclusive access to
                                           * specific functions.
                                           *
                                           * This module is used through inheritance. It will make available the modifier
                                           * `onlyOwner`, which can be applied to your functions to restrict their use to
                                           * the owner.
                                           */
                                          contract Ownable is Context {
                                              address private _owner;
                                          
                                              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                          
                                              /**
                                               * @dev Initializes the contract setting the deployer as the initial owner.
                                               */
                                              constructor () internal {
                                                  address msgSender = _msgSender();
                                                  _owner = msgSender;
                                                  emit OwnershipTransferred(address(0), msgSender);
                                              }
                                          
                                              /**
                                               * @dev Returns the address of the current owner.
                                               */
                                              function owner() public view returns (address) {
                                                  return _owner;
                                              }
                                          
                                              /**
                                               * @dev Throws if called by any account other than the owner.
                                               */
                                              modifier onlyOwner() {
                                                  require(isOwner(), "Ownable: caller is not the owner");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Returns true if the caller is the current owner.
                                               */
                                              function isOwner() public view returns (bool) {
                                                  return _msgSender() == _owner;
                                              }
                                          
                                              /**
                                               * @dev Leaves the contract without owner. It will not be possible to call
                                               * `onlyOwner` functions anymore. Can only be called by the current owner.
                                               *
                                               * NOTE: Renouncing ownership will leave the contract without an owner,
                                               * thereby removing any functionality that is only available to the owner.
                                               */
                                              function renounceOwnership() public onlyOwner {
                                                  emit OwnershipTransferred(_owner, address(0));
                                                  _owner = address(0);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               * Can only be called by the current owner.
                                               */
                                              function transferOwnership(address newOwner) public onlyOwner {
                                                  _transferOwnership(newOwner);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               */
                                              function _transferOwnership(address newOwner) internal {
                                                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                                                  emit OwnershipTransferred(_owner, newOwner);
                                                  _owner = newOwner;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see {ERC20Detailed}.
                                           */
                                          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: contracts/interface/ICompound.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract ICompound {
                                              function markets(address cToken)
                                                  external
                                                  view
                                                  returns (bool isListed, uint256 collateralFactorMantissa);
                                          }
                                          
                                          
                                          contract ICompoundToken is IERC20 {
                                              function underlying() external view returns (address);
                                          
                                              function exchangeRateStored() external view returns (uint256);
                                          
                                              function mint(uint256 mintAmount) external returns (uint256);
                                          
                                              function redeem(uint256 redeemTokens) external returns (uint256);
                                          }
                                          
                                          
                                          contract ICompoundEther is IERC20 {
                                              function mint() external payable;
                                          
                                              function redeem(uint256 redeemTokens) external returns (uint256);
                                          }
                                          
                                          // File: contracts/interface/ICompoundRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract ICompoundRegistry {
                                              function tokenByCToken(ICompoundToken cToken) external view returns(IERC20);
                                              function cTokenByToken(IERC20 token) external view returns(ICompoundToken);
                                          }
                                          
                                          // File: @openzeppelin/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.5.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, 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) {
                                                  return sub(a, b, "SafeMath: subtraction overflow");
                                              }
                                          
                                              /**
                                               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                               * overflow (when the result is negative).
                                               *
                                               * Counterpart to Solidity's `-` operator.
                                               *
                                               * Requirements:
                                               * - Subtraction cannot overflow.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b <= a, errorMessage);
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  return div(a, b, "SafeMath: division by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, errorMessage);
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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) {
                                                  return mod(a, b, "SafeMath: modulo by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b != 0, errorMessage);
                                                  return a % b;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/utils/Address.sol
                                          
                                          pragma solidity ^0.5.5;
                                          
                                          /**
                                           * @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) {
                                                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                                  // for accounts without code, i.e. `keccak256('')`
                                                  bytes32 codehash;
                                                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                                  // solhint-disable-next-line no-inline-assembly
                                                  assembly { codehash := extcodehash(account) }
                                                  return (codehash != accountHash && codehash != 0x0);
                                              }
                                          
                                              /**
                                               * @dev Converts an `address` into `address payable`. Note that this is
                                               * simply a type cast: the actual underlying value is not changed.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function toPayable(address account) internal pure returns (address payable) {
                                                  return address(uint160(account));
                                              }
                                          
                                              /**
                                               * @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].
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sendValue(address payable recipient, uint256 amount) internal {
                                                  require(address(this).balance >= amount, "Address: insufficient balance");
                                          
                                                  // solhint-disable-next-line avoid-call-value
                                                  (bool success, ) = recipient.call.value(amount)("");
                                                  require(success, "Address: unable to send value, recipient may have reverted");
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                                          
                                          pragma solidity ^0.5.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 ERC20;` 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));
                                              }
                                          
                                              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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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: contracts/UniversalERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          library UniversalERC20 {
                                          
                                              using SafeMath for uint256;
                                              using SafeERC20 for IERC20;
                                          
                                              IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
                                              IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
                                                  if (amount == 0) {
                                                      return true;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      address(uint160(to)).transfer(amount);
                                                  } else {
                                                      token.safeTransfer(to, amount);
                                                      return true;
                                                  }
                                              }
                                          
                                              function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
                                                      if (to != address(this)) {
                                                          address(uint160(to)).transfer(amount);
                                                      }
                                                      if (msg.value > amount) {
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(from, to, amount);
                                                  }
                                              }
                                          
                                              function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      if (msg.value > amount) {
                                                          // Return remainder if exist
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(msg.sender, address(this), amount);
                                                  }
                                              }
                                          
                                              function universalApprove(IERC20 token, address to, uint256 amount) internal {
                                                  if (!isETH(token)) {
                                                      if (amount == 0) {
                                                          token.safeApprove(to, 0);
                                                          return;
                                                      }
                                          
                                                      uint256 allowance = token.allowance(address(this), to);
                                                      if (allowance < amount) {
                                                          if (allowance > 0) {
                                                              token.safeApprove(to, 0);
                                                          }
                                                          token.safeApprove(to, amount);
                                                      }
                                                  }
                                              }
                                          
                                              function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
                                                  if (isETH(token)) {
                                                      return who.balance;
                                                  } else {
                                                      return token.balanceOf(who);
                                                  }
                                              }
                                          
                                              function universalDecimals(IERC20 token) internal view returns (uint256) {
                                          
                                                  if (isETH(token)) {
                                                      return 18;
                                                  }
                                          
                                                  (bool success, bytes memory data) = address(token).staticcall.gas(10000)(
                                                      abi.encodeWithSignature("decimals()")
                                                  );
                                                  if (!success || data.length == 0) {
                                                      (success, data) = address(token).staticcall.gas(10000)(
                                                          abi.encodeWithSignature("DECIMALS()")
                                                      );
                                                  }
                                          
                                                  return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
                                              }
                                          
                                              function isETH(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
                                              }
                                          
                                              function notExist(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(-1));
                                              }
                                          }
                                          
                                          // File: contracts/CompoundRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract CompoundRegistry is Ownable, ICompoundRegistry {
                                              using UniversalERC20 for IERC20;
                                          
                                              ICompoundToken internal constant cETH = ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
                                              IERC20 internal constant ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              mapping(address => address) private _tokenByCToken;
                                              mapping(address => address) private _cTokenByToken;
                                          
                                              function tokenByCToken(ICompoundToken cToken) external view returns(IERC20) {
                                                  if (cToken == cETH) {
                                                      return ETH;
                                                  }
                                                  return IERC20(_tokenByCToken[address(cToken)]);
                                              }
                                          
                                              function cTokenByToken(IERC20 token) external view returns(ICompoundToken) {
                                                  if (token.isETH()) {
                                                      return cETH;
                                                  }
                                                  return ICompoundToken(_cTokenByToken[address(token)]);
                                              }
                                          
                                              function addCToken(ICompoundToken cToken) public onlyOwner {
                                                  IERC20 token = IERC20(cToken.underlying());
                                                  _tokenByCToken[address(cToken)] = address(token);
                                                  _cTokenByToken[address(token)] = address(cToken);
                                              }
                                          
                                              function addCTokens(ICompoundToken[] calldata cTokens) external onlyOwner {
                                                  for (uint i = 0; i < cTokens.length; i++) {
                                                      addCToken(cTokens[i]);
                                                  }
                                              }
                                          }

                                          File 11 of 15: UFragments
                                          // File: openzeppelin-eth/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.4.24;
                                          
                                          
                                          /**
                                           * @title SafeMath
                                           * @dev Math operations with safety checks that revert on error
                                           */
                                          library SafeMath {
                                          
                                            /**
                                            * @dev Multiplies two numbers, reverts on overflow.
                                            */
                                            function mul(uint256 a, uint256 b) internal pure returns (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-solidity/pull/522
                                              if (a == 0) {
                                                return 0;
                                              }
                                          
                                              uint256 c = a * b;
                                              require(c / a == b);
                                          
                                              return c;
                                            }
                                          
                                            /**
                                            * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                            */
                                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                              require(b > 0); // Solidity only automatically asserts when dividing by 0
                                              uint256 c = a / b;
                                              // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                              return c;
                                            }
                                          
                                            /**
                                            * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                                            */
                                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                              require(b <= a);
                                              uint256 c = a - b;
                                          
                                              return c;
                                            }
                                          
                                            /**
                                            * @dev Adds two numbers, reverts on overflow.
                                            */
                                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                              uint256 c = a + b;
                                              require(c >= a);
                                          
                                              return c;
                                            }
                                          
                                            /**
                                            * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
                                            * reverts when dividing by zero.
                                            */
                                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                              require(b != 0);
                                              return a % b;
                                            }
                                          }
                                          
                                          // File: zos-lib/contracts/Initializable.sol
                                          
                                          pragma solidity >=0.4.24 <0.6.0;
                                          
                                          
                                          /**
                                           * @title Initializable
                                           *
                                           * @dev Helper contract to support initializer functions. To use it, replace
                                           * the constructor with a function that has the `initializer` modifier.
                                           * WARNING: Unlike constructors, initializer functions must be manually
                                           * invoked. This applies both to deploying an Initializable contract, as well
                                           * as extending an Initializable contract via inheritance.
                                           * WARNING: When used with inheritance, manual care must be taken to not invoke
                                           * a parent initializer twice, or ensure that all initializers are idempotent,
                                           * because this is not dealt with automatically as with constructors.
                                           */
                                          contract Initializable {
                                          
                                            /**
                                             * @dev Indicates that the contract has been initialized.
                                             */
                                            bool private initialized;
                                          
                                            /**
                                             * @dev Indicates that the contract is in the process of being initialized.
                                             */
                                            bool private initializing;
                                          
                                            /**
                                             * @dev Modifier to use in the initializer function of a contract.
                                             */
                                            modifier initializer() {
                                              require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
                                          
                                              bool isTopLevelCall = !initializing;
                                              if (isTopLevelCall) {
                                                initializing = true;
                                                initialized = true;
                                              }
                                          
                                              _;
                                          
                                              if (isTopLevelCall) {
                                                initializing = false;
                                              }
                                            }
                                          
                                            /// @dev Returns true if and only if the function is running in the constructor
                                            function isConstructor() private view returns (bool) {
                                              // extcodesize checks the size of the code stored in an address, and
                                              // address returns the current address. Since the code is still not
                                              // deployed when running a constructor, any checks on its code size will
                                              // yield zero, making it an effective way to detect if a contract is
                                              // under construction or not.
                                              uint256 cs;
                                              assembly { cs := extcodesize(address) }
                                              return cs == 0;
                                            }
                                          
                                            // Reserved storage space to allow for layout changes in the future.
                                            uint256[50] private ______gap;
                                          }
                                          
                                          // File: openzeppelin-eth/contracts/ownership/Ownable.sol
                                          
                                          pragma solidity ^0.4.24;
                                          
                                          
                                          /**
                                           * @title Ownable
                                           * @dev The Ownable contract has an owner address, and provides basic authorization control
                                           * functions, this simplifies the implementation of "user permissions".
                                           */
                                          contract Ownable is Initializable {
                                            address private _owner;
                                          
                                          
                                            event OwnershipRenounced(address indexed previousOwner);
                                            event OwnershipTransferred(
                                              address indexed previousOwner,
                                              address indexed newOwner
                                            );
                                          
                                          
                                            /**
                                             * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                                             * account.
                                             */
                                            function initialize(address sender) public initializer {
                                              _owner = sender;
                                            }
                                          
                                            /**
                                             * @return the address of the owner.
                                             */
                                            function owner() public view returns(address) {
                                              return _owner;
                                            }
                                          
                                            /**
                                             * @dev Throws if called by any account other than the owner.
                                             */
                                            modifier onlyOwner() {
                                              require(isOwner());
                                              _;
                                            }
                                          
                                            /**
                                             * @return true if `msg.sender` is the owner of the contract.
                                             */
                                            function isOwner() public view returns(bool) {
                                              return msg.sender == _owner;
                                            }
                                          
                                            /**
                                             * @dev Allows the current owner to relinquish control of the contract.
                                             * @notice Renouncing to ownership will leave the contract without an owner.
                                             * It will not be possible to call the functions with the `onlyOwner`
                                             * modifier anymore.
                                             */
                                            function renounceOwnership() public onlyOwner {
                                              emit OwnershipRenounced(_owner);
                                              _owner = address(0);
                                            }
                                          
                                            /**
                                             * @dev Allows the current owner to transfer control of the contract to a newOwner.
                                             * @param newOwner The address to transfer ownership to.
                                             */
                                            function transferOwnership(address newOwner) public onlyOwner {
                                              _transferOwnership(newOwner);
                                            }
                                          
                                            /**
                                             * @dev Transfers control of the contract to a newOwner.
                                             * @param newOwner The address to transfer ownership to.
                                             */
                                            function _transferOwnership(address newOwner) internal {
                                              require(newOwner != address(0));
                                              emit OwnershipTransferred(_owner, newOwner);
                                              _owner = newOwner;
                                            }
                                          
                                            uint256[50] private ______gap;
                                          }
                                          
                                          // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol
                                          
                                          pragma solidity ^0.4.24;
                                          
                                          
                                          /**
                                           * @title ERC20 interface
                                           * @dev see https://github.com/ethereum/EIPs/issues/20
                                           */
                                          interface IERC20 {
                                            function totalSupply() external view returns (uint256);
                                          
                                            function balanceOf(address who) external view returns (uint256);
                                          
                                            function allowance(address owner, address spender)
                                              external view returns (uint256);
                                          
                                            function transfer(address to, uint256 value) external returns (bool);
                                          
                                            function approve(address spender, uint256 value)
                                              external returns (bool);
                                          
                                            function transferFrom(address from, address to, uint256 value)
                                              external returns (bool);
                                          
                                            event Transfer(
                                              address indexed from,
                                              address indexed to,
                                              uint256 value
                                            );
                                          
                                            event Approval(
                                              address indexed owner,
                                              address indexed spender,
                                              uint256 value
                                            );
                                          }
                                          
                                          // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol
                                          
                                          pragma solidity ^0.4.24;
                                          
                                          
                                          
                                          
                                          /**
                                           * @title ERC20Detailed token
                                           * @dev The decimals are only for visualization purposes.
                                           * All the operations are done using the smallest and indivisible token unit,
                                           * just as on Ethereum all the operations are done in wei.
                                           */
                                          contract ERC20Detailed is Initializable, IERC20 {
                                            string private _name;
                                            string private _symbol;
                                            uint8 private _decimals;
                                          
                                            function initialize(string name, string symbol, uint8 decimals) public initializer {
                                              _name = name;
                                              _symbol = symbol;
                                              _decimals = decimals;
                                            }
                                          
                                            /**
                                             * @return the name of the token.
                                             */
                                            function name() public view returns(string) {
                                              return _name;
                                            }
                                          
                                            /**
                                             * @return the symbol of the token.
                                             */
                                            function symbol() public view returns(string) {
                                              return _symbol;
                                            }
                                          
                                            /**
                                             * @return the number of decimals of the token.
                                             */
                                            function decimals() public view returns(uint8) {
                                              return _decimals;
                                            }
                                          
                                            uint256[50] private ______gap;
                                          }
                                          
                                          // File: uFragments/contracts/lib/SafeMathInt.sol
                                          
                                          /*
                                          MIT License
                                          
                                          Copyright (c) 2018 requestnetwork
                                          Copyright (c) 2018 Fragments, Inc.
                                          
                                          Permission is hereby granted, free of charge, to any person obtaining a copy
                                          of this software and associated documentation files (the "Software"), to deal
                                          in the Software without restriction, including without limitation the rights
                                          to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                                          copies of the Software, and to permit persons to whom the Software is
                                          furnished to do so, subject to the following conditions:
                                          
                                          The above copyright notice and this permission notice shall be included in all
                                          copies or substantial portions of the Software.
                                          
                                          THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                                          IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                                          FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                                          AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                                          LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                                          OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                                          SOFTWARE.
                                          */
                                          
                                          pragma solidity 0.4.24;
                                          
                                          
                                          /**
                                           * @title SafeMathInt
                                           * @dev Math operations for int256 with overflow safety checks.
                                           */
                                          library SafeMathInt {
                                              int256 private constant MIN_INT256 = int256(1) << 255;
                                              int256 private constant MAX_INT256 = ~(int256(1) << 255);
                                          
                                              /**
                                               * @dev Multiplies two int256 variables and fails on overflow.
                                               */
                                              function mul(int256 a, int256 b)
                                                  internal
                                                  pure
                                                  returns (int256)
                                              {
                                                  int256 c = a * b;
                                          
                                                  // Detect overflow when multiplying MIN_INT256 with -1
                                                  require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
                                                  require((b == 0) || (c / b == a));
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Division of two int256 variables and fails on overflow.
                                               */
                                              function div(int256 a, int256 b)
                                                  internal
                                                  pure
                                                  returns (int256)
                                              {
                                                  // Prevent overflow when dividing MIN_INT256 by -1
                                                  require(b != -1 || a != MIN_INT256);
                                          
                                                  // Solidity already throws when dividing by 0.
                                                  return a / b;
                                              }
                                          
                                              /**
                                               * @dev Subtracts two int256 variables and fails on overflow.
                                               */
                                              function sub(int256 a, int256 b)
                                                  internal
                                                  pure
                                                  returns (int256)
                                              {
                                                  int256 c = a - b;
                                                  require((b >= 0 && c <= a) || (b < 0 && c > a));
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Adds two int256 variables and fails on overflow.
                                               */
                                              function add(int256 a, int256 b)
                                                  internal
                                                  pure
                                                  returns (int256)
                                              {
                                                  int256 c = a + b;
                                                  require((b >= 0 && c >= a) || (b < 0 && c < a));
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Converts to absolute value, and fails on overflow.
                                               */
                                              function abs(int256 a)
                                                  internal
                                                  pure
                                                  returns (int256)
                                              {
                                                  require(a != MIN_INT256);
                                                  return a < 0 ? -a : a;
                                              }
                                          }
                                          
                                          // File: uFragments/contracts/UFragments.sol
                                          
                                          pragma solidity 0.4.24;
                                          
                                          
                                          
                                          
                                          
                                          
                                          /**
                                           * @title uFragments ERC20 token
                                           * @dev This is part of an implementation of the uFragments Ideal Money protocol.
                                           *      uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and
                                           *      combining tokens proportionally across all wallets.
                                           *
                                           *      uFragment balances are internally represented with a hidden denomination, 'gons'.
                                           *      We support splitting the currency in expansion and combining the currency on contraction by
                                           *      changing the exchange rate between the hidden 'gons' and the public 'fragments'.
                                           */
                                          contract UFragments is ERC20Detailed, Ownable {
                                              // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
                                              // Anytime there is division, there is a risk of numerical instability from rounding errors. In
                                              // order to minimize this risk, we adhere to the following guidelines:
                                              // 1) The conversion rate adopted is the number of gons that equals 1 fragment.
                                              //    The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
                                              //    always the denominator. (i.e. If you want to convert gons to fragments instead of
                                              //    multiplying by the inverse rate, you should divide by the normal rate)
                                              // 2) Gon balances converted into Fragments are always rounded down (truncated).
                                              //
                                              // We make the following guarantees:
                                              // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will
                                              //   be decreased by precisely x Fragments, and B's external balance will be precisely
                                              //   increased by x Fragments.
                                              //
                                              // We do not guarantee that the sum of all balances equals the result of calling totalSupply().
                                              // This is because, for any conversion function 'f()' that has non-zero rounding error,
                                              // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
                                              using SafeMath for uint256;
                                              using SafeMathInt for int256;
                                          
                                              event LogRebase(uint256 indexed epoch, uint256 totalSupply);
                                              event LogRebasePaused(bool paused);
                                              event LogTokenPaused(bool paused);
                                              event LogMonetaryPolicyUpdated(address monetaryPolicy);
                                          
                                              // Used for authentication
                                              address public monetaryPolicy;
                                          
                                              modifier onlyMonetaryPolicy() {
                                                  require(msg.sender == monetaryPolicy);
                                                  _;
                                              }
                                          
                                              // Precautionary emergency controls.
                                              bool public rebasePaused;
                                              bool public tokenPaused;
                                          
                                              modifier whenRebaseNotPaused() {
                                                  require(!rebasePaused);
                                                  _;
                                              }
                                          
                                              modifier whenTokenNotPaused() {
                                                  require(!tokenPaused);
                                                  _;
                                              }
                                          
                                              modifier validRecipient(address to) {
                                                  require(to != address(0x0));
                                                  require(to != address(this));
                                                  _;
                                              }
                                          
                                              uint256 private constant DECIMALS = 9;
                                              uint256 private constant MAX_UINT256 = ~uint256(0);
                                              uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 50 * 10**6 * 10**DECIMALS;
                                          
                                              // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
                                              // Use the highest value that fits in a uint256 for max granularity.
                                              uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
                                          
                                              // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
                                              uint256 private constant MAX_SUPPLY = ~uint128(0);  // (2^128) - 1
                                          
                                              uint256 private _totalSupply;
                                              uint256 private _gonsPerFragment;
                                              mapping(address => uint256) private _gonBalances;
                                          
                                              // This is denominated in Fragments, because the gons-fragments conversion might change before
                                              // it's fully paid.
                                              mapping (address => mapping (address => uint256)) private _allowedFragments;
                                          
                                              /**
                                               * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
                                               */
                                              function setMonetaryPolicy(address monetaryPolicy_)
                                                  external
                                                  onlyOwner
                                              {
                                                  monetaryPolicy = monetaryPolicy_;
                                                  emit LogMonetaryPolicyUpdated(monetaryPolicy_);
                                              }
                                          
                                              /**
                                               * @dev Pauses or unpauses the execution of rebase operations.
                                               * @param paused Pauses rebase operations if this is true.
                                               */
                                              function setRebasePaused(bool paused)
                                                  external
                                                  onlyOwner
                                              {
                                                  rebasePaused = paused;
                                                  emit LogRebasePaused(paused);
                                              }
                                          
                                              /**
                                               * @dev Pauses or unpauses execution of ERC-20 transactions.
                                               * @param paused Pauses ERC-20 transactions if this is true.
                                               */
                                              function setTokenPaused(bool paused)
                                                  external
                                                  onlyOwner
                                              {
                                                  tokenPaused = paused;
                                                  emit LogTokenPaused(paused);
                                              }
                                          
                                              /**
                                               * @dev Notifies Fragments contract about a new rebase cycle.
                                               * @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
                                               * @return The total number of fragments after the supply adjustment.
                                               */
                                              function rebase(uint256 epoch, int256 supplyDelta)
                                                  external
                                                  onlyMonetaryPolicy
                                                  whenRebaseNotPaused
                                                  returns (uint256)
                                              {
                                                  if (supplyDelta == 0) {
                                                      emit LogRebase(epoch, _totalSupply);
                                                      return _totalSupply;
                                                  }
                                          
                                                  if (supplyDelta < 0) {
                                                      _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
                                                  } else {
                                                      _totalSupply = _totalSupply.add(uint256(supplyDelta));
                                                  }
                                          
                                                  if (_totalSupply > MAX_SUPPLY) {
                                                      _totalSupply = MAX_SUPPLY;
                                                  }
                                          
                                                  _gonsPerFragment = TOTAL_GONS.div(_totalSupply);
                                          
                                                  // From this point forward, _gonsPerFragment is taken as the source of truth.
                                                  // We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
                                                  // conversion rate.
                                                  // This means our applied supplyDelta can deviate from the requested supplyDelta,
                                                  // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
                                                  //
                                                  // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
                                                  // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
                                                  // ever increased, it must be re-included.
                                                  // _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
                                          
                                                  emit LogRebase(epoch, _totalSupply);
                                                  return _totalSupply;
                                              }
                                          
                                              function initialize(address owner_)
                                                  public
                                                  initializer
                                              {
                                                  ERC20Detailed.initialize("Ampleforth", "AMPL", uint8(DECIMALS));
                                                  Ownable.initialize(owner_);
                                          
                                                  rebasePaused = false;
                                                  tokenPaused = false;
                                          
                                                  _totalSupply = INITIAL_FRAGMENTS_SUPPLY;
                                                  _gonBalances[owner_] = TOTAL_GONS;
                                                  _gonsPerFragment = TOTAL_GONS.div(_totalSupply);
                                          
                                                  emit Transfer(address(0x0), owner_, _totalSupply);
                                              }
                                          
                                              /**
                                               * @return The total number of fragments.
                                               */
                                              function totalSupply()
                                                  public
                                                  view
                                                  returns (uint256)
                                              {
                                                  return _totalSupply;
                                              }
                                          
                                              /**
                                               * @param who The address to query.
                                               * @return The balance of the specified address.
                                               */
                                              function balanceOf(address who)
                                                  public
                                                  view
                                                  returns (uint256)
                                              {
                                                  return _gonBalances[who].div(_gonsPerFragment);
                                              }
                                          
                                              /**
                                               * @dev Transfer tokens to a specified address.
                                               * @param to The address to transfer to.
                                               * @param value The amount to be transferred.
                                               * @return True on success, false otherwise.
                                               */
                                              function transfer(address to, uint256 value)
                                                  public
                                                  validRecipient(to)
                                                  whenTokenNotPaused
                                                  returns (bool)
                                              {
                                                  uint256 gonValue = value.mul(_gonsPerFragment);
                                                  _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
                                                  _gonBalances[to] = _gonBalances[to].add(gonValue);
                                                  emit Transfer(msg.sender, to, value);
                                                  return true;
                                              }
                                          
                                              /**
                                               * @dev Function to check the amount of tokens that an owner has allowed to a spender.
                                               * @param owner_ The address which owns the funds.
                                               * @param spender The address which will spend the funds.
                                               * @return The number of tokens still available for the spender.
                                               */
                                              function allowance(address owner_, address spender)
                                                  public
                                                  view
                                                  returns (uint256)
                                              {
                                                  return _allowedFragments[owner_][spender];
                                              }
                                          
                                              /**
                                               * @dev Transfer tokens from one address to another.
                                               * @param from The address you want to send tokens from.
                                               * @param to The address you want to transfer to.
                                               * @param value The amount of tokens to be transferred.
                                               */
                                              function transferFrom(address from, address to, uint256 value)
                                                  public
                                                  validRecipient(to)
                                                  whenTokenNotPaused
                                                  returns (bool)
                                              {
                                                  _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
                                          
                                                  uint256 gonValue = value.mul(_gonsPerFragment);
                                                  _gonBalances[from] = _gonBalances[from].sub(gonValue);
                                                  _gonBalances[to] = _gonBalances[to].add(gonValue);
                                                  emit Transfer(from, to, value);
                                          
                                                  return true;
                                              }
                                          
                                              /**
                                               * @dev Approve the passed address to spend the specified amount of tokens on behalf of
                                               * msg.sender. This method is included for ERC20 compatibility.
                                               * increaseAllowance and decreaseAllowance should be used instead.
                                               * Changing an allowance with this method brings the risk that someone may transfer both
                                               * the old and the new allowance - if they are both greater than zero - if a transfer
                                               * transaction is mined before the later approve() call is mined.
                                               *
                                               * @param spender The address which will spend the funds.
                                               * @param value The amount of tokens to be spent.
                                               */
                                              function approve(address spender, uint256 value)
                                                  public
                                                  whenTokenNotPaused
                                                  returns (bool)
                                              {
                                                  _allowedFragments[msg.sender][spender] = value;
                                                  emit Approval(msg.sender, spender, value);
                                                  return true;
                                              }
                                          
                                              /**
                                               * @dev Increase the amount of tokens that an owner has allowed to a spender.
                                               * This method should be used instead of approve() to avoid the double approval vulnerability
                                               * described above.
                                               * @param spender The address which will spend the funds.
                                               * @param addedValue The amount of tokens to increase the allowance by.
                                               */
                                              function increaseAllowance(address spender, uint256 addedValue)
                                                  public
                                                  whenTokenNotPaused
                                                  returns (bool)
                                              {
                                                  _allowedFragments[msg.sender][spender] =
                                                      _allowedFragments[msg.sender][spender].add(addedValue);
                                                  emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
                                                  return true;
                                              }
                                          
                                              /**
                                               * @dev Decrease the amount of tokens that an owner has allowed to a spender.
                                               *
                                               * @param spender The address which will spend the funds.
                                               * @param subtractedValue The amount of tokens to decrease the allowance by.
                                               */
                                              function decreaseAllowance(address spender, uint256 subtractedValue)
                                                  public
                                                  whenTokenNotPaused
                                                  returns (bool)
                                              {
                                                  uint256 oldValue = _allowedFragments[msg.sender][spender];
                                                  if (subtractedValue >= oldValue) {
                                                      _allowedFragments[msg.sender][spender] = 0;
                                                  } else {
                                                      _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
                                                  }
                                                  emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
                                                  return true;
                                              }
                                          }
                                          

                                          File 12 of 15: AaveRegistry
                                          // File: @openzeppelin/contracts/GSN/Context.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /*
                                           * @dev Provides information about the current execution context, including the
                                           * sender of the transaction and its data. While these are generally available
                                           * via msg.sender and msg.data, they should not be accessed in such a direct
                                           * manner, since when dealing with GSN meta-transactions the account sending and
                                           * paying for execution may not be the actual sender (as far as an application
                                           * is concerned).
                                           *
                                           * This contract is only required for intermediate, library-like contracts.
                                           */
                                          contract Context {
                                              // Empty internal constructor, to prevent people from mistakenly deploying
                                              // an instance of this contract, which should be used via inheritance.
                                              constructor () internal { }
                                              // solhint-disable-previous-line no-empty-blocks
                                          
                                              function _msgSender() internal view returns (address payable) {
                                                  return msg.sender;
                                              }
                                          
                                              function _msgData() internal view returns (bytes memory) {
                                                  this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                                  return msg.data;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/ownership/Ownable.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Contract module which provides a basic access control mechanism, where
                                           * there is an account (an owner) that can be granted exclusive access to
                                           * specific functions.
                                           *
                                           * This module is used through inheritance. It will make available the modifier
                                           * `onlyOwner`, which can be applied to your functions to restrict their use to
                                           * the owner.
                                           */
                                          contract Ownable is Context {
                                              address private _owner;
                                          
                                              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                          
                                              /**
                                               * @dev Initializes the contract setting the deployer as the initial owner.
                                               */
                                              constructor () internal {
                                                  address msgSender = _msgSender();
                                                  _owner = msgSender;
                                                  emit OwnershipTransferred(address(0), msgSender);
                                              }
                                          
                                              /**
                                               * @dev Returns the address of the current owner.
                                               */
                                              function owner() public view returns (address) {
                                                  return _owner;
                                              }
                                          
                                              /**
                                               * @dev Throws if called by any account other than the owner.
                                               */
                                              modifier onlyOwner() {
                                                  require(isOwner(), "Ownable: caller is not the owner");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Returns true if the caller is the current owner.
                                               */
                                              function isOwner() public view returns (bool) {
                                                  return _msgSender() == _owner;
                                              }
                                          
                                              /**
                                               * @dev Leaves the contract without owner. It will not be possible to call
                                               * `onlyOwner` functions anymore. Can only be called by the current owner.
                                               *
                                               * NOTE: Renouncing ownership will leave the contract without an owner,
                                               * thereby removing any functionality that is only available to the owner.
                                               */
                                              function renounceOwnership() public onlyOwner {
                                                  emit OwnershipTransferred(_owner, address(0));
                                                  _owner = address(0);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               * Can only be called by the current owner.
                                               */
                                              function transferOwnership(address newOwner) public onlyOwner {
                                                  _transferOwnership(newOwner);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               */
                                              function _transferOwnership(address newOwner) internal {
                                                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                                                  emit OwnershipTransferred(_owner, newOwner);
                                                  _owner = newOwner;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see {ERC20Detailed}.
                                           */
                                          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: contracts/interface/IAaveToken.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          contract IAaveToken is IERC20 {
                                              function underlyingAssetAddress() external view returns (IERC20);
                                          
                                              function redeem(uint256 amount) external;
                                          }
                                          
                                          
                                          interface IAaveLendingPool {
                                              function core() external view returns (address);
                                          
                                              function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
                                          }
                                          
                                          // File: contracts/interface/IAaveRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          contract IAaveRegistry {
                                              function tokenByAToken(IAaveToken aToken) external view returns(IERC20);
                                              function aTokenByToken(IERC20 token) external view returns(IAaveToken);
                                          }
                                          
                                          // File: @openzeppelin/contracts/math/SafeMath.sol
                                          
                                          pragma solidity ^0.5.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, 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) {
                                                  return sub(a, b, "SafeMath: subtraction overflow");
                                              }
                                          
                                              /**
                                               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                               * overflow (when the result is negative).
                                               *
                                               * Counterpart to Solidity's `-` operator.
                                               *
                                               * Requirements:
                                               * - Subtraction cannot overflow.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b <= a, errorMessage);
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  return div(a, b, "SafeMath: division by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, errorMessage);
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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) {
                                                  return mod(a, b, "SafeMath: modulo by zero");
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts with custom message 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.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                                  require(b != 0, errorMessage);
                                                  return a % b;
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/utils/Address.sol
                                          
                                          pragma solidity ^0.5.5;
                                          
                                          /**
                                           * @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) {
                                                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                                  // for accounts without code, i.e. `keccak256('')`
                                                  bytes32 codehash;
                                                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                                  // solhint-disable-next-line no-inline-assembly
                                                  assembly { codehash := extcodehash(account) }
                                                  return (codehash != accountHash && codehash != 0x0);
                                              }
                                          
                                              /**
                                               * @dev Converts an `address` into `address payable`. Note that this is
                                               * simply a type cast: the actual underlying value is not changed.
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function toPayable(address account) internal pure returns (address payable) {
                                                  return address(uint160(account));
                                              }
                                          
                                              /**
                                               * @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].
                                               *
                                               * _Available since v2.4.0._
                                               */
                                              function sendValue(address payable recipient, uint256 amount) internal {
                                                  require(address(this).balance >= amount, "Address: insufficient balance");
                                          
                                                  // solhint-disable-next-line avoid-call-value
                                                  (bool success, ) = recipient.call.value(amount)("");
                                                  require(success, "Address: unable to send value, recipient may have reverted");
                                              }
                                          }
                                          
                                          // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                                          
                                          pragma solidity ^0.5.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 ERC20;` 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));
                                              }
                                          
                                              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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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: contracts/UniversalERC20.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          library UniversalERC20 {
                                          
                                              using SafeMath for uint256;
                                              using SafeERC20 for IERC20;
                                          
                                              IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
                                              IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
                                                  if (amount == 0) {
                                                      return true;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      address(uint160(to)).transfer(amount);
                                                  } else {
                                                      token.safeTransfer(to, amount);
                                                      return true;
                                                  }
                                              }
                                          
                                              function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
                                                      if (to != address(this)) {
                                                          address(uint160(to)).transfer(amount);
                                                      }
                                                      if (msg.value > amount) {
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(from, to, amount);
                                                  }
                                              }
                                          
                                              function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (isETH(token)) {
                                                      if (msg.value > amount) {
                                                          // Return remainder if exist
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(msg.sender, address(this), amount);
                                                  }
                                              }
                                          
                                              function universalApprove(IERC20 token, address to, uint256 amount) internal {
                                                  if (!isETH(token)) {
                                                      if (amount == 0) {
                                                          token.safeApprove(to, 0);
                                                          return;
                                                      }
                                          
                                                      uint256 allowance = token.allowance(address(this), to);
                                                      if (allowance < amount) {
                                                          if (allowance > 0) {
                                                              token.safeApprove(to, 0);
                                                          }
                                                          token.safeApprove(to, amount);
                                                      }
                                                  }
                                              }
                                          
                                              function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
                                                  if (isETH(token)) {
                                                      return who.balance;
                                                  } else {
                                                      return token.balanceOf(who);
                                                  }
                                              }
                                          
                                              function universalDecimals(IERC20 token) internal view returns (uint256) {
                                          
                                                  if (isETH(token)) {
                                                      return 18;
                                                  }
                                          
                                                  (bool success, bytes memory data) = address(token).staticcall.gas(10000)(
                                                      abi.encodeWithSignature("decimals()")
                                                  );
                                                  if (!success || data.length == 0) {
                                                      (success, data) = address(token).staticcall.gas(10000)(
                                                          abi.encodeWithSignature("DECIMALS()")
                                                      );
                                                  }
                                          
                                                  return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
                                              }
                                          
                                              function isETH(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
                                              }
                                          
                                              function notExist(IERC20 token) internal pure returns(bool) {
                                                  return (address(token) == address(-1));
                                              }
                                          }
                                          
                                          // File: contracts/AaveRegistry.sol
                                          
                                          pragma solidity ^0.5.0;
                                          
                                          
                                          
                                          
                                          
                                          
                                          contract AaveRegistry is Ownable, IAaveRegistry {
                                              using UniversalERC20 for IERC20;
                                          
                                              IAaveToken internal constant aETH = IAaveToken(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04);
                                              IERC20 internal constant ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              mapping(address => address) private _tokenByAToken;
                                              mapping(address => address) private _aTokenByToken;
                                          
                                              function tokenByAToken(IAaveToken aToken) external view returns(IERC20) {
                                                  if (aToken == aETH) {
                                                      return ETH;
                                                  }
                                                  return IERC20(_tokenByAToken[address(aToken)]);
                                              }
                                          
                                              function aTokenByToken(IERC20 token) external view returns(IAaveToken) {
                                                  if (token.isETH()) {
                                                      return aETH;
                                                  }
                                                  return IAaveToken(_aTokenByToken[address(token)]);
                                              }
                                          
                                              function addAToken(IAaveToken aToken) public onlyOwner {
                                                  IERC20 token = IERC20(aToken.underlyingAssetAddress());
                                                  _tokenByAToken[address(aToken)] = address(token);
                                                  _aTokenByToken[address(token)] = address(aToken);
                                              }
                                          
                                              function addATokens(IAaveToken[] calldata cTokens) external onlyOwner {
                                                  for (uint i = 0; i < cTokens.length; i++) {
                                                      addAToken(cTokens[i]);
                                                  }
                                              }
                                          }

                                          File 13 of 15: UniswapV2Factory
                                          pragma solidity =0.5.16;
                                          
                                          interface IUniswapV2Factory {
                                              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                                          
                                              function feeTo() external view returns (address);
                                              function feeToSetter() external view returns (address);
                                          
                                              function getPair(address tokenA, address tokenB) external view returns (address pair);
                                              function allPairs(uint) external view returns (address pair);
                                              function allPairsLength() external view returns (uint);
                                          
                                              function createPair(address tokenA, address tokenB) external returns (address pair);
                                          
                                              function setFeeTo(address) external;
                                              function setFeeToSetter(address) external;
                                          }
                                          
                                          interface IUniswapV2Pair {
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              function name() external pure returns (string memory);
                                              function symbol() external pure returns (string memory);
                                              function decimals() external pure returns (uint8);
                                              function totalSupply() external view returns (uint);
                                              function balanceOf(address owner) external view returns (uint);
                                              function allowance(address owner, address spender) external view returns (uint);
                                          
                                              function approve(address spender, uint value) external returns (bool);
                                              function transfer(address to, uint value) external returns (bool);
                                              function transferFrom(address from, address to, uint value) external returns (bool);
                                          
                                              function DOMAIN_SEPARATOR() external view returns (bytes32);
                                              function PERMIT_TYPEHASH() external pure returns (bytes32);
                                              function nonces(address owner) external view returns (uint);
                                          
                                              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                                          
                                              event Mint(address indexed sender, uint amount0, uint amount1);
                                              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                              event Swap(
                                                  address indexed sender,
                                                  uint amount0In,
                                                  uint amount1In,
                                                  uint amount0Out,
                                                  uint amount1Out,
                                                  address indexed to
                                              );
                                              event Sync(uint112 reserve0, uint112 reserve1);
                                          
                                              function MINIMUM_LIQUIDITY() external pure returns (uint);
                                              function factory() external view returns (address);
                                              function token0() external view returns (address);
                                              function token1() external view returns (address);
                                              function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                                              function price0CumulativeLast() external view returns (uint);
                                              function price1CumulativeLast() external view returns (uint);
                                              function kLast() external view returns (uint);
                                          
                                              function mint(address to) external returns (uint liquidity);
                                              function burn(address to) external returns (uint amount0, uint amount1);
                                              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                                              function skim(address to) external;
                                              function sync() external;
                                          
                                              function initialize(address, address) external;
                                          }
                                          
                                          interface IUniswapV2ERC20 {
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              function name() external pure returns (string memory);
                                              function symbol() external pure returns (string memory);
                                              function decimals() external pure returns (uint8);
                                              function totalSupply() external view returns (uint);
                                              function balanceOf(address owner) external view returns (uint);
                                              function allowance(address owner, address spender) external view returns (uint);
                                          
                                              function approve(address spender, uint value) external returns (bool);
                                              function transfer(address to, uint value) external returns (bool);
                                              function transferFrom(address from, address to, uint value) external returns (bool);
                                          
                                              function DOMAIN_SEPARATOR() external view returns (bytes32);
                                              function PERMIT_TYPEHASH() external pure returns (bytes32);
                                              function nonces(address owner) external view returns (uint);
                                          
                                              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                                          }
                                          
                                          interface IERC20 {
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              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 (uint);
                                              function balanceOf(address owner) external view returns (uint);
                                              function allowance(address owner, address spender) external view returns (uint);
                                          
                                              function approve(address spender, uint value) external returns (bool);
                                              function transfer(address to, uint value) external returns (bool);
                                              function transferFrom(address from, address to, uint value) external returns (bool);
                                          }
                                          
                                          interface IUniswapV2Callee {
                                              function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                                          }
                                          
                                          contract UniswapV2ERC20 is IUniswapV2ERC20 {
                                              using SafeMath for uint;
                                          
                                              string public constant name = 'Uniswap V2';
                                              string public constant symbol = 'UNI-V2';
                                              uint8 public constant decimals = 18;
                                              uint  public totalSupply;
                                              mapping(address => uint) public balanceOf;
                                              mapping(address => mapping(address => uint)) public allowance;
                                          
                                              bytes32 public DOMAIN_SEPARATOR;
                                              // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                                              bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                              mapping(address => uint) public nonces;
                                          
                                              event Approval(address indexed owner, address indexed spender, uint value);
                                              event Transfer(address indexed from, address indexed to, uint value);
                                          
                                              constructor() public {
                                                  uint chainId;
                                                  assembly {
                                                      chainId := chainid
                                                  }
                                                  DOMAIN_SEPARATOR = keccak256(
                                                      abi.encode(
                                                          keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                                                          keccak256(bytes(name)),
                                                          keccak256(bytes('1')),
                                                          chainId,
                                                          address(this)
                                                      )
                                                  );
                                              }
                                          
                                              function _mint(address to, uint value) internal {
                                                  totalSupply = totalSupply.add(value);
                                                  balanceOf[to] = balanceOf[to].add(value);
                                                  emit Transfer(address(0), to, value);
                                              }
                                          
                                              function _burn(address from, uint value) internal {
                                                  balanceOf[from] = balanceOf[from].sub(value);
                                                  totalSupply = totalSupply.sub(value);
                                                  emit Transfer(from, address(0), value);
                                              }
                                          
                                              function _approve(address owner, address spender, uint value) private {
                                                  allowance[owner][spender] = value;
                                                  emit Approval(owner, spender, value);
                                              }
                                          
                                              function _transfer(address from, address to, uint value) private {
                                                  balanceOf[from] = balanceOf[from].sub(value);
                                                  balanceOf[to] = balanceOf[to].add(value);
                                                  emit Transfer(from, to, value);
                                              }
                                          
                                              function approve(address spender, uint value) external returns (bool) {
                                                  _approve(msg.sender, spender, value);
                                                  return true;
                                              }
                                          
                                              function transfer(address to, uint value) external returns (bool) {
                                                  _transfer(msg.sender, to, value);
                                                  return true;
                                              }
                                          
                                              function transferFrom(address from, address to, uint value) external returns (bool) {
                                                  if (allowance[from][msg.sender] != uint(-1)) {
                                                      allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                                  }
                                                  _transfer(from, to, value);
                                                  return true;
                                              }
                                          
                                              function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                                                  require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                                                  bytes32 digest = keccak256(
                                                      abi.encodePacked(
                                                          '\x19\x01',
                                                          DOMAIN_SEPARATOR,
                                                          keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                                      )
                                                  );
                                                  address recoveredAddress = ecrecover(digest, v, r, s);
                                                  require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                                                  _approve(owner, spender, value);
                                              }
                                          }
                                          
                                          contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
                                              using SafeMath  for uint;
                                              using UQ112x112 for uint224;
                                          
                                              uint public constant MINIMUM_LIQUIDITY = 10**3;
                                              bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
                                          
                                              address public factory;
                                              address public token0;
                                              address public token1;
                                          
                                              uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                                              uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                                              uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
                                          
                                              uint public price0CumulativeLast;
                                              uint public price1CumulativeLast;
                                              uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                                          
                                              uint private unlocked = 1;
                                              modifier lock() {
                                                  require(unlocked == 1, 'UniswapV2: LOCKED');
                                                  unlocked = 0;
                                                  _;
                                                  unlocked = 1;
                                              }
                                          
                                              function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                                                  _reserve0 = reserve0;
                                                  _reserve1 = reserve1;
                                                  _blockTimestampLast = blockTimestampLast;
                                              }
                                          
                                              function _safeTransfer(address token, address to, uint value) private {
                                                  (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                                                  require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                                              }
                                          
                                              event Mint(address indexed sender, uint amount0, uint amount1);
                                              event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                                              event Swap(
                                                  address indexed sender,
                                                  uint amount0In,
                                                  uint amount1In,
                                                  uint amount0Out,
                                                  uint amount1Out,
                                                  address indexed to
                                              );
                                              event Sync(uint112 reserve0, uint112 reserve1);
                                          
                                              constructor() public {
                                                  factory = msg.sender;
                                              }
                                          
                                              // called once by the factory at time of deployment
                                              function initialize(address _token0, address _token1) external {
                                                  require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                                                  token0 = _token0;
                                                  token1 = _token1;
                                              }
                                          
                                              // update reserves and, on the first call per block, price accumulators
                                              function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                                                  require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                                                  uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                                                  uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                                                  if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                                                      // * never overflows, and + overflow is desired
                                                      price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                                                      price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                                                  }
                                                  reserve0 = uint112(balance0);
                                                  reserve1 = uint112(balance1);
                                                  blockTimestampLast = blockTimestamp;
                                                  emit Sync(reserve0, reserve1);
                                              }
                                          
                                              // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                                              function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                                                  address feeTo = IUniswapV2Factory(factory).feeTo();
                                                  feeOn = feeTo != address(0);
                                                  uint _kLast = kLast; // gas savings
                                                  if (feeOn) {
                                                      if (_kLast != 0) {
                                                          uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                                                          uint rootKLast = Math.sqrt(_kLast);
                                                          if (rootK > rootKLast) {
                                                              uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                                              uint denominator = rootK.mul(5).add(rootKLast);
                                                              uint liquidity = numerator / denominator;
                                                              if (liquidity > 0) _mint(feeTo, liquidity);
                                                          }
                                                      }
                                                  } else if (_kLast != 0) {
                                                      kLast = 0;
                                                  }
                                              }
                                          
                                              // this low-level function should be called from a contract which performs important safety checks
                                              function mint(address to) external lock returns (uint liquidity) {
                                                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                                  uint balance0 = IERC20(token0).balanceOf(address(this));
                                                  uint balance1 = IERC20(token1).balanceOf(address(this));
                                                  uint amount0 = balance0.sub(_reserve0);
                                                  uint amount1 = balance1.sub(_reserve1);
                                          
                                                  bool feeOn = _mintFee(_reserve0, _reserve1);
                                                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                                  if (_totalSupply == 0) {
                                                      liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                                                     _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                                                  } else {
                                                      liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                                                  }
                                                  require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                                                  _mint(to, liquidity);
                                          
                                                  _update(balance0, balance1, _reserve0, _reserve1);
                                                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                                  emit Mint(msg.sender, amount0, amount1);
                                              }
                                          
                                              // this low-level function should be called from a contract which performs important safety checks
                                              function burn(address to) external lock returns (uint amount0, uint amount1) {
                                                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                                  address _token0 = token0;                                // gas savings
                                                  address _token1 = token1;                                // gas savings
                                                  uint balance0 = IERC20(_token0).balanceOf(address(this));
                                                  uint balance1 = IERC20(_token1).balanceOf(address(this));
                                                  uint liquidity = balanceOf[address(this)];
                                          
                                                  bool feeOn = _mintFee(_reserve0, _reserve1);
                                                  uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                                  amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                                                  amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                                                  require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                                                  _burn(address(this), liquidity);
                                                  _safeTransfer(_token0, to, amount0);
                                                  _safeTransfer(_token1, to, amount1);
                                                  balance0 = IERC20(_token0).balanceOf(address(this));
                                                  balance1 = IERC20(_token1).balanceOf(address(this));
                                          
                                                  _update(balance0, balance1, _reserve0, _reserve1);
                                                  if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                                  emit Burn(msg.sender, amount0, amount1, to);
                                              }
                                          
                                              // this low-level function should be called from a contract which performs important safety checks
                                              function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                                                  require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                                                  (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                                  require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
                                          
                                                  uint balance0;
                                                  uint balance1;
                                                  { // scope for _token{0,1}, avoids stack too deep errors
                                                  address _token0 = token0;
                                                  address _token1 = token1;
                                                  require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                                                  if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                                                  if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                                                  if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                                                  balance0 = IERC20(_token0).balanceOf(address(this));
                                                  balance1 = IERC20(_token1).balanceOf(address(this));
                                                  }
                                                  uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                                                  uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                                                  require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                                                  { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                                                  uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                                                  uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                                                  require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                                                  }
                                          
                                                  _update(balance0, balance1, _reserve0, _reserve1);
                                                  emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                                              }
                                          
                                              // force balances to match reserves
                                              function skim(address to) external lock {
                                                  address _token0 = token0; // gas savings
                                                  address _token1 = token1; // gas savings
                                                  _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                                                  _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
                                              }
                                          
                                              // force reserves to match balances
                                              function sync() external lock {
                                                  _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
                                              }
                                          }
                                          
                                          contract UniswapV2Factory is IUniswapV2Factory {
                                              address public feeTo;
                                              address public feeToSetter;
                                          
                                              mapping(address => mapping(address => address)) public getPair;
                                              address[] public allPairs;
                                          
                                              event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                                          
                                              constructor(address _feeToSetter) public {
                                                  feeToSetter = _feeToSetter;
                                              }
                                          
                                              function allPairsLength() external view returns (uint) {
                                                  return allPairs.length;
                                              }
                                          
                                              function createPair(address tokenA, address tokenB) external returns (address pair) {
                                                  require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
                                                  (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                                                  require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
                                                  require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
                                                  bytes memory bytecode = type(UniswapV2Pair).creationCode;
                                                  bytes32 salt = keccak256(abi.encodePacked(token0, token1));
                                                  assembly {
                                                      pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
                                                  }
                                                  IUniswapV2Pair(pair).initialize(token0, token1);
                                                  getPair[token0][token1] = pair;
                                                  getPair[token1][token0] = pair; // populate mapping in the reverse direction
                                                  allPairs.push(pair);
                                                  emit PairCreated(token0, token1, pair, allPairs.length);
                                              }
                                          
                                              function setFeeTo(address _feeTo) external {
                                                  require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
                                                  feeTo = _feeTo;
                                              }
                                          
                                              function setFeeToSetter(address _feeToSetter) external {
                                                  require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
                                                  feeToSetter = _feeToSetter;
                                              }
                                          }
                                          
                                          // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
                                          
                                          library SafeMath {
                                              function add(uint x, uint y) internal pure returns (uint z) {
                                                  require((z = x + y) >= x, 'ds-math-add-overflow');
                                              }
                                          
                                              function sub(uint x, uint y) internal pure returns (uint z) {
                                                  require((z = x - y) <= x, 'ds-math-sub-underflow');
                                              }
                                          
                                              function mul(uint x, uint y) internal pure returns (uint z) {
                                                  require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                                              }
                                          }
                                          
                                          // a library for performing various math operations
                                          
                                          library Math {
                                              function min(uint x, uint y) internal pure returns (uint z) {
                                                  z = x < y ? x : y;
                                              }
                                          
                                              // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                                              function sqrt(uint y) internal pure returns (uint z) {
                                                  if (y > 3) {
                                                      z = y;
                                                      uint x = y / 2 + 1;
                                                      while (x < z) {
                                                          z = x;
                                                          x = (y / x + x) / 2;
                                                      }
                                                  } else if (y != 0) {
                                                      z = 1;
                                                  }
                                              }
                                          }
                                          
                                          // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                                          
                                          // range: [0, 2**112 - 1]
                                          // resolution: 1 / 2**112
                                          
                                          library UQ112x112 {
                                              uint224 constant Q112 = 2**112;
                                          
                                              // encode a uint112 as a UQ112x112
                                              function encode(uint112 y) internal pure returns (uint224 z) {
                                                  z = uint224(y) * Q112; // never overflows
                                              }
                                          
                                              // divide a UQ112x112 by a uint112, returning a UQ112x112
                                              function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                                                  z = x / uint224(y);
                                              }
                                          }

                                          File 14 of 15: ChiSpender
                                          pragma solidity ^0.5.0;
                                          pragma experimental ABIEncoderV2;
                                          
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see {ERC20Detailed}.
                                           */
                                          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);
                                          }
                                          
                                          
                                          contract IChi is IERC20 {
                                              function freeUpTo(uint256 value) external returns (uint256 freed);
                                              function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
                                          }
                                          
                                          
                                          contract ChiSpender {
                                              IChi public constant chi = IChi(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c);
                                          
                                              address public owner = msg.sender;
                                          
                                              function burnChi(uint tokens) external returns(uint256) {
                                                  require(msg.sender == owner, "Access restricted");
                                                  return chi.freeFromUpTo(tx.origin, tokens);
                                              }
                                          }

                                          File 15 of 15: TokenSpender
                                          /**
                                           *Submitted for verification at Etherscan.io on 2019-09-28
                                          */
                                          
                                          pragma solidity ^0.5.0;
                                          pragma experimental ABIEncoderV2;
                                          
                                          
                                          library ExternalCall {
                                              // Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
                                              // call has been separated into its own function in order to take advantage
                                              // of the Solidity's code generator to produce a loop that copies tx.data into memory.
                                              function externalCall(address destination, uint value, bytes memory data, uint dataOffset, uint dataLength, uint gasLimit) internal returns(bool result) {
                                                  // solium-disable-next-line security/no-inline-assembly
                                                  if (gasLimit == 0) {
                                                      gasLimit = gasleft() - 40000;
                                                  }
                                                  assembly {
                                                      let x := mload(0x40)   // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
                                                      let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
                                                      result := call(
                                                          gasLimit,
                                                          destination,
                                                          value,
                                                          add(d, dataOffset),
                                                          dataLength,        // Size of the input (in bytes) - this is what fixes the padding problem
                                                          x,
                                                          0                  // Output is ignored, therefore the output size is zero
                                                      )
                                                  }
                                              }
                                          }
                                          
                                          
                                          /**
                                           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
                                           * the optional functions; to access them see `ERC20Detailed`.
                                           */
                                          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.
                                               *
                                               * > 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);
                                          }
                                          
                                          
                                          /**
                                           * @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, 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");
                                                  uint256 c = a - b;
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @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) {
                                                  // 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 0;
                                                  }
                                          
                                                  uint256 c = a * b;
                                                  require(c / a == b, "SafeMath: multiplication overflow");
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the integer division of two unsigned integers. Reverts 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) {
                                                  // Solidity only automatically asserts when dividing by 0
                                                  require(b > 0, "SafeMath: division by zero");
                                                  uint256 c = a / b;
                                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                          
                                                  return c;
                                              }
                                          
                                              /**
                                               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                               * Reverts 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 Contract module which provides a basic access control mechanism, where
                                           * there is an account (an owner) that can be granted exclusive access to
                                           * specific functions.
                                           *
                                           * This module is used through inheritance. It will make available the modifier
                                           * `onlyOwner`, which can be aplied to your functions to restrict their use to
                                           * the owner.
                                           */
                                          contract Ownable {
                                              address private _owner;
                                          
                                              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                          
                                              /**
                                               * @dev Initializes the contract setting the deployer as the initial owner.
                                               */
                                              constructor () internal {
                                                  _owner = msg.sender;
                                                  emit OwnershipTransferred(address(0), _owner);
                                              }
                                          
                                              /**
                                               * @dev Returns the address of the current owner.
                                               */
                                              function owner() public view returns (address) {
                                                  return _owner;
                                              }
                                          
                                              /**
                                               * @dev Throws if called by any account other than the owner.
                                               */
                                              modifier onlyOwner() {
                                                  require(isOwner(), "Ownable: caller is not the owner");
                                                  _;
                                              }
                                          
                                              /**
                                               * @dev Returns true if the caller is the current owner.
                                               */
                                              function isOwner() public view returns (bool) {
                                                  return msg.sender == _owner;
                                              }
                                          
                                              /**
                                               * @dev Leaves the contract without owner. It will not be possible to call
                                               * `onlyOwner` functions anymore. Can only be called by the current owner.
                                               *
                                               * > Note: Renouncing ownership will leave the contract without an owner,
                                               * thereby removing any functionality that is only available to the owner.
                                               */
                                              function renounceOwnership() public onlyOwner {
                                                  emit OwnershipTransferred(_owner, address(0));
                                                  _owner = address(0);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               * Can only be called by the current owner.
                                               */
                                              function transferOwnership(address newOwner) public onlyOwner {
                                                  _transferOwnership(newOwner);
                                              }
                                          
                                              /**
                                               * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                               */
                                              function _transferOwnership(address newOwner) internal {
                                                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                                                  emit OwnershipTransferred(_owner, newOwner);
                                                  _owner = newOwner;
                                              }
                                          }
                                          
                                          contract IZrxExchange {
                                          
                                              struct Order {
                                                  address makerAddress;           // Address that created the order.
                                                  address takerAddress;           // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
                                                  address feeRecipientAddress;    // Address that will recieve fees when order is filled.
                                                  address senderAddress;          // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
                                                  uint256 makerAssetAmount;       // Amount of makerAsset being offered by maker. Must be greater than 0.
                                                  uint256 takerAssetAmount;       // Amount of takerAsset being bid on by maker. Must be greater than 0.
                                                  uint256 makerFee;               // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
                                                  uint256 takerFee;               // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
                                                  uint256 expirationTimeSeconds;  // Timestamp in seconds at which order expires.
                                                  uint256 salt;                   // Arbitrary number to facilitate uniqueness of the order's hash.
                                                  bytes makerAssetData;           // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
                                                  bytes takerAssetData;           // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
                                              }
                                          
                                              struct OrderInfo {
                                                  uint8 orderStatus;                    // Status that describes order's validity and fillability.
                                                  bytes32 orderHash;                    // EIP712 hash of the order (see IZrxExchange.getOrderHash).
                                                  uint256 orderTakerAssetFilledAmount;  // Amount of order that has already been filled.
                                              }
                                          
                                              struct FillResults {
                                                  uint256 makerAssetFilledAmount;  // Total amount of makerAsset(s) filled.
                                                  uint256 takerAssetFilledAmount;  // Total amount of takerAsset(s) filled.
                                                  uint256 makerFeePaid;            // Total amount of ZRX paid by maker(s) to feeRecipient(s).
                                                  uint256 takerFeePaid;            // Total amount of ZRX paid by taker to feeRecipients(s).
                                              }
                                          
                                              function getOrderInfo(Order memory order)
                                                  public
                                                  view
                                                  returns (OrderInfo memory orderInfo);
                                          
                                              function getOrdersInfo(Order[] memory orders)
                                                  public
                                                  view
                                                  returns (OrderInfo[] memory ordersInfo);
                                          
                                              function fillOrder(
                                                  Order memory order,
                                                  uint256 takerAssetFillAmount,
                                                  bytes memory signature
                                              )
                                                  public
                                                  returns (FillResults memory fillResults);
                                          
                                              function fillOrderNoThrow(
                                                  Order memory order,
                                                  uint256 takerAssetFillAmount,
                                                  bytes memory signature
                                              )
                                                  public
                                                  returns (FillResults memory fillResults);
                                          }
                                          
                                          
                                          contract IGST2 is IERC20 {
                                          
                                              function freeUpTo(uint256 value) external returns (uint256 freed);
                                          
                                              function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
                                          
                                              function balanceOf(address who) external view returns (uint256);
                                          }
                                          
                                          
                                          /**
                                           * @dev Collection of functions related to the address type,
                                           */
                                          library Address {
                                              /**
                                               * @dev Returns true if `account` is a contract.
                                               *
                                               * This test is non-exhaustive, and there may be false-negatives: during the
                                               * execution of a contract's constructor, its address will be reported as
                                               * not containing a contract.
                                               *
                                               * > It is unsafe to assume that an address for which this function returns
                                               * false is an externally-owned account (EOA) and not a contract.
                                               */
                                              function isContract(address account) internal view returns (bool) {
                                                  // This method relies in 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;
                                              }
                                          }
                                          
                                          
                                          
                                          contract IWETH is IERC20 {
                                          
                                              function deposit() external payable;
                                          
                                              function withdraw(uint256 amount) external;
                                          }
                                          
                                          
                                          
                                          contract Shutdownable is Ownable {
                                          
                                              bool public isShutdown;
                                          
                                              event Shutdown();
                                          
                                              modifier notShutdown {
                                                  require(!isShutdown, "Smart contract is shut down.");
                                                  _;
                                              }
                                          
                                              function shutdown() public onlyOwner {
                                                  isShutdown = true;
                                                  emit Shutdown();
                                              }
                                          }
                                          
                                          contract IERC20NonView {
                                              // Methods are not view to avoid throw on proxy tokens with delegatecall inside
                                              function balanceOf(address user) public returns(uint256);
                                              function allowance(address from, address to) public returns(uint256);
                                          }
                                          
                                          contract ZrxMarketOrder {
                                          
                                              using SafeMath for uint256;
                                          
                                              function marketSellOrdersProportion(
                                                  IERC20 tokenSell,
                                                  address tokenBuy,
                                                  address zrxExchange,
                                                  address zrxTokenProxy,
                                                  IZrxExchange.Order[] calldata orders,
                                                  bytes[] calldata signatures,
                                                  uint256 mul,
                                                  uint256 div
                                              )
                                                  external
                                              {
                                                  uint256 amount = tokenSell.balanceOf(msg.sender).mul(mul).div(div);
                                                  this.marketSellOrders(tokenBuy, zrxExchange, zrxTokenProxy, amount, orders, signatures);
                                              }
                                          
                                              function marketSellOrders(
                                                  address makerAsset,
                                                  address zrxExchange,
                                                  address zrxTokenProxy,
                                                  uint256 takerAssetFillAmount,
                                                  IZrxExchange.Order[] calldata orders,
                                                  bytes[] calldata signatures
                                              )
                                                  external
                                                  returns (IZrxExchange.FillResults memory totalFillResults)
                                              {
                                                  for (uint i = 0; i < orders.length; i++) {
                                          
                                                      // Stop execution if the entire amount of takerAsset has been sold
                                                      if (totalFillResults.takerAssetFilledAmount >= takerAssetFillAmount) {
                                                          break;
                                                      }
                                          
                                                      // Calculate the remaining amount of takerAsset to sell
                                                      uint256 remainingTakerAmount = takerAssetFillAmount.sub(totalFillResults.takerAssetFilledAmount);
                                          
                                                      IZrxExchange.OrderInfo memory orderInfo = IZrxExchange(zrxExchange).getOrderInfo(orders[i]);
                                                      uint256 orderRemainingTakerAmount = orders[i].takerAssetAmount.sub(orderInfo.orderTakerAssetFilledAmount);
                                          
                                                      // Check available balance and allowance and update orderRemainingTakerAmount
                                                      {
                                                          uint256 balance = IERC20NonView(makerAsset).balanceOf(orders[i].makerAddress);
                                                          uint256 allowance = IERC20NonView(makerAsset).allowance(orders[i].makerAddress, zrxTokenProxy);
                                                          uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
                                                          uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
                                          
                                                          if (availableTakerAmount < orderRemainingTakerAmount) {
                                                              orderRemainingTakerAmount = availableTakerAmount;
                                                          }
                                                      }
                                          
                                                      uint256 takerAmount = (orderRemainingTakerAmount < remainingTakerAmount) ? orderRemainingTakerAmount : remainingTakerAmount;
                                          
                                                      IZrxExchange.FillResults memory fillResults = IZrxExchange(zrxExchange).fillOrderNoThrow(
                                                          orders[i],
                                                          takerAmount,
                                                          signatures[i]
                                                      );
                                          
                                                      _addFillResults(totalFillResults, fillResults);
                                                  }
                                          
                                                  return totalFillResults;
                                              }
                                          
                                              function _addFillResults(
                                                  IZrxExchange.FillResults memory totalFillResults,
                                                  IZrxExchange.FillResults memory singleFillResults
                                              )
                                                  internal
                                                  pure
                                              {
                                                  totalFillResults.makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount.add(singleFillResults.makerAssetFilledAmount);
                                                  totalFillResults.takerAssetFilledAmount = totalFillResults.takerAssetFilledAmount.add(singleFillResults.takerAssetFilledAmount);
                                                  totalFillResults.makerFeePaid = totalFillResults.makerFeePaid.add(singleFillResults.makerFeePaid);
                                                  totalFillResults.takerFeePaid = totalFillResults.takerFeePaid.add(singleFillResults.takerFeePaid);
                                              }
                                          
                                              function getOrdersInfoRespectingBalancesAndAllowances(
                                                  IERC20 token,
                                                  IZrxExchange zrx,
                                                  address zrxTokenProxy,
                                                  IZrxExchange.Order[] memory orders
                                              )
                                                  public
                                                  view
                                                  returns (IZrxExchange.OrderInfo[] memory ordersInfo)
                                              {
                                                  ordersInfo = zrx.getOrdersInfo(orders);
                                          
                                                  for (uint i = 0; i < ordersInfo.length; i++) {
                                          
                                                      uint256 balance = token.balanceOf(orders[i].makerAddress);
                                                      uint256 allowance = token.allowance(orders[i].makerAddress, zrxTokenProxy);
                                                      uint256 availableMakerAmount = (allowance < balance) ? allowance : balance;
                                                      uint256 availableTakerAmount = availableMakerAmount.mul(orders[i].takerAssetAmount).div(orders[i].makerAssetAmount);
                                          
                                                      for (uint j = 0; j < i; j++) {
                                          
                                                          if (orders[j].makerAddress == orders[i].makerAddress) {
                                          
                                                              uint256 orderTakerAssetRemainigAmount = orders[j].takerAssetAmount.sub(
                                                                  ordersInfo[j].orderTakerAssetFilledAmount
                                                              );
                                          
                                                              if (availableTakerAmount > orderTakerAssetRemainigAmount) {
                                          
                                                                  availableTakerAmount = availableTakerAmount.sub(orderTakerAssetRemainigAmount);
                                                              } else {
                                          
                                                                  availableTakerAmount = 0;
                                                                  break;
                                                              }
                                                          }
                                                      }
                                          
                                                      uint256 remainingTakerAmount = orders[i].takerAssetAmount.sub(
                                                          ordersInfo[i].orderTakerAssetFilledAmount
                                                      );
                                          
                                                      if (availableTakerAmount < remainingTakerAmount) {
                                          
                                                          ordersInfo[i].orderTakerAssetFilledAmount = orders[i].takerAssetAmount.sub(availableTakerAmount);
                                                      }
                                                  }
                                              }
                                          }
                                          
                                          
                                          
                                          
                                          /**
                                           * @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 ERC20;` 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));
                                              }
                                          
                                              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);
                                                  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.
                                          
                                                  // A Solidity high level call has three parts:
                                                  //  1. The target address is checked to verify it contains contract code
                                                  //  2. The call itself is made, and success asserted
                                                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                                                  // solhint-disable-next-line max-line-length
                                                  require(address(token).isContract(), "SafeERC20: call to non-contract");
                                          
                                                  // solhint-disable-next-line avoid-low-level-calls
                                                  (bool success, bytes memory returndata) = address(token).call(data);
                                                  require(success, "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");
                                                  }
                                              }
                                          }
                                          
                                          
                                          
                                          
                                          
                                          library UniversalERC20 {
                                          
                                              using SafeMath for uint256;
                                              using SafeERC20 for IERC20;
                                          
                                              IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
                                              IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount) internal {
                                                  universalTransfer(token, to, amount, false);
                                              }
                                          
                                              function universalTransfer(IERC20 token, address to, uint256 amount, bool mayFail) internal returns(bool) {
                                                  if (amount == 0) {
                                                      return true;
                                                  }
                                          
                                                  if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
                                                      if (mayFail) {
                                                          return address(uint160(to)).send(amount);
                                                      } else {
                                                          address(uint160(to)).transfer(amount);
                                                          return true;
                                                      }
                                                  } else {
                                                      token.safeTransfer(to, amount);
                                                      return true;
                                                  }
                                              }
                                          
                                              function universalApprove(IERC20 token, address to, uint256 amount) internal {
                                                  if (token != ZERO_ADDRESS && token != ETH_ADDRESS) {
                                                      token.safeApprove(to, amount);
                                                  }
                                              }
                                          
                                              function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                                                  if (amount == 0) {
                                                      return;
                                                  }
                                          
                                                  if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
                                                      require(from == msg.sender && msg.value >= amount, "msg.value is zero");
                                                      if (to != address(this)) {
                                                          address(uint160(to)).transfer(amount);
                                                      }
                                                      if (msg.value > amount) {
                                                          msg.sender.transfer(msg.value.sub(amount));
                                                      }
                                                  } else {
                                                      token.safeTransferFrom(from, to, amount);
                                                  }
                                              }
                                          
                                              function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
                                                  if (token == ZERO_ADDRESS || token == ETH_ADDRESS) {
                                                      return who.balance;
                                                  } else {
                                                      return token.balanceOf(who);
                                                  }
                                              }
                                          }
                                          
                                          
                                          
                                          contract TokenSpender {
                                          
                                              using SafeERC20 for IERC20;
                                          
                                              address public owner;
                                              IGST2 public gasToken;
                                              address public gasTokenOwner;
                                          
                                              constructor(IGST2 _gasToken, address _gasTokenOwner) public {
                                                  owner = msg.sender;
                                                  gasToken = _gasToken;
                                                  gasTokenOwner = _gasTokenOwner;
                                              }
                                          
                                              function claimTokens(IERC20 token, address who, address dest, uint256 amount) external {
                                                  require(msg.sender == owner, "Access restricted");
                                                  token.safeTransferFrom(who, dest, amount);
                                              }
                                          
                                              function burnGasToken(uint gasSpent) external {
                                                  require(msg.sender == owner, "Access restricted");
                                                  uint256 tokens = (gasSpent + 14154) / 41130;
                                                  gasToken.freeUpTo(tokens);
                                              }
                                          
                                              function() external {
                                                  if (msg.sender == gasTokenOwner) {
                                                      gasToken.transfer(msg.sender, gasToken.balanceOf(address(this)));
                                                  }
                                              }
                                          }