ETH Price: $2,491.66 (-2.82%)

Transaction Decoder

Block:
9610685 at Mar-05-2020 10:29:30 AM +UTC
Transaction Fee:
0.000702345 ETH $1.75
Gas Used:
140,469 Gas / 5 Gwei

Emitted Events:

114 ProxyERC20.Transfer( from=[Receiver] Vyper_contract, to=[Sender] 0xd1898665a01a91ac10bd2c6cb1899336df34ac33, value=103111089804123130 )
115 Vyper_contract.TokenPurchase( buyer=[Sender] 0xd1898665a01a91ac10bd2c6cb1899336df34ac33, eth_sold=100000000000000000, tokens_bought=103111089804123130 )

Account State Difference:

  Address   Before After State Difference Code
0x34A5ef81...f4c79031c
(Synthetix: Token State sETH)
(Spark Pool)
83.938424254601946776 Eth83.939126599601946776 Eth0.000702345
0x9f71b659...D6e2c211C
0xD1898665...6df34AC33
0.225739747272451446 Eth
Nonce: 212
0.125037402272451446 Eth
Nonce: 213
0.100702345
0xe9Cf7887...16438F244 36,486.259447847702015146 Eth36,486.359447847702015146 Eth0.1

Execution Trace

ETH 0.1 Vyper_contract.ethToTokenSwapInput( min_tokens=102595534355102515, deadline=1583405033 ) => ( out=103111089804123130 )
  • ETH 0.1 Vyper_contract.ethToTokenSwapInput( min_tokens=102595534355102515, deadline=1583405033 ) => ( out=103111089804123130 )
    • ProxyERC20.balanceOf( owner=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244 ) => ( 37734686607013178530001 )
      • MultiCollateralSynth.balanceOf( account=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244 ) => ( 37734686607013178530001 )
        • TokenState.balanceOf( 0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244 ) => ( 37734686607013178530001 )
        • ProxyERC20.transfer( to=0xD1898665a01A91AC10bD2C6cb1899336df34AC33, value=103111089804123130 ) => ( True )
          • MultiCollateralSynth.setMessageSender( sender=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244 )
          • MultiCollateralSynth.transfer( to=0xD1898665a01A91AC10bD2C6cb1899336df34AC33, value=103111089804123130 ) => ( True )
            • AddressResolver.requireAndGetAddress( name=45786368616E6765720000000000000000000000000000000000000000000000, reason=Missing Exchanger address ) => ( 0x6289fd70d3Dce8DE61896959cdEfcFF3cE46A108 )
            • Exchanger.maxSecsLeftInWaitingPeriod( account=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244, currencyKey=7345544800000000000000000000000000000000000000000000000000000000 ) => ( 0 )
              • AddressResolver.requireAndGetAddress( name=45786368616E6765537461746500000000000000000000000000000000000000, reason=Missing ExchangeState address ) => ( 0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 )
              • ExchangeState.getMaxTimestamp( account=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244, currencyKey=7345544800000000000000000000000000000000000000000000000000000000 ) => ( 0 )
              • AddressResolver.requireAndGetAddress( name=45786368616E6765720000000000000000000000000000000000000000000000, reason=Missing Exchanger address ) => ( 0x6289fd70d3Dce8DE61896959cdEfcFF3cE46A108 )
              • Exchanger.settlementOwing( account=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244, currencyKey=7345544800000000000000000000000000000000000000000000000000000000 ) => ( reclaimAmount=0, rebateAmount=0 )
                • AddressResolver.requireAndGetAddress( name=45786368616E6765537461746500000000000000000000000000000000000000, reason=Missing ExchangeState address ) => ( 0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 )
                • ExchangeState.getLengthOfEntries( account=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244, currencyKey=7345544800000000000000000000000000000000000000000000000000000000 ) => ( 0 )
                • TokenState.balanceOf( 0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244 ) => ( 37734686607013178530001 )
                • TokenState.balanceOf( 0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244 ) => ( 37734686607013178530001 )
                • TokenState.setBalanceOf( account=0xe9Cf7887b93150D4F2Da7dFc6D502B216438F244, value=37734583495923374406871 )
                • TokenState.balanceOf( 0xD1898665a01A91AC10bD2C6cb1899336df34AC33 ) => ( 0 )
                • TokenState.setBalanceOf( account=0xD1898665a01A91AC10bD2C6cb1899336df34AC33, value=103111089804123130 )
                • ProxyERC20._emit( callData=0x000000000000000000000000000000000000000000000000016E52FD682D9BFA, numTopics=3, topic1=DDF252AD1BE2C89B69C2B068FC378DAA952BA7F163C4A11628F55A4DF523B3EF, topic2=000000000000000000000000E9CF7887B93150D4F2DA7DFC6D502B216438F244, topic3=000000000000000000000000D1898665A01A91AC10BD2C6CB1899336DF34AC33, topic4=0000000000000000000000000000000000000000000000000000000000000000 )
                  File 1 of 8: Vyper_contract
                  # @title Uniswap Exchange Interface V1
                  # @notice Source code found at https://github.com/uniswap
                  # @notice Use at your own risk
                  
                  contract Factory():
                      def getExchange(token_addr: address) -> address: constant
                  
                  contract Exchange():
                      def getEthToTokenOutputPrice(tokens_bought: uint256) -> uint256(wei): constant
                      def ethToTokenTransferInput(min_tokens: uint256, deadline: timestamp, recipient: address) -> uint256: modifying
                      def ethToTokenTransferOutput(tokens_bought: uint256, deadline: timestamp, recipient: address) -> uint256(wei): modifying
                  
                  TokenPurchase: event({buyer: indexed(address), eth_sold: indexed(uint256(wei)), tokens_bought: indexed(uint256)})
                  EthPurchase: event({buyer: indexed(address), tokens_sold: indexed(uint256), eth_bought: indexed(uint256(wei))})
                  AddLiquidity: event({provider: indexed(address), eth_amount: indexed(uint256(wei)), token_amount: indexed(uint256)})
                  RemoveLiquidity: event({provider: indexed(address), eth_amount: indexed(uint256(wei)), token_amount: indexed(uint256)})
                  Transfer: event({_from: indexed(address), _to: indexed(address), _value: uint256})
                  Approval: event({_owner: indexed(address), _spender: indexed(address), _value: uint256})
                  
                  name: public(bytes32)                             # Uniswap V1
                  symbol: public(bytes32)                           # UNI-V1
                  decimals: public(uint256)                         # 18
                  totalSupply: public(uint256)                      # total number of UNI in existence
                  balances: uint256[address]                        # UNI balance of an address
                  allowances: (uint256[address])[address]           # UNI allowance of one address on another
                  token: address(ERC20)                             # address of the ERC20 token traded on this contract
                  factory: Factory                                  # interface for the factory that created this contract
                  
                  # @dev This function acts as a contract constructor which is not currently supported in contracts deployed
                  #      using create_with_code_of(). It is called once by the factory during contract creation.
                  @public
                  def setup(token_addr: address):
                      assert (self.factory == ZERO_ADDRESS and self.token == ZERO_ADDRESS) and token_addr != ZERO_ADDRESS
                      self.factory = msg.sender
                      self.token = token_addr
                      self.name = 0x556e697377617020563100000000000000000000000000000000000000000000
                      self.symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000
                      self.decimals = 18
                  
                  # @notice Deposit ETH and Tokens (self.token) at current ratio to mint UNI tokens.
                  # @dev min_liquidity does nothing when total UNI supply is 0.
                  # @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0.
                  # @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return The amount of UNI minted.
                  @public
                  @payable
                  def addLiquidity(min_liquidity: uint256, max_tokens: uint256, deadline: timestamp) -> uint256:
                      assert deadline > block.timestamp and (max_tokens > 0 and msg.value > 0)
                      total_liquidity: uint256 = self.totalSupply
                      if total_liquidity > 0:
                          assert min_liquidity > 0
                          eth_reserve: uint256(wei) = self.balance - msg.value
                          token_reserve: uint256 = self.token.balanceOf(self)
                          token_amount: uint256 = msg.value * token_reserve / eth_reserve + 1
                          liquidity_minted: uint256 = msg.value * total_liquidity / eth_reserve
                          assert max_tokens >= token_amount and liquidity_minted >= min_liquidity
                          self.balances[msg.sender] += liquidity_minted
                          self.totalSupply = total_liquidity + liquidity_minted
                          assert self.token.transferFrom(msg.sender, self, token_amount)
                          log.AddLiquidity(msg.sender, msg.value, token_amount)
                          log.Transfer(ZERO_ADDRESS, msg.sender, liquidity_minted)
                          return liquidity_minted
                      else:
                          assert (self.factory != ZERO_ADDRESS and self.token != ZERO_ADDRESS) and msg.value >= 1000000000
                          assert self.factory.getExchange(self.token) == self
                          token_amount: uint256 = max_tokens
                          initial_liquidity: uint256 = as_unitless_number(self.balance)
                          self.totalSupply = initial_liquidity
                          self.balances[msg.sender] = initial_liquidity
                          assert self.token.transferFrom(msg.sender, self, token_amount)
                          log.AddLiquidity(msg.sender, msg.value, token_amount)
                          log.Transfer(ZERO_ADDRESS, msg.sender, initial_liquidity)
                          return initial_liquidity
                  
                  # @dev Burn UNI tokens to withdraw ETH and Tokens at current ratio.
                  # @param amount Amount of UNI burned.
                  # @param min_eth Minimum ETH withdrawn.
                  # @param min_tokens Minimum Tokens withdrawn.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return The amount of ETH and Tokens withdrawn.
                  @public
                  def removeLiquidity(amount: uint256, min_eth: uint256(wei), min_tokens: uint256, deadline: timestamp) -> (uint256(wei), uint256):
                      assert (amount > 0 and deadline > block.timestamp) and (min_eth > 0 and min_tokens > 0)
                      total_liquidity: uint256 = self.totalSupply
                      assert total_liquidity > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_amount: uint256(wei) = amount * self.balance / total_liquidity
                      token_amount: uint256 = amount * token_reserve / total_liquidity
                      assert eth_amount >= min_eth and token_amount >= min_tokens
                      self.balances[msg.sender] -= amount
                      self.totalSupply = total_liquidity - amount
                      send(msg.sender, eth_amount)
                      assert self.token.transfer(msg.sender, token_amount)
                      log.RemoveLiquidity(msg.sender, eth_amount, token_amount)
                      log.Transfer(msg.sender, ZERO_ADDRESS, amount)
                      return eth_amount, token_amount
                  
                  # @dev Pricing function for converting between ETH and Tokens.
                  # @param input_amount Amount of ETH or Tokens being sold.
                  # @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves.
                  # @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves.
                  # @return Amount of ETH or Tokens bought.
                  @private
                  @constant
                  def getInputPrice(input_amount: uint256, input_reserve: uint256, output_reserve: uint256) -> uint256:
                      assert input_reserve > 0 and output_reserve > 0
                      input_amount_with_fee: uint256 = input_amount * 997
                      numerator: uint256 = input_amount_with_fee * output_reserve
                      denominator: uint256 = (input_reserve * 1000) + input_amount_with_fee
                      return numerator / denominator
                  
                  # @dev Pricing function for converting between ETH and Tokens.
                  # @param output_amount Amount of ETH or Tokens being bought.
                  # @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves.
                  # @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves.
                  # @return Amount of ETH or Tokens sold.
                  @private
                  @constant
                  def getOutputPrice(output_amount: uint256, input_reserve: uint256, output_reserve: uint256) -> uint256:
                      assert input_reserve > 0 and output_reserve > 0
                      numerator: uint256 = input_reserve * output_amount * 1000
                      denominator: uint256 = (output_reserve - output_amount) * 997
                      return numerator / denominator + 1
                  
                  @private
                  def ethToTokenInput(eth_sold: uint256(wei), min_tokens: uint256, deadline: timestamp, buyer: address, recipient: address) -> uint256:
                      assert deadline >= block.timestamp and (eth_sold > 0 and min_tokens > 0)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      tokens_bought: uint256 = self.getInputPrice(as_unitless_number(eth_sold), as_unitless_number(self.balance - eth_sold), token_reserve)
                      assert tokens_bought >= min_tokens
                      assert self.token.transfer(recipient, tokens_bought)
                      log.TokenPurchase(buyer, eth_sold, tokens_bought)
                      return tokens_bought
                  
                  # @notice Convert ETH to Tokens.
                  # @dev User specifies exact input (msg.value).
                  # @dev User cannot specify minimum output or deadline.
                  @public
                  @payable
                  def __default__():
                      self.ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender)
                  
                  # @notice Convert ETH to Tokens.
                  # @dev User specifies exact input (msg.value) and minimum output.
                  # @param min_tokens Minimum Tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of Tokens bought.
                  @public
                  @payable
                  def ethToTokenSwapInput(min_tokens: uint256, deadline: timestamp) -> uint256:
                      return self.ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert ETH to Tokens and transfers Tokens to recipient.
                  # @dev User specifies exact input (msg.value) and minimum output
                  # @param min_tokens Minimum Tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output Tokens.
                  # @return Amount of Tokens bought.
                  @public
                  @payable
                  def ethToTokenTransferInput(min_tokens: uint256, deadline: timestamp, recipient: address) -> uint256:
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient)
                  
                  @private
                  def ethToTokenOutput(tokens_bought: uint256, max_eth: uint256(wei), deadline: timestamp, buyer: address, recipient: address) -> uint256(wei):
                      assert deadline >= block.timestamp and (tokens_bought > 0 and max_eth > 0)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_sold: uint256 = self.getOutputPrice(tokens_bought, as_unitless_number(self.balance - max_eth), token_reserve)
                      # Throws if eth_sold > max_eth
                      eth_refund: uint256(wei) = max_eth - as_wei_value(eth_sold, 'wei')
                      if eth_refund > 0:
                          send(buyer, eth_refund)
                      assert self.token.transfer(recipient, tokens_bought)
                      log.TokenPurchase(buyer, as_wei_value(eth_sold, 'wei'), tokens_bought)
                      return as_wei_value(eth_sold, 'wei')
                  
                  # @notice Convert ETH to Tokens.
                  # @dev User specifies maximum input (msg.value) and exact output.
                  # @param tokens_bought Amount of tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of ETH sold.
                  @public
                  @payable
                  def ethToTokenSwapOutput(tokens_bought: uint256, deadline: timestamp) -> uint256(wei):
                      return self.ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert ETH to Tokens and transfers Tokens to recipient.
                  # @dev User specifies maximum input (msg.value) and exact output.
                  # @param tokens_bought Amount of tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output Tokens.
                  # @return Amount of ETH sold.
                  @public
                  @payable
                  def ethToTokenTransferOutput(tokens_bought: uint256, deadline: timestamp, recipient: address) -> uint256(wei):
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient)
                  
                  @private
                  def tokenToEthInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp, buyer: address, recipient: address) -> uint256(wei):
                      assert deadline >= block.timestamp and (tokens_sold > 0 and min_eth > 0)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
                      wei_bought: uint256(wei) = as_wei_value(eth_bought, 'wei')
                      assert wei_bought >= min_eth
                      send(recipient, wei_bought)
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      log.EthPurchase(buyer, tokens_sold, wei_bought)
                      return wei_bought
                  
                  
                  # @notice Convert Tokens to ETH.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_eth Minimum ETH purchased.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of ETH bought.
                  @public
                  def tokenToEthSwapInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp) -> uint256(wei):
                      return self.tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert Tokens to ETH and transfers ETH to recipient.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_eth Minimum ETH purchased.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @return Amount of ETH bought.
                  @public
                  def tokenToEthTransferInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp, recipient: address) -> uint256(wei):
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient)
                  
                  @private
                  def tokenToEthOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp, buyer: address, recipient: address) -> uint256:
                      assert deadline >= block.timestamp and eth_bought > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      tokens_sold: uint256 = self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
                      # tokens sold is always > 0
                      assert max_tokens >= tokens_sold
                      send(recipient, eth_bought)
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      log.EthPurchase(buyer, tokens_sold, eth_bought)
                      return tokens_sold
                  
                  # @notice Convert Tokens to ETH.
                  # @dev User specifies maximum input and exact output.
                  # @param eth_bought Amount of ETH purchased.
                  # @param max_tokens Maximum Tokens sold.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of Tokens sold.
                  @public
                  def tokenToEthSwapOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp) -> uint256:
                      return self.tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert Tokens to ETH and transfers ETH to recipient.
                  # @dev User specifies maximum input and exact output.
                  # @param eth_bought Amount of ETH purchased.
                  # @param max_tokens Maximum Tokens sold.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @return Amount of Tokens sold.
                  @public
                  def tokenToEthTransferOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp, recipient: address) -> uint256:
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient)
                  
                  @private
                  def tokenToTokenInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, buyer: address, recipient: address, exchange_addr: address) -> uint256:
                      assert (deadline >= block.timestamp and tokens_sold > 0) and (min_tokens_bought > 0 and min_eth_bought > 0)
                      assert exchange_addr != self and exchange_addr != ZERO_ADDRESS
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
                      wei_bought: uint256(wei) = as_wei_value(eth_bought, 'wei')
                      assert wei_bought >= min_eth_bought
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      tokens_bought: uint256 = Exchange(exchange_addr).ethToTokenTransferInput(min_tokens_bought, deadline, recipient, value=wei_bought)
                      log.EthPurchase(buyer, tokens_sold, wei_bought)
                      return tokens_bought
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr).
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (token_addr) bought.
                  @public
                  def tokenToTokenSwapInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr) and transfers
                  #         Tokens (token_addr) to recipient.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (token_addr) bought.
                  @public
                  def tokenToTokenTransferInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, recipient: address, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr)
                  
                  @private
                  def tokenToTokenOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, buyer: address, recipient: address, exchange_addr: address) -> uint256:
                      assert deadline >= block.timestamp and (tokens_bought > 0 and max_eth_sold > 0)
                      assert exchange_addr != self and exchange_addr != ZERO_ADDRESS
                      eth_bought: uint256(wei) = Exchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      tokens_sold: uint256 = self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
                      # tokens sold is always > 0
                      assert max_tokens_sold >= tokens_sold and max_eth_sold >= eth_bought
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      eth_sold: uint256(wei) = Exchange(exchange_addr).ethToTokenTransferOutput(tokens_bought, deadline, recipient, value=eth_bought)
                      log.EthPurchase(buyer, tokens_sold, eth_bought)
                      return tokens_sold
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr).
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToTokenSwapOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr) and transfers
                  #         Tokens (token_addr) to recipient.
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToTokenTransferOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, recipient: address, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token).
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param exchange_addr The address of the exchange for the token being purchased.
                  # @return Amount of Tokens (exchange_addr.token) bought.
                  @public
                  def tokenToExchangeSwapInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, exchange_addr: address) -> uint256:
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token) and transfers
                  #         Tokens (exchange_addr.token) to recipient.
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param exchange_addr The address of the exchange for the token being purchased.
                  # @return Amount of Tokens (exchange_addr.token) bought.
                  @public
                  def tokenToExchangeTransferInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, recipient: address, exchange_addr: address) -> uint256:
                      assert recipient != self
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token).
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param exchange_addr The address of the exchange for the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToExchangeSwapOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, exchange_addr: address) -> uint256:
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token) and transfers
                  #         Tokens (exchange_addr.token) to recipient.
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToExchangeTransferOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, recipient: address, exchange_addr: address) -> uint256:
                      assert recipient != self
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr)
                  
                  # @notice Public price function for ETH to Token trades with an exact input.
                  # @param eth_sold Amount of ETH sold.
                  # @return Amount of Tokens that can be bought with input ETH.
                  @public
                  @constant
                  def getEthToTokenInputPrice(eth_sold: uint256(wei)) -> uint256:
                      assert eth_sold > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      return self.getInputPrice(as_unitless_number(eth_sold), as_unitless_number(self.balance), token_reserve)
                  
                  # @notice Public price function for ETH to Token trades with an exact output.
                  # @param tokens_bought Amount of Tokens bought.
                  # @return Amount of ETH needed to buy output Tokens.
                  @public
                  @constant
                  def getEthToTokenOutputPrice(tokens_bought: uint256) -> uint256(wei):
                      assert tokens_bought > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_sold: uint256 = self.getOutputPrice(tokens_bought, as_unitless_number(self.balance), token_reserve)
                      return as_wei_value(eth_sold, 'wei')
                  
                  # @notice Public price function for Token to ETH trades with an exact input.
                  # @param tokens_sold Amount of Tokens sold.
                  # @return Amount of ETH that can be bought with input Tokens.
                  @public
                  @constant
                  def getTokenToEthInputPrice(tokens_sold: uint256) -> uint256(wei):
                      assert tokens_sold > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
                      return as_wei_value(eth_bought, 'wei')
                  
                  # @notice Public price function for Token to ETH trades with an exact output.
                  # @param eth_bought Amount of output ETH.
                  # @return Amount of Tokens needed to buy output ETH.
                  @public
                  @constant
                  def getTokenToEthOutputPrice(eth_bought: uint256(wei)) -> uint256:
                      assert eth_bought > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      return self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
                  
                  # @return Address of Token that is sold on this exchange.
                  @public
                  @constant
                  def tokenAddress() -> address:
                      return self.token
                  
                  # @return Address of factory that created this exchange.
                  @public
                  @constant
                  def factoryAddress() -> address(Factory):
                      return self.factory
                  
                  # ERC20 compatibility for exchange liquidity modified from
                  # https://github.com/ethereum/vyper/blob/master/examples/tokens/ERC20.vy
                  @public
                  @constant
                  def balanceOf(_owner : address) -> uint256:
                      return self.balances[_owner]
                  
                  @public
                  def transfer(_to : address, _value : uint256) -> bool:
                      self.balances[msg.sender] -= _value
                      self.balances[_to] += _value
                      log.Transfer(msg.sender, _to, _value)
                      return True
                  
                  @public
                  def transferFrom(_from : address, _to : address, _value : uint256) -> bool:
                      self.balances[_from] -= _value
                      self.balances[_to] += _value
                      self.allowances[_from][msg.sender] -= _value
                      log.Transfer(_from, _to, _value)
                      return True
                  
                  @public
                  def approve(_spender : address, _value : uint256) -> bool:
                      self.allowances[msg.sender][_spender] = _value
                      log.Approval(msg.sender, _spender, _value)
                      return True
                  
                  @public
                  @constant
                  def allowance(_owner : address, _spender : address) -> uint256:
                      return self.allowances[_owner][_spender]

                  File 2 of 8: ProxyERC20
                  /* ===============================================
                  * Flattened with Solidifier by Coinage
                  * 
                  * https://solidifier.coina.ge
                  * ===============================================
                  */
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Owned.sol
                  version:    1.1
                  author:     Anton Jurisevic
                              Dominic Romanowski
                  
                  date:       2018-2-26
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  An Owned contract, to be inherited by other contracts.
                  Requires its owner to be explicitly set in the constructor.
                  Provides an onlyOwner access modifier.
                  
                  To change owner, the current owner must nominate the next owner,
                  who then has to accept the nomination. The nomination can be
                  cancelled before it is accepted by the new owner by having the
                  previous owner change the nomination (setting it to 0).
                  
                  -----------------------------------------------------------------
                  */
                  
                  pragma solidity 0.4.25;
                  
                  /**
                   * @title A contract with an owner.
                   * @notice Contract ownership can be transferred by first nominating the new owner,
                   * who must then accept the ownership, which prevents accidental incorrect ownership transfers.
                   */
                  contract Owned {
                      address public owner;
                      address public nominatedOwner;
                  
                      /**
                       * @dev Owned Constructor
                       */
                      constructor(address _owner)
                          public
                      {
                          require(_owner != address(0), "Owner address cannot be 0");
                          owner = _owner;
                          emit OwnerChanged(address(0), _owner);
                      }
                  
                      /**
                       * @notice Nominate a new owner of this contract.
                       * @dev Only the current owner may nominate a new owner.
                       */
                      function nominateNewOwner(address _owner)
                          external
                          onlyOwner
                      {
                          nominatedOwner = _owner;
                          emit OwnerNominated(_owner);
                      }
                  
                      /**
                       * @notice Accept the nomination to be owner.
                       */
                      function acceptOwnership()
                          external
                      {
                          require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
                          emit OwnerChanged(owner, nominatedOwner);
                          owner = nominatedOwner;
                          nominatedOwner = address(0);
                      }
                  
                      modifier onlyOwner
                      {
                          require(msg.sender == owner, "Only the contract owner may perform this action");
                          _;
                      }
                  
                      event OwnerNominated(address newOwner);
                      event OwnerChanged(address oldOwner, address newOwner);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Proxy.sol
                  version:    1.3
                  author:     Anton Jurisevic
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxy contract that, if it does not recognise the function
                  being called on it, passes all value and call data to an
                  underlying target contract.
                  
                  This proxy has the capacity to toggle between DELEGATECALL
                  and CALL style proxy functionality.
                  
                  The former executes in the proxy's context, and so will preserve 
                  msg.sender and store data at the proxy address. The latter will not.
                  Therefore, any contract the proxy wraps in the CALL style must
                  implement the Proxyable interface, in order that it can pass msg.sender
                  into the underlying contract as the state parameter, messageSender.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract Proxy is Owned {
                  
                      Proxyable public target;
                      bool public useDELEGATECALL;
                  
                      constructor(address _owner)
                          Owned(_owner)
                          public
                      {}
                  
                      function setTarget(Proxyable _target)
                          external
                          onlyOwner
                      {
                          target = _target;
                          emit TargetUpdated(_target);
                      }
                  
                      function setUseDELEGATECALL(bool value) 
                          external
                          onlyOwner
                      {
                          useDELEGATECALL = value;
                      }
                  
                      function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
                          external
                          onlyTarget
                      {
                          uint size = callData.length;
                          bytes memory _callData = callData;
                  
                          assembly {
                              /* The first 32 bytes of callData contain its length (as specified by the abi). 
                               * Length is assumed to be a uint256 and therefore maximum of 32 bytes
                               * in length. It is also leftpadded to be a multiple of 32 bytes.
                               * This means moving call_data across 32 bytes guarantees we correctly access
                               * the data itself. */
                              switch numTopics
                              case 0 {
                                  log0(add(_callData, 32), size)
                              } 
                              case 1 {
                                  log1(add(_callData, 32), size, topic1)
                              }
                              case 2 {
                                  log2(add(_callData, 32), size, topic1, topic2)
                              }
                              case 3 {
                                  log3(add(_callData, 32), size, topic1, topic2, topic3)
                              }
                              case 4 {
                                  log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
                              }
                          }
                      }
                  
                      function()
                          external
                          payable
                      {
                          if (useDELEGATECALL) {
                              assembly {
                                  /* Copy call data into free memory region. */
                                  let free_ptr := mload(0x40)
                                  calldatacopy(free_ptr, 0, calldatasize)
                  
                                  /* Forward all gas and call data to the target contract. */
                                  let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
                                  returndatacopy(free_ptr, 0, returndatasize)
                  
                                  /* Revert if the call failed, otherwise return the result. */
                                  if iszero(result) { revert(free_ptr, returndatasize) }
                                  return(free_ptr, returndatasize)
                              }
                          } else {
                              /* Here we are as above, but must send the messageSender explicitly 
                               * since we are using CALL rather than DELEGATECALL. */
                              target.setMessageSender(msg.sender);
                              assembly {
                                  let free_ptr := mload(0x40)
                                  calldatacopy(free_ptr, 0, calldatasize)
                  
                                  /* We must explicitly forward ether to the underlying contract as well. */
                                  let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
                                  returndatacopy(free_ptr, 0, returndatasize)
                  
                                  if iszero(result) { revert(free_ptr, returndatasize) }
                                  return(free_ptr, returndatasize)
                              }
                          }
                      }
                  
                      modifier onlyTarget {
                          require(Proxyable(msg.sender) == target, "Must be proxy target");
                          _;
                      }
                  
                      event TargetUpdated(Proxyable newTarget);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Proxyable.sol
                  version:    1.1
                  author:     Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  checked:    Mike Spain
                  approved:   Samuel Brooks
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxyable contract that works hand in hand with the Proxy contract
                  to allow for anyone to interact with the underlying contract both
                  directly and through the proxy.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  // This contract should be treated like an abstract contract
                  contract Proxyable is Owned {
                      /* The proxy this contract exists behind. */
                      Proxy public proxy;
                      Proxy public integrationProxy;
                  
                      /* The caller of the proxy, passed through to this contract.
                       * Note that every function using this member must apply the onlyProxy or
                       * optionalProxy modifiers, otherwise their invocations can use stale values. */
                      address messageSender;
                  
                      constructor(address _proxy, address _owner)
                          Owned(_owner)
                          public
                      {
                          proxy = Proxy(_proxy);
                          emit ProxyUpdated(_proxy);
                      }
                  
                      function setProxy(address _proxy)
                          external
                          onlyOwner
                      {
                          proxy = Proxy(_proxy);
                          emit ProxyUpdated(_proxy);
                      }
                  
                      function setIntegrationProxy(address _integrationProxy)
                          external
                          onlyOwner
                      {
                          integrationProxy = Proxy(_integrationProxy);
                      }
                  
                      function setMessageSender(address sender)
                          external
                          onlyProxy
                      {
                          messageSender = sender;
                      }
                  
                      modifier onlyProxy {
                          require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
                          _;
                      }
                  
                      modifier optionalProxy
                      {
                          if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy) {
                              messageSender = msg.sender;
                          }
                          _;
                      }
                  
                      modifier optionalProxy_onlyOwner
                      {
                          if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy) {
                              messageSender = msg.sender;
                          }
                          require(messageSender == owner, "Owner only function");
                          _;
                      }
                  
                      event ProxyUpdated(address proxyAddress);
                  }
                  
                  
                  /**
                   * @title ERC20 interface
                   * @dev see https://github.com/ethereum/EIPs/issues/20
                   */
                  contract IERC20 {
                      function totalSupply() public view returns (uint);
                  
                      function balanceOf(address owner) public view returns (uint);
                  
                      function allowance(address owner, address spender) public view returns (uint);
                  
                      function transfer(address to, uint value) public returns (bool);
                  
                      function approve(address spender, uint value) public returns (bool);
                  
                      function transferFrom(address from, address to, uint value) public returns (bool);
                  
                      // ERC20 Optional
                      function name() public view returns (string);
                      function symbol() public view returns (string);
                      function decimals() public view returns (uint8);
                  
                      event Transfer(
                        address indexed from,
                        address indexed to,
                        uint value
                      );
                  
                      event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint value
                      );
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       ProxyERC20.sol
                  version:    1.0
                  author:     Jackson Chan, Clinton Ennis
                  
                  date:       2019-06-19
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxy contract that is ERC20 compliant for the Synthetix Network.
                  
                  If it does not recognise a function being called on it, passes all
                  value and call data to an underlying target contract.
                  
                  The ERC20 standard has been explicitly implemented to ensure
                  contract to contract calls are compatable on MAINNET
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract ProxyERC20 is Proxy, IERC20 {
                  
                      constructor(address _owner)
                          Proxy(_owner)
                          public
                      {}
                  
                      // ------------- ERC20 Details ------------- //
                  
                      function name() public view returns (string){
                          // Immutable static call from target contract
                          return IERC20(target).name();
                      }
                  
                      function symbol() public view returns (string){
                           // Immutable static call from target contract
                          return IERC20(target).symbol();
                      }
                  
                      function decimals() public view returns (uint8){
                           // Immutable static call from target contract
                          return IERC20(target).decimals();
                      }
                  
                      // ------------- ERC20 Interface ------------- //
                  
                      /**
                      * @dev Total number of tokens in existence
                      */
                      function totalSupply() public view returns (uint256) {
                          // Immutable static call from target contract
                          return IERC20(target).totalSupply();
                      }
                  
                      /**
                      * @dev Gets the balance of the specified address.
                      * @param owner The address to query the balance of.
                      * @return An uint256 representing the amount owned by the passed address.
                      */
                      function balanceOf(address owner) public view returns (uint256) {
                          // Immutable static call from target contract
                          return IERC20(target).balanceOf(owner);
                      }
                  
                      /**
                      * @dev Function to check the amount of tokens that an owner allowed to a spender.
                      * @param owner address The address which owns the funds.
                      * @param spender address The address which will spend the funds.
                      * @return A uint256 specifying the amount of tokens still available for the spender.
                      */
                      function allowance(
                          address owner,
                          address spender
                      )
                          public
                          view
                          returns (uint256)
                      {
                          // Immutable static call from target contract
                          return IERC20(target).allowance(owner, spender);
                      }
                  
                      /**
                      * @dev Transfer token for a specified address
                      * @param to The address to transfer to.
                      * @param value The amount to be transferred.
                      */
                      function transfer(address to, uint256 value) public returns (bool) {
                          // Mutable state call requires the proxy to tell the target who the msg.sender is.
                          target.setMessageSender(msg.sender);
                  
                          // Forward the ERC20 call to the target contract
                          IERC20(target).transfer(to, value);
                  
                          // Event emitting will occur via Synthetix.Proxy._emit()
                          return true;
                      }
                  
                      /**
                      * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
                      * 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
                      * @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 returns (bool) {
                          // Mutable state call requires the proxy to tell the target who the msg.sender is.
                          target.setMessageSender(msg.sender);
                  
                          // Forward the ERC20 call to the target contract
                          IERC20(target).approve(spender, value);
                  
                          // Event emitting will occur via Synthetix.Proxy._emit()
                          return true;
                      }
                  
                      /**
                      * @dev Transfer tokens from one address to another
                      * @param from address The address which you want to send tokens from
                      * @param to address The address which you want to transfer to
                      * @param value uint256 the amount of tokens to be transferred
                      */
                      function transferFrom(
                          address from,
                          address to,
                          uint256 value
                      )
                          public
                          returns (bool)
                      {
                          // Mutable state call requires the proxy to tell the target who the msg.sender is.
                          target.setMessageSender(msg.sender);
                  
                          // Forward the ERC20 call to the target contract
                          IERC20(target).transferFrom(from, to, value);
                  
                          // Event emitting will occur via Synthetix.Proxy._emit()
                          return true;
                      }
                  }
                  
                  

                  File 3 of 8: Vyper_contract
                  # @title Uniswap Exchange Interface V1
                  # @notice Source code found at https://github.com/uniswap
                  # @notice Use at your own risk
                  
                  contract Factory():
                      def getExchange(token_addr: address) -> address: constant
                  
                  contract Exchange():
                      def getEthToTokenOutputPrice(tokens_bought: uint256) -> uint256(wei): constant
                      def ethToTokenTransferInput(min_tokens: uint256, deadline: timestamp, recipient: address) -> uint256: modifying
                      def ethToTokenTransferOutput(tokens_bought: uint256, deadline: timestamp, recipient: address) -> uint256(wei): modifying
                  
                  TokenPurchase: event({buyer: indexed(address), eth_sold: indexed(uint256(wei)), tokens_bought: indexed(uint256)})
                  EthPurchase: event({buyer: indexed(address), tokens_sold: indexed(uint256), eth_bought: indexed(uint256(wei))})
                  AddLiquidity: event({provider: indexed(address), eth_amount: indexed(uint256(wei)), token_amount: indexed(uint256)})
                  RemoveLiquidity: event({provider: indexed(address), eth_amount: indexed(uint256(wei)), token_amount: indexed(uint256)})
                  Transfer: event({_from: indexed(address), _to: indexed(address), _value: uint256})
                  Approval: event({_owner: indexed(address), _spender: indexed(address), _value: uint256})
                  
                  name: public(bytes32)                             # Uniswap V1
                  symbol: public(bytes32)                           # UNI-V1
                  decimals: public(uint256)                         # 18
                  totalSupply: public(uint256)                      # total number of UNI in existence
                  balances: uint256[address]                        # UNI balance of an address
                  allowances: (uint256[address])[address]           # UNI allowance of one address on another
                  token: address(ERC20)                             # address of the ERC20 token traded on this contract
                  factory: Factory                                  # interface for the factory that created this contract
                  
                  # @dev This function acts as a contract constructor which is not currently supported in contracts deployed
                  #      using create_with_code_of(). It is called once by the factory during contract creation.
                  @public
                  def setup(token_addr: address):
                      assert (self.factory == ZERO_ADDRESS and self.token == ZERO_ADDRESS) and token_addr != ZERO_ADDRESS
                      self.factory = msg.sender
                      self.token = token_addr
                      self.name = 0x556e697377617020563100000000000000000000000000000000000000000000
                      self.symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000
                      self.decimals = 18
                  
                  # @notice Deposit ETH and Tokens (self.token) at current ratio to mint UNI tokens.
                  # @dev min_liquidity does nothing when total UNI supply is 0.
                  # @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0.
                  # @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return The amount of UNI minted.
                  @public
                  @payable
                  def addLiquidity(min_liquidity: uint256, max_tokens: uint256, deadline: timestamp) -> uint256:
                      assert deadline > block.timestamp and (max_tokens > 0 and msg.value > 0)
                      total_liquidity: uint256 = self.totalSupply
                      if total_liquidity > 0:
                          assert min_liquidity > 0
                          eth_reserve: uint256(wei) = self.balance - msg.value
                          token_reserve: uint256 = self.token.balanceOf(self)
                          token_amount: uint256 = msg.value * token_reserve / eth_reserve + 1
                          liquidity_minted: uint256 = msg.value * total_liquidity / eth_reserve
                          assert max_tokens >= token_amount and liquidity_minted >= min_liquidity
                          self.balances[msg.sender] += liquidity_minted
                          self.totalSupply = total_liquidity + liquidity_minted
                          assert self.token.transferFrom(msg.sender, self, token_amount)
                          log.AddLiquidity(msg.sender, msg.value, token_amount)
                          log.Transfer(ZERO_ADDRESS, msg.sender, liquidity_minted)
                          return liquidity_minted
                      else:
                          assert (self.factory != ZERO_ADDRESS and self.token != ZERO_ADDRESS) and msg.value >= 1000000000
                          assert self.factory.getExchange(self.token) == self
                          token_amount: uint256 = max_tokens
                          initial_liquidity: uint256 = as_unitless_number(self.balance)
                          self.totalSupply = initial_liquidity
                          self.balances[msg.sender] = initial_liquidity
                          assert self.token.transferFrom(msg.sender, self, token_amount)
                          log.AddLiquidity(msg.sender, msg.value, token_amount)
                          log.Transfer(ZERO_ADDRESS, msg.sender, initial_liquidity)
                          return initial_liquidity
                  
                  # @dev Burn UNI tokens to withdraw ETH and Tokens at current ratio.
                  # @param amount Amount of UNI burned.
                  # @param min_eth Minimum ETH withdrawn.
                  # @param min_tokens Minimum Tokens withdrawn.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return The amount of ETH and Tokens withdrawn.
                  @public
                  def removeLiquidity(amount: uint256, min_eth: uint256(wei), min_tokens: uint256, deadline: timestamp) -> (uint256(wei), uint256):
                      assert (amount > 0 and deadline > block.timestamp) and (min_eth > 0 and min_tokens > 0)
                      total_liquidity: uint256 = self.totalSupply
                      assert total_liquidity > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_amount: uint256(wei) = amount * self.balance / total_liquidity
                      token_amount: uint256 = amount * token_reserve / total_liquidity
                      assert eth_amount >= min_eth and token_amount >= min_tokens
                      self.balances[msg.sender] -= amount
                      self.totalSupply = total_liquidity - amount
                      send(msg.sender, eth_amount)
                      assert self.token.transfer(msg.sender, token_amount)
                      log.RemoveLiquidity(msg.sender, eth_amount, token_amount)
                      log.Transfer(msg.sender, ZERO_ADDRESS, amount)
                      return eth_amount, token_amount
                  
                  # @dev Pricing function for converting between ETH and Tokens.
                  # @param input_amount Amount of ETH or Tokens being sold.
                  # @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves.
                  # @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves.
                  # @return Amount of ETH or Tokens bought.
                  @private
                  @constant
                  def getInputPrice(input_amount: uint256, input_reserve: uint256, output_reserve: uint256) -> uint256:
                      assert input_reserve > 0 and output_reserve > 0
                      input_amount_with_fee: uint256 = input_amount * 997
                      numerator: uint256 = input_amount_with_fee * output_reserve
                      denominator: uint256 = (input_reserve * 1000) + input_amount_with_fee
                      return numerator / denominator
                  
                  # @dev Pricing function for converting between ETH and Tokens.
                  # @param output_amount Amount of ETH or Tokens being bought.
                  # @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves.
                  # @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves.
                  # @return Amount of ETH or Tokens sold.
                  @private
                  @constant
                  def getOutputPrice(output_amount: uint256, input_reserve: uint256, output_reserve: uint256) -> uint256:
                      assert input_reserve > 0 and output_reserve > 0
                      numerator: uint256 = input_reserve * output_amount * 1000
                      denominator: uint256 = (output_reserve - output_amount) * 997
                      return numerator / denominator + 1
                  
                  @private
                  def ethToTokenInput(eth_sold: uint256(wei), min_tokens: uint256, deadline: timestamp, buyer: address, recipient: address) -> uint256:
                      assert deadline >= block.timestamp and (eth_sold > 0 and min_tokens > 0)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      tokens_bought: uint256 = self.getInputPrice(as_unitless_number(eth_sold), as_unitless_number(self.balance - eth_sold), token_reserve)
                      assert tokens_bought >= min_tokens
                      assert self.token.transfer(recipient, tokens_bought)
                      log.TokenPurchase(buyer, eth_sold, tokens_bought)
                      return tokens_bought
                  
                  # @notice Convert ETH to Tokens.
                  # @dev User specifies exact input (msg.value).
                  # @dev User cannot specify minimum output or deadline.
                  @public
                  @payable
                  def __default__():
                      self.ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender)
                  
                  # @notice Convert ETH to Tokens.
                  # @dev User specifies exact input (msg.value) and minimum output.
                  # @param min_tokens Minimum Tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of Tokens bought.
                  @public
                  @payable
                  def ethToTokenSwapInput(min_tokens: uint256, deadline: timestamp) -> uint256:
                      return self.ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert ETH to Tokens and transfers Tokens to recipient.
                  # @dev User specifies exact input (msg.value) and minimum output
                  # @param min_tokens Minimum Tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output Tokens.
                  # @return Amount of Tokens bought.
                  @public
                  @payable
                  def ethToTokenTransferInput(min_tokens: uint256, deadline: timestamp, recipient: address) -> uint256:
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient)
                  
                  @private
                  def ethToTokenOutput(tokens_bought: uint256, max_eth: uint256(wei), deadline: timestamp, buyer: address, recipient: address) -> uint256(wei):
                      assert deadline >= block.timestamp and (tokens_bought > 0 and max_eth > 0)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_sold: uint256 = self.getOutputPrice(tokens_bought, as_unitless_number(self.balance - max_eth), token_reserve)
                      # Throws if eth_sold > max_eth
                      eth_refund: uint256(wei) = max_eth - as_wei_value(eth_sold, 'wei')
                      if eth_refund > 0:
                          send(buyer, eth_refund)
                      assert self.token.transfer(recipient, tokens_bought)
                      log.TokenPurchase(buyer, as_wei_value(eth_sold, 'wei'), tokens_bought)
                      return as_wei_value(eth_sold, 'wei')
                  
                  # @notice Convert ETH to Tokens.
                  # @dev User specifies maximum input (msg.value) and exact output.
                  # @param tokens_bought Amount of tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of ETH sold.
                  @public
                  @payable
                  def ethToTokenSwapOutput(tokens_bought: uint256, deadline: timestamp) -> uint256(wei):
                      return self.ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert ETH to Tokens and transfers Tokens to recipient.
                  # @dev User specifies maximum input (msg.value) and exact output.
                  # @param tokens_bought Amount of tokens bought.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output Tokens.
                  # @return Amount of ETH sold.
                  @public
                  @payable
                  def ethToTokenTransferOutput(tokens_bought: uint256, deadline: timestamp, recipient: address) -> uint256(wei):
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient)
                  
                  @private
                  def tokenToEthInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp, buyer: address, recipient: address) -> uint256(wei):
                      assert deadline >= block.timestamp and (tokens_sold > 0 and min_eth > 0)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
                      wei_bought: uint256(wei) = as_wei_value(eth_bought, 'wei')
                      assert wei_bought >= min_eth
                      send(recipient, wei_bought)
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      log.EthPurchase(buyer, tokens_sold, wei_bought)
                      return wei_bought
                  
                  
                  # @notice Convert Tokens to ETH.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_eth Minimum ETH purchased.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of ETH bought.
                  @public
                  def tokenToEthSwapInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp) -> uint256(wei):
                      return self.tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert Tokens to ETH and transfers ETH to recipient.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_eth Minimum ETH purchased.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @return Amount of ETH bought.
                  @public
                  def tokenToEthTransferInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp, recipient: address) -> uint256(wei):
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient)
                  
                  @private
                  def tokenToEthOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp, buyer: address, recipient: address) -> uint256:
                      assert deadline >= block.timestamp and eth_bought > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      tokens_sold: uint256 = self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
                      # tokens sold is always > 0
                      assert max_tokens >= tokens_sold
                      send(recipient, eth_bought)
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      log.EthPurchase(buyer, tokens_sold, eth_bought)
                      return tokens_sold
                  
                  # @notice Convert Tokens to ETH.
                  # @dev User specifies maximum input and exact output.
                  # @param eth_bought Amount of ETH purchased.
                  # @param max_tokens Maximum Tokens sold.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @return Amount of Tokens sold.
                  @public
                  def tokenToEthSwapOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp) -> uint256:
                      return self.tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender)
                  
                  # @notice Convert Tokens to ETH and transfers ETH to recipient.
                  # @dev User specifies maximum input and exact output.
                  # @param eth_bought Amount of ETH purchased.
                  # @param max_tokens Maximum Tokens sold.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @return Amount of Tokens sold.
                  @public
                  def tokenToEthTransferOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp, recipient: address) -> uint256:
                      assert recipient != self and recipient != ZERO_ADDRESS
                      return self.tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient)
                  
                  @private
                  def tokenToTokenInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, buyer: address, recipient: address, exchange_addr: address) -> uint256:
                      assert (deadline >= block.timestamp and tokens_sold > 0) and (min_tokens_bought > 0 and min_eth_bought > 0)
                      assert exchange_addr != self and exchange_addr != ZERO_ADDRESS
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
                      wei_bought: uint256(wei) = as_wei_value(eth_bought, 'wei')
                      assert wei_bought >= min_eth_bought
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      tokens_bought: uint256 = Exchange(exchange_addr).ethToTokenTransferInput(min_tokens_bought, deadline, recipient, value=wei_bought)
                      log.EthPurchase(buyer, tokens_sold, wei_bought)
                      return tokens_bought
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr).
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (token_addr) bought.
                  @public
                  def tokenToTokenSwapInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr) and transfers
                  #         Tokens (token_addr) to recipient.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (token_addr) bought.
                  @public
                  def tokenToTokenTransferInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, recipient: address, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr)
                  
                  @private
                  def tokenToTokenOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, buyer: address, recipient: address, exchange_addr: address) -> uint256:
                      assert deadline >= block.timestamp and (tokens_bought > 0 and max_eth_sold > 0)
                      assert exchange_addr != self and exchange_addr != ZERO_ADDRESS
                      eth_bought: uint256(wei) = Exchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought)
                      token_reserve: uint256 = self.token.balanceOf(self)
                      tokens_sold: uint256 = self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
                      # tokens sold is always > 0
                      assert max_tokens_sold >= tokens_sold and max_eth_sold >= eth_bought
                      assert self.token.transferFrom(buyer, self, tokens_sold)
                      eth_sold: uint256(wei) = Exchange(exchange_addr).ethToTokenTransferOutput(tokens_bought, deadline, recipient, value=eth_bought)
                      log.EthPurchase(buyer, tokens_sold, eth_bought)
                      return tokens_sold
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr).
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToTokenSwapOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (token_addr) and transfers
                  #         Tokens (token_addr) to recipient.
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToTokenTransferOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, recipient: address, token_addr: address) -> uint256:
                      exchange_addr: address = self.factory.getExchange(token_addr)
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token).
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param exchange_addr The address of the exchange for the token being purchased.
                  # @return Amount of Tokens (exchange_addr.token) bought.
                  @public
                  def tokenToExchangeSwapInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, exchange_addr: address) -> uint256:
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token) and transfers
                  #         Tokens (exchange_addr.token) to recipient.
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies exact input and minimum output.
                  # @param tokens_sold Amount of Tokens sold.
                  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
                  # @param min_eth_bought Minimum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param exchange_addr The address of the exchange for the token being purchased.
                  # @return Amount of Tokens (exchange_addr.token) bought.
                  @public
                  def tokenToExchangeTransferInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, recipient: address, exchange_addr: address) -> uint256:
                      assert recipient != self
                      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token).
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param exchange_addr The address of the exchange for the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToExchangeSwapOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, exchange_addr: address) -> uint256:
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr)
                  
                  # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token) and transfers
                  #         Tokens (exchange_addr.token) to recipient.
                  # @dev Allows trades through contracts that were not deployed from the same factory.
                  # @dev User specifies maximum input and exact output.
                  # @param tokens_bought Amount of Tokens (token_addr) bought.
                  # @param max_tokens_sold Maximum Tokens (self.token) sold.
                  # @param max_eth_sold Maximum ETH purchased as intermediary.
                  # @param deadline Time after which this transaction can no longer be executed.
                  # @param recipient The address that receives output ETH.
                  # @param token_addr The address of the token being purchased.
                  # @return Amount of Tokens (self.token) sold.
                  @public
                  def tokenToExchangeTransferOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, recipient: address, exchange_addr: address) -> uint256:
                      assert recipient != self
                      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr)
                  
                  # @notice Public price function for ETH to Token trades with an exact input.
                  # @param eth_sold Amount of ETH sold.
                  # @return Amount of Tokens that can be bought with input ETH.
                  @public
                  @constant
                  def getEthToTokenInputPrice(eth_sold: uint256(wei)) -> uint256:
                      assert eth_sold > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      return self.getInputPrice(as_unitless_number(eth_sold), as_unitless_number(self.balance), token_reserve)
                  
                  # @notice Public price function for ETH to Token trades with an exact output.
                  # @param tokens_bought Amount of Tokens bought.
                  # @return Amount of ETH needed to buy output Tokens.
                  @public
                  @constant
                  def getEthToTokenOutputPrice(tokens_bought: uint256) -> uint256(wei):
                      assert tokens_bought > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_sold: uint256 = self.getOutputPrice(tokens_bought, as_unitless_number(self.balance), token_reserve)
                      return as_wei_value(eth_sold, 'wei')
                  
                  # @notice Public price function for Token to ETH trades with an exact input.
                  # @param tokens_sold Amount of Tokens sold.
                  # @return Amount of ETH that can be bought with input Tokens.
                  @public
                  @constant
                  def getTokenToEthInputPrice(tokens_sold: uint256) -> uint256(wei):
                      assert tokens_sold > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
                      return as_wei_value(eth_bought, 'wei')
                  
                  # @notice Public price function for Token to ETH trades with an exact output.
                  # @param eth_bought Amount of output ETH.
                  # @return Amount of Tokens needed to buy output ETH.
                  @public
                  @constant
                  def getTokenToEthOutputPrice(eth_bought: uint256(wei)) -> uint256:
                      assert eth_bought > 0
                      token_reserve: uint256 = self.token.balanceOf(self)
                      return self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
                  
                  # @return Address of Token that is sold on this exchange.
                  @public
                  @constant
                  def tokenAddress() -> address:
                      return self.token
                  
                  # @return Address of factory that created this exchange.
                  @public
                  @constant
                  def factoryAddress() -> address(Factory):
                      return self.factory
                  
                  # ERC20 compatibility for exchange liquidity modified from
                  # https://github.com/ethereum/vyper/blob/master/examples/tokens/ERC20.vy
                  @public
                  @constant
                  def balanceOf(_owner : address) -> uint256:
                      return self.balances[_owner]
                  
                  @public
                  def transfer(_to : address, _value : uint256) -> bool:
                      self.balances[msg.sender] -= _value
                      self.balances[_to] += _value
                      log.Transfer(msg.sender, _to, _value)
                      return True
                  
                  @public
                  def transferFrom(_from : address, _to : address, _value : uint256) -> bool:
                      self.balances[_from] -= _value
                      self.balances[_to] += _value
                      self.allowances[_from][msg.sender] -= _value
                      log.Transfer(_from, _to, _value)
                      return True
                  
                  @public
                  def approve(_spender : address, _value : uint256) -> bool:
                      self.allowances[msg.sender][_spender] = _value
                      log.Approval(msg.sender, _spender, _value)
                      return True
                  
                  @public
                  @constant
                  def allowance(_owner : address, _spender : address) -> uint256:
                      return self.allowances[_owner][_spender]

                  File 4 of 8: MultiCollateralSynth
                  /*
                  * Synthetix - MultiCollateralSynth.sol
                  *
                  * https://github.com/Synthetixio/synthetix
                  * https://synthetix.io
                  *
                  * MIT License
                  * ===========
                  *
                  * Copyright (c) 2020 Synthetix
                  *
                  * 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
                  */
                      
                  /* ===============================================
                  * Flattened with Solidifier by Coinage
                  * 
                  * https://solidifier.coina.ge
                  * ===============================================
                  */
                  
                  
                  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, "SafeMath.mul Error");
                  
                      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, "SafeMath.div Error"); // 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, "SafeMath.sub Error");
                      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, "SafeMath.add Error");
                  
                      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, "SafeMath.mod Error");
                      return a % b;
                    }
                  }
                  
                  
                  /*
                  
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       SafeDecimalMath.sol
                  version:    2.0
                  author:     Kevin Brown
                              Gavin Conway
                  date:       2018-10-18
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A library providing safe mathematical operations for division and
                  multiplication with the capability to round or truncate the results
                  to the nearest increment. Operations can return a standard precision
                  or high precision decimal. High precision decimals are useful for
                  example when attempting to calculate percentages or fractions
                  accurately.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title Safely manipulate unsigned fixed-point decimals at a given precision level.
                   * @dev Functions accepting uints in this contract and derived contracts
                   * are taken to be such fixed point decimals of a specified precision (either standard
                   * or high).
                   */
                  library SafeDecimalMath {
                      using SafeMath for uint;
                  
                      /* Number of decimal places in the representations. */
                      uint8 public constant decimals = 18;
                      uint8 public constant highPrecisionDecimals = 27;
                  
                      /* The number representing 1.0. */
                      uint public constant UNIT = 10**uint(decimals);
                  
                      /* The number representing 1.0 for higher fidelity numbers. */
                      uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
                      uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
                  
                      /** 
                       * @return Provides an interface to UNIT.
                       */
                      function unit() external pure returns (uint) {
                          return UNIT;
                      }
                  
                      /** 
                       * @return Provides an interface to PRECISE_UNIT.
                       */
                      function preciseUnit() external pure returns (uint) {
                          return PRECISE_UNIT;
                      }
                  
                      /**
                       * @return The result of multiplying x and y, interpreting the operands as fixed-point
                       * decimals.
                       * 
                       * @dev A unit factor is divided out after the product of x and y is evaluated,
                       * so that product must be less than 2**256. As this is an integer division,
                       * the internal division always rounds down. This helps save on gas. Rounding
                       * is more expensive on gas.
                       */
                      function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
                          /* Divide by UNIT to remove the extra factor introduced by the product. */
                          return x.mul(y) / UNIT;
                      }
                  
                      /**
                       * @return The result of safely multiplying x and y, interpreting the operands
                       * as fixed-point decimals of the specified precision unit.
                       *
                       * @dev The operands should be in the form of a the specified unit factor which will be
                       * divided out after the product of x and y is evaluated, so that product must be
                       * less than 2**256.
                       *
                       * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
                       * Rounding is useful when you need to retain fidelity for small decimal numbers
                       * (eg. small fractions or percentages).
                       */
                      function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) {
                          /* Divide by UNIT to remove the extra factor introduced by the product. */
                          uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
                  
                          if (quotientTimesTen % 10 >= 5) {
                              quotientTimesTen += 10;
                          }
                  
                          return quotientTimesTen / 10;
                      }
                  
                      /**
                       * @return The result of safely multiplying x and y, interpreting the operands
                       * as fixed-point decimals of a precise unit.
                       *
                       * @dev The operands should be in the precise unit factor which will be
                       * divided out after the product of x and y is evaluated, so that product must be
                       * less than 2**256.
                       *
                       * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
                       * Rounding is useful when you need to retain fidelity for small decimal numbers
                       * (eg. small fractions or percentages).
                       */
                      function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
                          return _multiplyDecimalRound(x, y, PRECISE_UNIT);
                      }
                  
                      /**
                       * @return The result of safely multiplying x and y, interpreting the operands
                       * as fixed-point decimals of a standard unit.
                       *
                       * @dev The operands should be in the standard unit factor which will be
                       * divided out after the product of x and y is evaluated, so that product must be
                       * less than 2**256.
                       *
                       * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
                       * Rounding is useful when you need to retain fidelity for small decimal numbers
                       * (eg. small fractions or percentages).
                       */
                      function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
                          return _multiplyDecimalRound(x, y, UNIT);
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is a high
                       * precision decimal.
                       * 
                       * @dev y is divided after the product of x and the standard precision unit
                       * is evaluated, so the product of x and UNIT must be less than 2**256. As
                       * this is an integer division, the result is always rounded down.
                       * This helps save on gas. Rounding is more expensive on gas.
                       */
                      function divideDecimal(uint x, uint y) internal pure returns (uint) {
                          /* Reintroduce the UNIT factor that will be divided out by y. */
                          return x.mul(UNIT).div(y);
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is as a rounded
                       * decimal in the precision unit specified in the parameter.
                       *
                       * @dev y is divided after the product of x and the specified precision unit
                       * is evaluated, so the product of x and the specified precision unit must
                       * be less than 2**256. The result is rounded to the nearest increment.
                       */
                      function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) {
                          uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
                  
                          if (resultTimesTen % 10 >= 5) {
                              resultTimesTen += 10;
                          }
                  
                          return resultTimesTen / 10;
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is as a rounded
                       * standard precision decimal.
                       *
                       * @dev y is divided after the product of x and the standard precision unit
                       * is evaluated, so the product of x and the standard precision unit must
                       * be less than 2**256. The result is rounded to the nearest increment.
                       */
                      function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
                          return _divideDecimalRound(x, y, UNIT);
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is as a rounded
                       * high precision decimal.
                       *
                       * @dev y is divided after the product of x and the high precision unit
                       * is evaluated, so the product of x and the high precision unit must
                       * be less than 2**256. The result is rounded to the nearest increment.
                       */
                      function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
                          return _divideDecimalRound(x, y, PRECISE_UNIT);
                      }
                  
                      /**
                       * @dev Convert a standard decimal representation to a high precision one.
                       */
                      function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
                          return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
                      }
                  
                      /**
                       * @dev Convert a high precision decimal to a standard decimal representation.
                       */
                      function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
                          uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
                  
                          if (quotientTimesTen % 10 >= 5) {
                              quotientTimesTen += 10;
                          }
                  
                          return quotientTimesTen / 10;
                      }
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Owned.sol
                  version:    1.1
                  author:     Anton Jurisevic
                              Dominic Romanowski
                  
                  date:       2018-2-26
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  An Owned contract, to be inherited by other contracts.
                  Requires its owner to be explicitly set in the constructor.
                  Provides an onlyOwner access modifier.
                  
                  To change owner, the current owner must nominate the next owner,
                  who then has to accept the nomination. The nomination can be
                  cancelled before it is accepted by the new owner by having the
                  previous owner change the nomination (setting it to 0).
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title A contract with an owner.
                   * @notice Contract ownership can be transferred by first nominating the new owner,
                   * who must then accept the ownership, which prevents accidental incorrect ownership transfers.
                   */
                  contract Owned {
                      address public owner;
                      address public nominatedOwner;
                  
                      /**
                       * @dev Owned Constructor
                       */
                      constructor(address _owner) public {
                          require(_owner != address(0), "Owner address cannot be 0");
                          owner = _owner;
                          emit OwnerChanged(address(0), _owner);
                      }
                  
                      /**
                       * @notice Nominate a new owner of this contract.
                       * @dev Only the current owner may nominate a new owner.
                       */
                      function nominateNewOwner(address _owner) external onlyOwner {
                          nominatedOwner = _owner;
                          emit OwnerNominated(_owner);
                      }
                  
                      /**
                       * @notice Accept the nomination to be owner.
                       */
                      function acceptOwnership() external {
                          require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
                          emit OwnerChanged(owner, nominatedOwner);
                          owner = nominatedOwner;
                          nominatedOwner = address(0);
                      }
                  
                      modifier onlyOwner {
                          require(msg.sender == owner, "Only the contract owner may perform this action");
                          _;
                      }
                  
                      event OwnerNominated(address newOwner);
                      event OwnerChanged(address oldOwner, address newOwner);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       SelfDestructible.sol
                  version:    1.2
                  author:     Anton Jurisevic
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  This contract allows an inheriting contract to be destroyed after
                  its owner indicates an intention and then waits for a period
                  without changing their mind. All ether contained in the contract
                  is forwarded to a nominated beneficiary upon destruction.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title A contract that can be destroyed by its owner after a delay elapses.
                   */
                  contract SelfDestructible is Owned {
                      uint public initiationTime;
                      bool public selfDestructInitiated;
                      address public selfDestructBeneficiary;
                      uint public constant SELFDESTRUCT_DELAY = 4 weeks;
                  
                      /**
                       * @dev Constructor
                       * @param _owner The account which controls this contract.
                       */
                      constructor(address _owner) public Owned(_owner) {
                          require(_owner != address(0), "Owner must not be zero");
                          selfDestructBeneficiary = _owner;
                          emit SelfDestructBeneficiaryUpdated(_owner);
                      }
                  
                      /**
                       * @notice Set the beneficiary address of this contract.
                       * @dev Only the contract owner may call this. The provided beneficiary must be non-null.
                       * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
                       */
                      function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner {
                          require(_beneficiary != address(0), "Beneficiary must not be zero");
                          selfDestructBeneficiary = _beneficiary;
                          emit SelfDestructBeneficiaryUpdated(_beneficiary);
                      }
                  
                      /**
                       * @notice Begin the self-destruction counter of this contract.
                       * Once the delay has elapsed, the contract may be self-destructed.
                       * @dev Only the contract owner may call this.
                       */
                      function initiateSelfDestruct() external onlyOwner {
                          initiationTime = now;
                          selfDestructInitiated = true;
                          emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
                      }
                  
                      /**
                       * @notice Terminate and reset the self-destruction timer.
                       * @dev Only the contract owner may call this.
                       */
                      function terminateSelfDestruct() external onlyOwner {
                          initiationTime = 0;
                          selfDestructInitiated = false;
                          emit SelfDestructTerminated();
                      }
                  
                      /**
                       * @notice If the self-destruction delay has elapsed, destroy this contract and
                       * remit any ether it owns to the beneficiary address.
                       * @dev Only the contract owner may call this.
                       */
                      function selfDestruct() external onlyOwner {
                          require(selfDestructInitiated, "Self Destruct not yet initiated");
                          require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met");
                          address beneficiary = selfDestructBeneficiary;
                          emit SelfDestructed(beneficiary);
                          selfdestruct(beneficiary);
                      }
                  
                      event SelfDestructTerminated();
                      event SelfDestructed(address beneficiary);
                      event SelfDestructInitiated(uint selfDestructDelay);
                      event SelfDestructBeneficiaryUpdated(address newBeneficiary);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       State.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract State is Owned {
                      // the address of the contract that can modify variables
                      // this can only be changed by the owner of this contract
                      address public associatedContract;
                  
                      constructor(address _owner, address _associatedContract) public Owned(_owner) {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      // Change the associated contract to a new address
                      function setAssociatedContract(address _associatedContract) external onlyOwner {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      modifier onlyAssociatedContract {
                          require(msg.sender == associatedContract, "Only the associated contract can perform this action");
                          _;
                      }
                  
                      /* ========== EVENTS ========== */
                  
                      event AssociatedContractUpdated(address associatedContract);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       TokenState.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A contract that holds the state of an ERC20 compliant token.
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title ERC20 Token State
                   * @notice Stores balance information of an ERC20 token contract.
                   */
                  contract TokenState is State {
                      /* ERC20 fields. */
                      mapping(address => uint) public balanceOf;
                      mapping(address => mapping(address => uint)) public allowance;
                  
                      /**
                       * @dev Constructor
                       * @param _owner The address which controls this contract.
                       * @param _associatedContract The ERC20 contract whose state this composes.
                       */
                      constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
                  
                      /* ========== SETTERS ========== */
                  
                      /**
                       * @notice Set ERC20 allowance.
                       * @dev Only the associated contract may call this.
                       * @param tokenOwner The authorising party.
                       * @param spender The authorised party.
                       * @param value The total value the authorised party may spend on the
                       * authorising party's behalf.
                       */
                      function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract {
                          allowance[tokenOwner][spender] = value;
                      }
                  
                      /**
                       * @notice Set the balance in a given account
                       * @dev Only the associated contract may call this.
                       * @param account The account whose value to set.
                       * @param value The new balance of the given account.
                       */
                      function setBalanceOf(address account, uint value) external onlyAssociatedContract {
                          balanceOf[account] = value;
                      }
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Proxy.sol
                  version:    1.3
                  author:     Anton Jurisevic
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxy contract that, if it does not recognise the function
                  being called on it, passes all value and call data to an
                  underlying target contract.
                  
                  This proxy has the capacity to toggle between DELEGATECALL
                  and CALL style proxy functionality.
                  
                  The former executes in the proxy's context, and so will preserve 
                  msg.sender and store data at the proxy address. The latter will not.
                  Therefore, any contract the proxy wraps in the CALL style must
                  implement the Proxyable interface, in order that it can pass msg.sender
                  into the underlying contract as the state parameter, messageSender.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract Proxy is Owned {
                      Proxyable public target;
                      bool public useDELEGATECALL;
                  
                      constructor(address _owner) public Owned(_owner) {}
                  
                      function setTarget(Proxyable _target) external onlyOwner {
                          target = _target;
                          emit TargetUpdated(_target);
                      }
                  
                      function setUseDELEGATECALL(bool value) external onlyOwner {
                          useDELEGATECALL = value;
                      }
                  
                      function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
                          external
                          onlyTarget
                      {
                          uint size = callData.length;
                          bytes memory _callData = callData;
                  
                          assembly {
                              /* The first 32 bytes of callData contain its length (as specified by the abi). 
                               * Length is assumed to be a uint256 and therefore maximum of 32 bytes
                               * in length. It is also leftpadded to be a multiple of 32 bytes.
                               * This means moving call_data across 32 bytes guarantees we correctly access
                               * the data itself. */
                              switch numTopics
                                  case 0 {
                                      log0(add(_callData, 32), size)
                                  }
                                  case 1 {
                                      log1(add(_callData, 32), size, topic1)
                                  }
                                  case 2 {
                                      log2(add(_callData, 32), size, topic1, topic2)
                                  }
                                  case 3 {
                                      log3(add(_callData, 32), size, topic1, topic2, topic3)
                                  }
                                  case 4 {
                                      log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
                                  }
                          }
                      }
                  
                      function() external payable {
                          if (useDELEGATECALL) {
                              assembly {
                                  /* Copy call data into free memory region. */
                                  let free_ptr := mload(0x40)
                                  calldatacopy(free_ptr, 0, calldatasize)
                  
                                  /* Forward all gas and call data to the target contract. */
                                  let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
                                  returndatacopy(free_ptr, 0, returndatasize)
                  
                                  /* Revert if the call failed, otherwise return the result. */
                                  if iszero(result) {
                                      revert(free_ptr, returndatasize)
                                  }
                                  return(free_ptr, returndatasize)
                              }
                          } else {
                              /* Here we are as above, but must send the messageSender explicitly 
                               * since we are using CALL rather than DELEGATECALL. */
                              target.setMessageSender(msg.sender);
                              assembly {
                                  let free_ptr := mload(0x40)
                                  calldatacopy(free_ptr, 0, calldatasize)
                  
                                  /* We must explicitly forward ether to the underlying contract as well. */
                                  let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
                                  returndatacopy(free_ptr, 0, returndatasize)
                  
                                  if iszero(result) {
                                      revert(free_ptr, returndatasize)
                                  }
                                  return(free_ptr, returndatasize)
                              }
                          }
                      }
                  
                      modifier onlyTarget {
                          require(Proxyable(msg.sender) == target, "Must be proxy target");
                          _;
                      }
                  
                      event TargetUpdated(Proxyable newTarget);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Proxyable.sol
                  version:    1.1
                  author:     Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  checked:    Mike Spain
                  approved:   Samuel Brooks
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxyable contract that works hand in hand with the Proxy contract
                  to allow for anyone to interact with the underlying contract both
                  directly and through the proxy.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  // This contract should be treated like an abstract contract
                  contract Proxyable is Owned {
                      /* The proxy this contract exists behind. */
                      Proxy public proxy;
                      Proxy public integrationProxy;
                  
                      /* The caller of the proxy, passed through to this contract.
                       * Note that every function using this member must apply the onlyProxy or
                       * optionalProxy modifiers, otherwise their invocations can use stale values. */
                      address public messageSender;
                  
                      constructor(address _proxy, address _owner) public Owned(_owner) {
                          proxy = Proxy(_proxy);
                          emit ProxyUpdated(_proxy);
                      }
                  
                      function setProxy(address _proxy) external onlyOwner {
                          proxy = Proxy(_proxy);
                          emit ProxyUpdated(_proxy);
                      }
                  
                      function setIntegrationProxy(address _integrationProxy) external onlyOwner {
                          integrationProxy = Proxy(_integrationProxy);
                      }
                  
                      function setMessageSender(address sender) external onlyProxy {
                          messageSender = sender;
                      }
                  
                      modifier onlyProxy {
                          require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
                          _;
                      }
                  
                      modifier optionalProxy {
                          if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
                              messageSender = msg.sender;
                          }
                          _;
                      }
                  
                      modifier optionalProxy_onlyOwner {
                          if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
                              messageSender = msg.sender;
                          }
                          require(messageSender == owner, "Owner only function");
                          _;
                      }
                  
                      event ProxyUpdated(address proxyAddress);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       ExternStateToken.sol
                  version:    1.3
                  author:     Anton Jurisevic
                              Dominic Romanowski
                              Kevin Brown
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A partial ERC20 token contract, designed to operate with a proxy.
                  To produce a complete ERC20 token, transfer and transferFrom
                  tokens must be implemented, using the provided _byProxy internal
                  functions.
                  This contract utilises an external state for upgradeability.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
                   */
                  contract ExternStateToken is SelfDestructible, Proxyable {
                      using SafeMath for uint;
                      using SafeDecimalMath for uint;
                  
                      /* ========== STATE VARIABLES ========== */
                  
                      /* Stores balances and allowances. */
                      TokenState public tokenState;
                  
                      /* Other ERC20 fields. */
                      string public name;
                      string public symbol;
                      uint public totalSupply;
                      uint8 public decimals;
                  
                      /**
                       * @dev Constructor.
                       * @param _proxy The proxy associated with this contract.
                       * @param _name Token's ERC20 name.
                       * @param _symbol Token's ERC20 symbol.
                       * @param _totalSupply The total supply of the token.
                       * @param _tokenState The TokenState contract address.
                       * @param _owner The owner of this contract.
                       */
                      constructor(
                          address _proxy,
                          TokenState _tokenState,
                          string _name,
                          string _symbol,
                          uint _totalSupply,
                          uint8 _decimals,
                          address _owner
                      ) public SelfDestructible(_owner) Proxyable(_proxy, _owner) {
                          tokenState = _tokenState;
                  
                          name = _name;
                          symbol = _symbol;
                          totalSupply = _totalSupply;
                          decimals = _decimals;
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      /**
                       * @notice Returns the ERC20 allowance of one party to spend on behalf of another.
                       * @param owner The party authorising spending of their funds.
                       * @param spender The party spending tokenOwner's funds.
                       */
                      function allowance(address owner, address spender) public view returns (uint) {
                          return tokenState.allowance(owner, spender);
                      }
                  
                      /**
                       * @notice Returns the ERC20 token balance of a given account.
                       */
                      function balanceOf(address account) public view returns (uint) {
                          return tokenState.balanceOf(account);
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      /**
                       * @notice Set the address of the TokenState contract.
                       * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
                       * as balances would be unreachable.
                       */
                      function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
                          tokenState = _tokenState;
                          emitTokenStateUpdated(_tokenState);
                      }
                  
                      function _internalTransfer(address from, address to, uint value) internal returns (bool) {
                          /* Disallow transfers to irretrievable-addresses. */
                          require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
                  
                          // Insufficient balance will be handled by the safe subtraction.
                          tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
                          tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
                  
                          // Emit a standard ERC20 transfer event
                          emitTransfer(from, to, value);
                  
                          return true;
                      }
                  
                      /**
                       * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
                       * the onlyProxy or optionalProxy modifiers.
                       */
                      function _transfer_byProxy(address from, address to, uint value) internal returns (bool) {
                          return _internalTransfer(from, to, value);
                      }
                  
                      /**
                       * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
                       * possessing the optionalProxy or optionalProxy modifiers.
                       */
                      function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) {
                          /* Insufficient allowance will be handled by the safe subtraction. */
                          tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
                          return _internalTransfer(from, to, value);
                      }
                  
                      /**
                       * @notice Approves spender to transfer on the message sender's behalf.
                       */
                      function approve(address spender, uint value) public optionalProxy returns (bool) {
                          address sender = messageSender;
                  
                          tokenState.setAllowance(sender, spender, value);
                          emitApproval(sender, spender, value);
                          return true;
                      }
                  
                      /* ========== EVENTS ========== */
                  
                      event Transfer(address indexed from, address indexed to, uint value);
                      bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
                  
                      function emitTransfer(address from, address to, uint value) internal {
                          proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
                      }
                  
                      event Approval(address indexed owner, address indexed spender, uint value);
                      bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
                  
                      function emitApproval(address owner, address spender, uint value) internal {
                          proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
                      }
                  
                      event TokenStateUpdated(address newTokenState);
                      bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
                  
                      function emitTokenStateUpdated(address newTokenState) internal {
                          proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
                      }
                  }
                  
                  
                  /**
                   * @title FeePool Interface
                   * @notice Abstract contract to hold public getters
                   */
                  contract IFeePool {
                      address public FEE_ADDRESS;
                      uint public exchangeFeeRate;
                  
                      function amountReceivedFromExchange(uint value) external view returns (uint);
                  
                      function amountReceivedFromTransfer(uint value) external view returns (uint);
                  
                      function recordFeePaid(uint sUSDAmount) external;
                  
                      function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external;
                  
                      function setRewardsToDistribute(uint amount) external;
                  }
                  
                  
                  /**
                   * @title SynthetixState interface contract
                   * @notice Abstract contract to hold public getters
                   */
                  contract ISynthetixState {
                      // A struct for handing values associated with an individual user's debt position
                      struct IssuanceData {
                          // Percentage of the total debt owned at the time
                          // of issuance. This number is modified by the global debt
                          // delta array. You can figure out a user's exit price and
                          // collateralisation ratio using a combination of their initial
                          // debt and the slice of global debt delta which applies to them.
                          uint initialDebtOwnership;
                          // This lets us know when (in relative terms) the user entered
                          // the debt pool so we can calculate their exit price and
                          // collateralistion ratio
                          uint debtEntryIndex;
                      }
                  
                      uint[] public debtLedger;
                      uint public issuanceRatio;
                      mapping(address => IssuanceData) public issuanceData;
                  
                      function debtLedgerLength() external view returns (uint);
                  
                      function hasIssued(address account) external view returns (bool);
                  
                      function incrementTotalIssuerCount() external;
                  
                      function decrementTotalIssuerCount() external;
                  
                      function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
                  
                      function lastDebtLedgerEntry() external view returns (uint);
                  
                      function appendDebtLedgerValue(uint value) external;
                  
                      function clearIssuanceData(address account) external;
                  }
                  
                  
                  interface ISynth {
                      function burn(address account, uint amount) external;
                  
                      function issue(address account, uint amount) external;
                  
                      function transfer(address to, uint value) external returns (bool);
                  
                      function transferFrom(address from, address to, uint value) external returns (bool);
                  
                      function transferFromAndSettle(address from, address to, uint value) external returns (bool);
                  
                      function balanceOf(address owner) external view returns (uint);
                  }
                  
                  
                  /**
                   * @title SynthetixEscrow interface
                   */
                  interface ISynthetixEscrow {
                      function balanceOf(address account) public view returns (uint);
                  
                      function appendVestingEntry(address account, uint quantity) public;
                  }
                  
                  
                  /**
                   * @title ExchangeRates interface
                   */
                  interface IExchangeRates {
                      function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
                          external
                          view
                          returns (uint);
                  
                      function rateForCurrency(bytes32 currencyKey) external view returns (uint);
                  
                      function ratesForCurrencies(bytes32[] currencyKeys) external view returns (uint[] memory);
                  
                      function rateIsStale(bytes32 currencyKey) external view returns (bool);
                  
                      function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
                  
                      function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool);
                  
                      function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
                  
                      function effectiveValueAtRound(
                          bytes32 sourceCurrencyKey,
                          uint sourceAmount,
                          bytes32 destinationCurrencyKey,
                          uint roundIdForSrc,
                          uint roundIdForDest
                      ) external view returns (uint);
                  
                      function getLastRoundIdBeforeElapsedSecs(
                          bytes32 currencyKey,
                          uint startingRoundId,
                          uint startingTimestamp,
                          uint timediff
                      ) external view returns (uint);
                  
                      function ratesAndStaleForCurrencies(bytes32[] currencyKeys) external view returns (uint[], bool);
                  
                      function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
                  }
                  
                  
                  /**
                   * @title Synthetix interface contract
                   * @notice Abstract contract to hold public getters
                   * @dev pseudo interface, actually declared as contract to hold the public getters
                   */
                  
                  
                  contract ISynthetix {
                      // ========== PUBLIC STATE VARIABLES ==========
                  
                      uint public totalSupply;
                  
                      mapping(bytes32 => Synth) public synths;
                  
                      mapping(address => bytes32) public synthsByAddress;
                  
                      // ========== PUBLIC FUNCTIONS ==========
                  
                      function balanceOf(address account) public view returns (uint);
                  
                      function transfer(address to, uint value) public returns (bool);
                  
                      function transferFrom(address from, address to, uint value) public returns (bool);
                  
                      function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
                          external
                          returns (uint amountReceived);
                  
                      function issueSynths(uint amount) external;
                  
                      function issueMaxSynths() external;
                  
                      function burnSynths(uint amount) external;
                  
                      function settle(bytes32 currencyKey) external returns (uint reclaimed, uint refunded);
                  
                      function collateralisationRatio(address issuer) public view returns (uint);
                  
                      function totalIssuedSynths(bytes32 currencyKey) public view returns (uint);
                  
                      function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) public view returns (uint);
                  
                      function debtBalanceOf(address issuer, bytes32 currencyKey) public view returns (uint);
                  
                      function remainingIssuableSynths(address issuer) public view returns (uint, uint);
                  
                      function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
                  
                      function emitSynthExchange(
                          address account,
                          bytes32 fromCurrencyKey,
                          uint fromAmount,
                          bytes32 toCurrencyKey,
                          uint toAmount,
                          address toAddress
                      ) external;
                  
                      function emitExchangeReclaim(address account, bytes32 currencyKey, uint amount) external;
                  
                      function emitExchangeRebate(address account, bytes32 currencyKey, uint amount) external;
                  }
                  
                  
                  interface IExchanger {
                      function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
                  
                      function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint);
                  
                      function settlementOwing(address account, bytes32 currencyKey)
                          external
                          view
                          returns (uint reclaimAmount, uint rebateAmount);
                  
                      function settle(address from, bytes32 currencyKey) external returns (uint reclaimed, uint refunded);
                  
                      function exchange(
                          address from,
                          bytes32 sourceCurrencyKey,
                          uint sourceAmount,
                          bytes32 destinationCurrencyKey,
                          address destinationAddress
                      ) external returns (uint amountReceived);
                  
                      function calculateAmountAfterSettlement(address from, bytes32 currencyKey, uint amount, uint refunded)
                          external
                          view
                          returns (uint amountAfterSettlement);
                  }
                  
                  
                  interface IIssuer {
                      function issueSynths(address from, uint amount) external;
                  
                      function issueMaxSynths(address from) external;
                  
                      function burnSynths(address from, uint amount) external;
                  }
                  
                  
                  contract AddressResolver is Owned {
                      mapping(bytes32 => address) public repository;
                  
                      constructor(address _owner) public Owned(_owner) {}
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function importAddresses(bytes32[] names, address[] destinations) public onlyOwner {
                          require(names.length == destinations.length, "Input lengths must match");
                  
                          for (uint i = 0; i < names.length; i++) {
                              repository[names[i]] = destinations[i];
                          }
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      function getAddress(bytes32 name) public view returns (address) {
                          return repository[name];
                      }
                  
                      function requireAndGetAddress(bytes32 name, string reason) public view returns (address) {
                          address _foundAddress = repository[name];
                          require(_foundAddress != address(0), reason);
                          return _foundAddress;
                      }
                  }
                  
                  
                  contract MixinResolver is Owned {
                      AddressResolver public resolver;
                  
                      constructor(address _owner, address _resolver) public Owned(_owner) {
                          resolver = AddressResolver(_resolver);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      function setResolver(AddressResolver _resolver) public onlyOwner {
                          resolver = _resolver;
                      }
                  }
                  
                  
                  contract Synth is ExternStateToken, MixinResolver {
                      /* ========== STATE VARIABLES ========== */
                  
                      // Currency key which identifies this Synth to the Synthetix system
                      bytes32 public currencyKey;
                  
                      uint8 public constant DECIMALS = 18;
                  
                      // Where fees are pooled in sUSD
                      address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
                  
                      /* ========== CONSTRUCTOR ========== */
                  
                      constructor(
                          address _proxy,
                          TokenState _tokenState,
                          string _tokenName,
                          string _tokenSymbol,
                          address _owner,
                          bytes32 _currencyKey,
                          uint _totalSupply,
                          address _resolver
                      )
                          public
                          ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner)
                          MixinResolver(_owner, _resolver)
                      {
                          require(_proxy != address(0), "_proxy cannot be 0");
                          require(_owner != 0, "_owner cannot be 0");
                  
                          currencyKey = _currencyKey;
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function transfer(address to, uint value) public optionalProxy returns (bool) {
                          _ensureCanTransfer(messageSender, value);
                  
                          // transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee
                          if (to == FEE_ADDRESS) {
                              return _transferToFeeAddress(to, value);
                          }
                  
                          // transfers to 0x address will be burned
                          if (to == address(0)) {
                              return _internalBurn(messageSender, value);
                          }
                  
                          return super._internalTransfer(messageSender, to, value);
                      }
                  
                      function transferAndSettle(address to, uint value) public optionalProxy returns (bool) {
                          exchanger().settle(messageSender, currencyKey);
                  
                          // Save gas instead of calling transferableSynths
                          uint balanceAfter = tokenState.balanceOf(messageSender);
                  
                          // Reduce the value to transfer if balance is insufficient after reclaimed
                          value = value > balanceAfter ? balanceAfter : value;
                  
                          return super._internalTransfer(messageSender, to, value);
                      }
                  
                      function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) {
                          _ensureCanTransfer(from, value);
                  
                          return _internalTransferFrom(from, to, value);
                      }
                  
                      function transferFromAndSettle(address from, address to, uint value) public optionalProxy returns (bool) {
                          exchanger().settle(from, currencyKey);
                  
                          // Save gas instead of calling transferableSynths
                          uint balanceAfter = tokenState.balanceOf(from);
                  
                          // Reduce the value to transfer if balance is insufficient after reclaimed
                          value = value >= balanceAfter ? balanceAfter : value;
                  
                          return _internalTransferFrom(from, to, value);
                      }
                  
                      /**
                       * @notice _transferToFeeAddress function
                       * non-sUSD synths are exchanged into sUSD via synthInitiatedExchange
                       * notify feePool to record amount as fee paid to feePool */
                      function _transferToFeeAddress(address to, uint value) internal returns (bool) {
                          uint amountInUSD;
                  
                          // sUSD can be transferred to FEE_ADDRESS directly
                          if (currencyKey == "sUSD") {
                              amountInUSD = value;
                              super._internalTransfer(messageSender, to, value);
                          } else {
                              // else exchange synth into sUSD and send to FEE_ADDRESS
                              amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS);
                          }
                  
                          // Notify feePool to record sUSD to distribute as fees
                          feePool().recordFeePaid(amountInUSD);
                  
                          return true;
                      }
                  
                      // Allow synthetix to issue a certain number of synths from an account.
                      // forward call to _internalIssue
                      function issue(address account, uint amount) external onlyInternalContracts {
                          _internalIssue(account, amount);
                      }
                  
                      // Allow synthetix or another synth contract to burn a certain number of synths from an account.
                      // forward call to _internalBurn
                      function burn(address account, uint amount) external onlyInternalContracts {
                          _internalBurn(account, amount);
                      }
                  
                      function _internalIssue(address account, uint amount) internal {
                          tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
                          totalSupply = totalSupply.add(amount);
                          emitTransfer(address(0), account, amount);
                          emitIssued(account, amount);
                      }
                  
                      function _internalBurn(address account, uint amount) internal returns (bool) {
                          tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
                          totalSupply = totalSupply.sub(amount);
                          emitTransfer(account, address(0), amount);
                          emitBurned(account, amount);
                  
                          return true;
                      }
                  
                      // Allow owner to set the total supply on import.
                      function setTotalSupply(uint amount) external optionalProxy_onlyOwner {
                          totalSupply = amount;
                      }
                  
                      /* ========== VIEWS ========== */
                      function synthetix() internal view returns (ISynthetix) {
                          return ISynthetix(resolver.requireAndGetAddress("Synthetix", "Missing Synthetix address"));
                      }
                  
                      function feePool() internal view returns (IFeePool) {
                          return IFeePool(resolver.requireAndGetAddress("FeePool", "Missing FeePool address"));
                      }
                  
                      function exchanger() internal view returns (IExchanger) {
                          return IExchanger(resolver.requireAndGetAddress("Exchanger", "Missing Exchanger address"));
                      }
                  
                      function issuer() internal view returns (IIssuer) {
                          return IIssuer(resolver.requireAndGetAddress("Issuer", "Missing Issuer address"));
                      }
                  
                      function _ensureCanTransfer(address from, uint value) internal view {
                          require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period");
                          require(transferableSynths(from) >= value, "Transfer requires settle");
                      }
                  
                      function transferableSynths(address account) public view returns (uint) {
                          (uint reclaimAmount, ) = exchanger().settlementOwing(account, currencyKey);
                  
                          // Note: ignoring rebate amount here because a settle() is required in order to
                          // allow the transfer to actually work
                  
                          uint balance = tokenState.balanceOf(account);
                  
                          if (reclaimAmount > balance) {
                              return 0;
                          } else {
                              return balance.sub(reclaimAmount);
                          }
                      }
                  
                      /* ========== INTERNAL FUNCTIONS ========== */
                  
                      function _internalTransferFrom(address from, address to, uint value) internal returns (bool) {
                          // Skip allowance update in case of infinite allowance
                          if (tokenState.allowance(from, messageSender) != uint(-1)) {
                              // Reduce the allowance by the amount we're transferring.
                              // The safeSub call will handle an insufficient allowance.
                              tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
                          }
                  
                          return super._internalTransfer(from, to, value);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      modifier onlyInternalContracts() {
                          bool isSynthetix = msg.sender == address(synthetix());
                          bool isFeePool = msg.sender == address(feePool());
                          bool isExchanger = msg.sender == address(exchanger());
                          bool isIssuer = msg.sender == address(issuer());
                  
                          require(
                              isSynthetix || isFeePool || isExchanger || isIssuer,
                              "Only Synthetix, FeePool, Exchanger or Issuer contracts allowed"
                          );
                          _;
                      }
                  
                      /* ========== EVENTS ========== */
                      event Issued(address indexed account, uint value);
                      bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)");
                  
                      function emitIssued(address account, uint value) internal {
                          proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
                      }
                  
                      event Burned(address indexed account, uint value);
                      bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)");
                  
                      function emitBurned(address account, uint value) internal {
                          proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
                      }
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       MultiCollateralSynth.sol
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  MultiCollateralSynth synths are a subclass of Synth that allows the
                  multiCollateral contract to issue and burn synths.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract MultiCollateralSynth is Synth {
                      /* ========== CONSTRUCTOR ========== */
                      bytes32 public multiCollateralKey;
                  
                      constructor(
                          address _proxy,
                          TokenState _tokenState,
                          string _tokenName,
                          string _tokenSymbol,
                          address _owner,
                          bytes32 _currencyKey,
                          uint _totalSupply,
                          address _resolver,
                          bytes32 _multiCollateralKey
                      ) public Synth(_proxy, _tokenState, _tokenName, _tokenSymbol, _owner, _currencyKey, _totalSupply, _resolver) {
                          multiCollateralKey = _multiCollateralKey;
                      }
                  
                      /* ========== VIEWS ======================= */
                  
                      function multiCollateral() internal view returns (address) {
                          address _foundAddress = resolver.getAddress(multiCollateralKey);
                          require(_foundAddress != address(0), "Resolver is missing multiCollateral address");
                          return _foundAddress;
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      /**
                       * @notice Function that allows multi Collateral to issue a certain number of synths from an account.
                       * @param account Account to issue synths to
                       * @param amount Number of synths
                       */
                      function issue(address account, uint amount) external onlyInternalContracts {
                          super._internalIssue(account, amount);
                      }
                  
                      /**
                       * @notice Function that allows multi Collateral to burn a certain number of synths from an account.
                       * @param account Account to burn synths from
                       * @param amount Number of synths
                       */
                      function burn(address account, uint amount) external onlyInternalContracts {
                          super._internalBurn(account, amount);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      // Contracts directly interacting with multiCollateralSynth to issue and burn
                      modifier onlyInternalContracts() {
                          bool isSynthetix = msg.sender == address(synthetix());
                          bool isFeePool = msg.sender == address(feePool());
                          bool isExchanger = msg.sender == address(exchanger());
                          bool isIssuer = msg.sender == address(issuer());
                          bool isMultiCollateral = msg.sender == address(multiCollateral());
                  
                          require(
                              isSynthetix || isFeePool || isExchanger || isIssuer || isMultiCollateral,
                              "Only Synthetix, FeePool, Exchanger, Issuer or MultiCollateral contracts allowed"
                          );
                          _;
                      }
                  }
                  
                  
                      

                  File 5 of 8: TokenState
                  /* ===============================================
                  * Flattened with Solidifier by Coinage
                  * 
                  * https://solidifier.coina.ge
                  * ===============================================
                  */
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Owned.sol
                  version:    1.1
                  author:     Anton Jurisevic
                              Dominic Romanowski
                  
                  date:       2018-2-26
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  An Owned contract, to be inherited by other contracts.
                  Requires its owner to be explicitly set in the constructor.
                  Provides an onlyOwner access modifier.
                  
                  To change owner, the current owner must nominate the next owner,
                  who then has to accept the nomination. The nomination can be
                  cancelled before it is accepted by the new owner by having the
                  previous owner change the nomination (setting it to 0).
                  
                  -----------------------------------------------------------------
                  */
                  
                  pragma solidity 0.4.25;
                  
                  /**
                   * @title A contract with an owner.
                   * @notice Contract ownership can be transferred by first nominating the new owner,
                   * who must then accept the ownership, which prevents accidental incorrect ownership transfers.
                   */
                  contract Owned {
                      address public owner;
                      address public nominatedOwner;
                  
                      /**
                       * @dev Owned Constructor
                       */
                      constructor(address _owner)
                          public
                      {
                          require(_owner != address(0), "Owner address cannot be 0");
                          owner = _owner;
                          emit OwnerChanged(address(0), _owner);
                      }
                  
                      /**
                       * @notice Nominate a new owner of this contract.
                       * @dev Only the current owner may nominate a new owner.
                       */
                      function nominateNewOwner(address _owner)
                          external
                          onlyOwner
                      {
                          nominatedOwner = _owner;
                          emit OwnerNominated(_owner);
                      }
                  
                      /**
                       * @notice Accept the nomination to be owner.
                       */
                      function acceptOwnership()
                          external
                      {
                          require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
                          emit OwnerChanged(owner, nominatedOwner);
                          owner = nominatedOwner;
                          nominatedOwner = address(0);
                      }
                  
                      modifier onlyOwner
                      {
                          require(msg.sender == owner, "Only the contract owner may perform this action");
                          _;
                      }
                  
                      event OwnerNominated(address newOwner);
                      event OwnerChanged(address oldOwner, address newOwner);
                  }
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       State.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract State is Owned {
                      // the address of the contract that can modify variables
                      // this can only be changed by the owner of this contract
                      address public associatedContract;
                  
                  
                      constructor(address _owner, address _associatedContract)
                          Owned(_owner)
                          public
                      {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      // Change the associated contract to a new address
                      function setAssociatedContract(address _associatedContract)
                          external
                          onlyOwner
                      {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      modifier onlyAssociatedContract
                      {
                          require(msg.sender == associatedContract, "Only the associated contract can perform this action");
                          _;
                      }
                  
                      /* ========== EVENTS ========== */
                  
                      event AssociatedContractUpdated(address associatedContract);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       TokenState.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A contract that holds the state of an ERC20 compliant token.
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title ERC20 Token State
                   * @notice Stores balance information of an ERC20 token contract.
                   */
                  contract TokenState is State {
                  
                      /* ERC20 fields. */
                      mapping(address => uint) public balanceOf;
                      mapping(address => mapping(address => uint)) public allowance;
                  
                      /**
                       * @dev Constructor
                       * @param _owner The address which controls this contract.
                       * @param _associatedContract The ERC20 contract whose state this composes.
                       */
                      constructor(address _owner, address _associatedContract)
                          State(_owner, _associatedContract)
                          public
                      {}
                  
                      /* ========== SETTERS ========== */
                  
                      /**
                       * @notice Set ERC20 allowance.
                       * @dev Only the associated contract may call this.
                       * @param tokenOwner The authorising party.
                       * @param spender The authorised party.
                       * @param value The total value the authorised party may spend on the
                       * authorising party's behalf.
                       */
                      function setAllowance(address tokenOwner, address spender, uint value)
                          external
                          onlyAssociatedContract
                      {
                          allowance[tokenOwner][spender] = value;
                      }
                  
                      /**
                       * @notice Set the balance in a given account
                       * @dev Only the associated contract may call this.
                       * @param account The account whose value to set.
                       * @param value The new balance of the given account.
                       */
                      function setBalanceOf(address account, uint value)
                          external
                          onlyAssociatedContract
                      {
                          balanceOf[account] = value;
                      }
                  }
                  
                  

                  File 6 of 8: AddressResolver
                  /*
                  * Synthetix - AddressResolver.sol
                  *
                  * https://github.com/Synthetixio/synthetix
                  * https://synthetix.io
                  *
                  * MIT License
                  * ===========
                  *
                  * Copyright (c) 2020 Synthetix
                  *
                  * 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
                  */
                      
                  /* ===============================================
                  * Flattened with Solidifier by Coinage
                  * 
                  * https://solidifier.coina.ge
                  * ===============================================
                  */
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Owned.sol
                  version:    1.1
                  author:     Anton Jurisevic
                              Dominic Romanowski
                  
                  date:       2018-2-26
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  An Owned contract, to be inherited by other contracts.
                  Requires its owner to be explicitly set in the constructor.
                  Provides an onlyOwner access modifier.
                  
                  To change owner, the current owner must nominate the next owner,
                  who then has to accept the nomination. The nomination can be
                  cancelled before it is accepted by the new owner by having the
                  previous owner change the nomination (setting it to 0).
                  
                  -----------------------------------------------------------------
                  */
                  
                  pragma solidity 0.4.25;
                  
                  
                  /**
                   * @title A contract with an owner.
                   * @notice Contract ownership can be transferred by first nominating the new owner,
                   * who must then accept the ownership, which prevents accidental incorrect ownership transfers.
                   */
                  contract Owned {
                      address public owner;
                      address public nominatedOwner;
                  
                      /**
                       * @dev Owned Constructor
                       */
                      constructor(address _owner) public {
                          require(_owner != address(0), "Owner address cannot be 0");
                          owner = _owner;
                          emit OwnerChanged(address(0), _owner);
                      }
                  
                      /**
                       * @notice Nominate a new owner of this contract.
                       * @dev Only the current owner may nominate a new owner.
                       */
                      function nominateNewOwner(address _owner) external onlyOwner {
                          nominatedOwner = _owner;
                          emit OwnerNominated(_owner);
                      }
                  
                      /**
                       * @notice Accept the nomination to be owner.
                       */
                      function acceptOwnership() external {
                          require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
                          emit OwnerChanged(owner, nominatedOwner);
                          owner = nominatedOwner;
                          nominatedOwner = address(0);
                      }
                  
                      modifier onlyOwner {
                          require(msg.sender == owner, "Only the contract owner may perform this action");
                          _;
                      }
                  
                      event OwnerNominated(address newOwner);
                      event OwnerChanged(address oldOwner, address newOwner);
                  }
                  
                  
                  contract AddressResolver is Owned {
                      mapping(bytes32 => address) public repository;
                  
                      constructor(address _owner) public Owned(_owner) {}
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function importAddresses(bytes32[] names, address[] destinations) public onlyOwner {
                          require(names.length == destinations.length, "Input lengths must match");
                  
                          for (uint i = 0; i < names.length; i++) {
                              repository[names[i]] = destinations[i];
                          }
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      function getAddress(bytes32 name) public view returns (address) {
                          return repository[name];
                      }
                  
                      function requireAndGetAddress(bytes32 name, string reason) public view returns (address) {
                          address _foundAddress = repository[name];
                          require(_foundAddress != address(0), reason);
                          return _foundAddress;
                      }
                  }
                  
                  
                      

                  File 7 of 8: Exchanger
                  /*
                  * Synthetix - Exchanger.sol
                  *
                  * https://github.com/Synthetixio/synthetix
                  * https://synthetix.io
                  *
                  * MIT License
                  * ===========
                  *
                  * Copyright (c) 2020 Synthetix
                  *
                  * 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
                  */
                      
                  /* ===============================================
                  * Flattened with Solidifier by Coinage
                  * 
                  * https://solidifier.coina.ge
                  * ===============================================
                  */
                  
                  
                  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, "SafeMath.mul Error");
                  
                      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, "SafeMath.div Error"); // 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, "SafeMath.sub Error");
                      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, "SafeMath.add Error");
                  
                      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, "SafeMath.mod Error");
                      return a % b;
                    }
                  }
                  
                  
                  /*
                  
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       SafeDecimalMath.sol
                  version:    2.0
                  author:     Kevin Brown
                              Gavin Conway
                  date:       2018-10-18
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A library providing safe mathematical operations for division and
                  multiplication with the capability to round or truncate the results
                  to the nearest increment. Operations can return a standard precision
                  or high precision decimal. High precision decimals are useful for
                  example when attempting to calculate percentages or fractions
                  accurately.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title Safely manipulate unsigned fixed-point decimals at a given precision level.
                   * @dev Functions accepting uints in this contract and derived contracts
                   * are taken to be such fixed point decimals of a specified precision (either standard
                   * or high).
                   */
                  library SafeDecimalMath {
                      using SafeMath for uint;
                  
                      /* Number of decimal places in the representations. */
                      uint8 public constant decimals = 18;
                      uint8 public constant highPrecisionDecimals = 27;
                  
                      /* The number representing 1.0. */
                      uint public constant UNIT = 10**uint(decimals);
                  
                      /* The number representing 1.0 for higher fidelity numbers. */
                      uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
                      uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
                  
                      /** 
                       * @return Provides an interface to UNIT.
                       */
                      function unit() external pure returns (uint) {
                          return UNIT;
                      }
                  
                      /** 
                       * @return Provides an interface to PRECISE_UNIT.
                       */
                      function preciseUnit() external pure returns (uint) {
                          return PRECISE_UNIT;
                      }
                  
                      /**
                       * @return The result of multiplying x and y, interpreting the operands as fixed-point
                       * decimals.
                       * 
                       * @dev A unit factor is divided out after the product of x and y is evaluated,
                       * so that product must be less than 2**256. As this is an integer division,
                       * the internal division always rounds down. This helps save on gas. Rounding
                       * is more expensive on gas.
                       */
                      function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
                          /* Divide by UNIT to remove the extra factor introduced by the product. */
                          return x.mul(y) / UNIT;
                      }
                  
                      /**
                       * @return The result of safely multiplying x and y, interpreting the operands
                       * as fixed-point decimals of the specified precision unit.
                       *
                       * @dev The operands should be in the form of a the specified unit factor which will be
                       * divided out after the product of x and y is evaluated, so that product must be
                       * less than 2**256.
                       *
                       * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
                       * Rounding is useful when you need to retain fidelity for small decimal numbers
                       * (eg. small fractions or percentages).
                       */
                      function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) {
                          /* Divide by UNIT to remove the extra factor introduced by the product. */
                          uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
                  
                          if (quotientTimesTen % 10 >= 5) {
                              quotientTimesTen += 10;
                          }
                  
                          return quotientTimesTen / 10;
                      }
                  
                      /**
                       * @return The result of safely multiplying x and y, interpreting the operands
                       * as fixed-point decimals of a precise unit.
                       *
                       * @dev The operands should be in the precise unit factor which will be
                       * divided out after the product of x and y is evaluated, so that product must be
                       * less than 2**256.
                       *
                       * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
                       * Rounding is useful when you need to retain fidelity for small decimal numbers
                       * (eg. small fractions or percentages).
                       */
                      function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
                          return _multiplyDecimalRound(x, y, PRECISE_UNIT);
                      }
                  
                      /**
                       * @return The result of safely multiplying x and y, interpreting the operands
                       * as fixed-point decimals of a standard unit.
                       *
                       * @dev The operands should be in the standard unit factor which will be
                       * divided out after the product of x and y is evaluated, so that product must be
                       * less than 2**256.
                       *
                       * Unlike multiplyDecimal, this function rounds the result to the nearest increment.
                       * Rounding is useful when you need to retain fidelity for small decimal numbers
                       * (eg. small fractions or percentages).
                       */
                      function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
                          return _multiplyDecimalRound(x, y, UNIT);
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is a high
                       * precision decimal.
                       * 
                       * @dev y is divided after the product of x and the standard precision unit
                       * is evaluated, so the product of x and UNIT must be less than 2**256. As
                       * this is an integer division, the result is always rounded down.
                       * This helps save on gas. Rounding is more expensive on gas.
                       */
                      function divideDecimal(uint x, uint y) internal pure returns (uint) {
                          /* Reintroduce the UNIT factor that will be divided out by y. */
                          return x.mul(UNIT).div(y);
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is as a rounded
                       * decimal in the precision unit specified in the parameter.
                       *
                       * @dev y is divided after the product of x and the specified precision unit
                       * is evaluated, so the product of x and the specified precision unit must
                       * be less than 2**256. The result is rounded to the nearest increment.
                       */
                      function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) {
                          uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
                  
                          if (resultTimesTen % 10 >= 5) {
                              resultTimesTen += 10;
                          }
                  
                          return resultTimesTen / 10;
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is as a rounded
                       * standard precision decimal.
                       *
                       * @dev y is divided after the product of x and the standard precision unit
                       * is evaluated, so the product of x and the standard precision unit must
                       * be less than 2**256. The result is rounded to the nearest increment.
                       */
                      function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
                          return _divideDecimalRound(x, y, UNIT);
                      }
                  
                      /**
                       * @return The result of safely dividing x and y. The return value is as a rounded
                       * high precision decimal.
                       *
                       * @dev y is divided after the product of x and the high precision unit
                       * is evaluated, so the product of x and the high precision unit must
                       * be less than 2**256. The result is rounded to the nearest increment.
                       */
                      function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
                          return _divideDecimalRound(x, y, PRECISE_UNIT);
                      }
                  
                      /**
                       * @dev Convert a standard decimal representation to a high precision one.
                       */
                      function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
                          return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
                      }
                  
                      /**
                       * @dev Convert a high precision decimal to a standard decimal representation.
                       */
                      function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
                          uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
                  
                          if (quotientTimesTen % 10 >= 5) {
                              quotientTimesTen += 10;
                          }
                  
                          return quotientTimesTen / 10;
                      }
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Owned.sol
                  version:    1.1
                  author:     Anton Jurisevic
                              Dominic Romanowski
                  
                  date:       2018-2-26
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  An Owned contract, to be inherited by other contracts.
                  Requires its owner to be explicitly set in the constructor.
                  Provides an onlyOwner access modifier.
                  
                  To change owner, the current owner must nominate the next owner,
                  who then has to accept the nomination. The nomination can be
                  cancelled before it is accepted by the new owner by having the
                  previous owner change the nomination (setting it to 0).
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title A contract with an owner.
                   * @notice Contract ownership can be transferred by first nominating the new owner,
                   * who must then accept the ownership, which prevents accidental incorrect ownership transfers.
                   */
                  contract Owned {
                      address public owner;
                      address public nominatedOwner;
                  
                      /**
                       * @dev Owned Constructor
                       */
                      constructor(address _owner) public {
                          require(_owner != address(0), "Owner address cannot be 0");
                          owner = _owner;
                          emit OwnerChanged(address(0), _owner);
                      }
                  
                      /**
                       * @notice Nominate a new owner of this contract.
                       * @dev Only the current owner may nominate a new owner.
                       */
                      function nominateNewOwner(address _owner) external onlyOwner {
                          nominatedOwner = _owner;
                          emit OwnerNominated(_owner);
                      }
                  
                      /**
                       * @notice Accept the nomination to be owner.
                       */
                      function acceptOwnership() external {
                          require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
                          emit OwnerChanged(owner, nominatedOwner);
                          owner = nominatedOwner;
                          nominatedOwner = address(0);
                      }
                  
                      modifier onlyOwner {
                          require(msg.sender == owner, "Only the contract owner may perform this action");
                          _;
                      }
                  
                      event OwnerNominated(address newOwner);
                      event OwnerChanged(address oldOwner, address newOwner);
                  }
                  
                  
                  contract AddressResolver is Owned {
                      mapping(bytes32 => address) public repository;
                  
                      constructor(address _owner) public Owned(_owner) {}
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function importAddresses(bytes32[] names, address[] destinations) public onlyOwner {
                          require(names.length == destinations.length, "Input lengths must match");
                  
                          for (uint i = 0; i < names.length; i++) {
                              repository[names[i]] = destinations[i];
                          }
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      function getAddress(bytes32 name) public view returns (address) {
                          return repository[name];
                      }
                  
                      function requireAndGetAddress(bytes32 name, string reason) public view returns (address) {
                          address _foundAddress = repository[name];
                          require(_foundAddress != address(0), reason);
                          return _foundAddress;
                      }
                  }
                  
                  
                  contract MixinResolver is Owned {
                      AddressResolver public resolver;
                  
                      constructor(address _owner, address _resolver) public Owned(_owner) {
                          resolver = AddressResolver(_resolver);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      function setResolver(AddressResolver _resolver) public onlyOwner {
                          resolver = _resolver;
                      }
                  }
                  
                  
                  interface IExchangeState {
                      function appendExchangeEntry(
                          address account,
                          bytes32 src,
                          uint amount,
                          bytes32 dest,
                          uint amountReceived,
                          uint exchangeFeeRate,
                          uint timestamp,
                          uint roundIdForSrc,
                          uint roundIdForDest
                      ) external;
                  
                      function removeEntries(address account, bytes32 currencyKey) external;
                  
                      function getLengthOfEntries(address account, bytes32 currencyKey) external view returns (uint);
                  
                      function getEntryAt(address account, bytes32 currencyKey, uint index)
                          external
                          view
                          returns (
                              bytes32 src,
                              uint amount,
                              bytes32 dest,
                              uint amountReceived,
                              uint exchangeFeeRate,
                              uint timestamp,
                              uint roundIdForSrc,
                              uint roundIdForDest
                          );
                  
                      function getMaxTimestamp(address account, bytes32 currencyKey) external view returns (uint);
                  }
                  
                  
                  /**
                   * @title ExchangeRates interface
                   */
                  interface IExchangeRates {
                      function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
                          external
                          view
                          returns (uint);
                  
                      function rateForCurrency(bytes32 currencyKey) external view returns (uint);
                  
                      function ratesForCurrencies(bytes32[] currencyKeys) external view returns (uint[] memory);
                  
                      function rateIsStale(bytes32 currencyKey) external view returns (bool);
                  
                      function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
                  
                      function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool);
                  
                      function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
                  
                      function effectiveValueAtRound(
                          bytes32 sourceCurrencyKey,
                          uint sourceAmount,
                          bytes32 destinationCurrencyKey,
                          uint roundIdForSrc,
                          uint roundIdForDest
                      ) external view returns (uint);
                  
                      function getLastRoundIdBeforeElapsedSecs(
                          bytes32 currencyKey,
                          uint startingRoundId,
                          uint startingTimestamp,
                          uint timediff
                      ) external view returns (uint);
                  
                      function ratesAndStaleForCurrencies(bytes32[] currencyKeys) external view returns (uint[], bool);
                  
                      function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
                  }
                  
                  
                  /**
                   * @title SynthetixState interface contract
                   * @notice Abstract contract to hold public getters
                   */
                  contract ISynthetixState {
                      // A struct for handing values associated with an individual user's debt position
                      struct IssuanceData {
                          // Percentage of the total debt owned at the time
                          // of issuance. This number is modified by the global debt
                          // delta array. You can figure out a user's exit price and
                          // collateralisation ratio using a combination of their initial
                          // debt and the slice of global debt delta which applies to them.
                          uint initialDebtOwnership;
                          // This lets us know when (in relative terms) the user entered
                          // the debt pool so we can calculate their exit price and
                          // collateralistion ratio
                          uint debtEntryIndex;
                      }
                  
                      uint[] public debtLedger;
                      uint public issuanceRatio;
                      mapping(address => IssuanceData) public issuanceData;
                  
                      function debtLedgerLength() external view returns (uint);
                  
                      function hasIssued(address account) external view returns (bool);
                  
                      function incrementTotalIssuerCount() external;
                  
                      function decrementTotalIssuerCount() external;
                  
                      function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
                  
                      function lastDebtLedgerEntry() external view returns (uint);
                  
                      function appendDebtLedgerValue(uint value) external;
                  
                      function clearIssuanceData(address account) external;
                  }
                  
                  
                  interface ISynth {
                      function burn(address account, uint amount) external;
                  
                      function issue(address account, uint amount) external;
                  
                      function transfer(address to, uint value) external returns (bool);
                  
                      function transferFrom(address from, address to, uint value) external returns (bool);
                  
                      function transferFromAndSettle(address from, address to, uint value) external returns (bool);
                  
                      function balanceOf(address owner) external view returns (uint);
                  }
                  
                  
                  /**
                   * @title SynthetixEscrow interface
                   */
                  interface ISynthetixEscrow {
                      function balanceOf(address account) public view returns (uint);
                  
                      function appendVestingEntry(address account, uint quantity) public;
                  }
                  
                  
                  /**
                   * @title FeePool Interface
                   * @notice Abstract contract to hold public getters
                   */
                  contract IFeePool {
                      address public FEE_ADDRESS;
                      uint public exchangeFeeRate;
                  
                      function amountReceivedFromExchange(uint value) external view returns (uint);
                  
                      function amountReceivedFromTransfer(uint value) external view returns (uint);
                  
                      function recordFeePaid(uint sUSDAmount) external;
                  
                      function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external;
                  
                      function setRewardsToDistribute(uint amount) external;
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       SelfDestructible.sol
                  version:    1.2
                  author:     Anton Jurisevic
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  This contract allows an inheriting contract to be destroyed after
                  its owner indicates an intention and then waits for a period
                  without changing their mind. All ether contained in the contract
                  is forwarded to a nominated beneficiary upon destruction.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title A contract that can be destroyed by its owner after a delay elapses.
                   */
                  contract SelfDestructible is Owned {
                      uint public initiationTime;
                      bool public selfDestructInitiated;
                      address public selfDestructBeneficiary;
                      uint public constant SELFDESTRUCT_DELAY = 4 weeks;
                  
                      /**
                       * @dev Constructor
                       * @param _owner The account which controls this contract.
                       */
                      constructor(address _owner) public Owned(_owner) {
                          require(_owner != address(0), "Owner must not be zero");
                          selfDestructBeneficiary = _owner;
                          emit SelfDestructBeneficiaryUpdated(_owner);
                      }
                  
                      /**
                       * @notice Set the beneficiary address of this contract.
                       * @dev Only the contract owner may call this. The provided beneficiary must be non-null.
                       * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
                       */
                      function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner {
                          require(_beneficiary != address(0), "Beneficiary must not be zero");
                          selfDestructBeneficiary = _beneficiary;
                          emit SelfDestructBeneficiaryUpdated(_beneficiary);
                      }
                  
                      /**
                       * @notice Begin the self-destruction counter of this contract.
                       * Once the delay has elapsed, the contract may be self-destructed.
                       * @dev Only the contract owner may call this.
                       */
                      function initiateSelfDestruct() external onlyOwner {
                          initiationTime = now;
                          selfDestructInitiated = true;
                          emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
                      }
                  
                      /**
                       * @notice Terminate and reset the self-destruction timer.
                       * @dev Only the contract owner may call this.
                       */
                      function terminateSelfDestruct() external onlyOwner {
                          initiationTime = 0;
                          selfDestructInitiated = false;
                          emit SelfDestructTerminated();
                      }
                  
                      /**
                       * @notice If the self-destruction delay has elapsed, destroy this contract and
                       * remit any ether it owns to the beneficiary address.
                       * @dev Only the contract owner may call this.
                       */
                      function selfDestruct() external onlyOwner {
                          require(selfDestructInitiated, "Self Destruct not yet initiated");
                          require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met");
                          address beneficiary = selfDestructBeneficiary;
                          emit SelfDestructed(beneficiary);
                          selfdestruct(beneficiary);
                      }
                  
                      event SelfDestructTerminated();
                      event SelfDestructed(address beneficiary);
                      event SelfDestructInitiated(uint selfDestructDelay);
                      event SelfDestructBeneficiaryUpdated(address newBeneficiary);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       State.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract State is Owned {
                      // the address of the contract that can modify variables
                      // this can only be changed by the owner of this contract
                      address public associatedContract;
                  
                      constructor(address _owner, address _associatedContract) public Owned(_owner) {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      // Change the associated contract to a new address
                      function setAssociatedContract(address _associatedContract) external onlyOwner {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      modifier onlyAssociatedContract {
                          require(msg.sender == associatedContract, "Only the associated contract can perform this action");
                          _;
                      }
                  
                      /* ========== EVENTS ========== */
                  
                      event AssociatedContractUpdated(address associatedContract);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       TokenState.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A contract that holds the state of an ERC20 compliant token.
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title ERC20 Token State
                   * @notice Stores balance information of an ERC20 token contract.
                   */
                  contract TokenState is State {
                      /* ERC20 fields. */
                      mapping(address => uint) public balanceOf;
                      mapping(address => mapping(address => uint)) public allowance;
                  
                      /**
                       * @dev Constructor
                       * @param _owner The address which controls this contract.
                       * @param _associatedContract The ERC20 contract whose state this composes.
                       */
                      constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
                  
                      /* ========== SETTERS ========== */
                  
                      /**
                       * @notice Set ERC20 allowance.
                       * @dev Only the associated contract may call this.
                       * @param tokenOwner The authorising party.
                       * @param spender The authorised party.
                       * @param value The total value the authorised party may spend on the
                       * authorising party's behalf.
                       */
                      function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract {
                          allowance[tokenOwner][spender] = value;
                      }
                  
                      /**
                       * @notice Set the balance in a given account
                       * @dev Only the associated contract may call this.
                       * @param account The account whose value to set.
                       * @param value The new balance of the given account.
                       */
                      function setBalanceOf(address account, uint value) external onlyAssociatedContract {
                          balanceOf[account] = value;
                      }
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Proxy.sol
                  version:    1.3
                  author:     Anton Jurisevic
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxy contract that, if it does not recognise the function
                  being called on it, passes all value and call data to an
                  underlying target contract.
                  
                  This proxy has the capacity to toggle between DELEGATECALL
                  and CALL style proxy functionality.
                  
                  The former executes in the proxy's context, and so will preserve 
                  msg.sender and store data at the proxy address. The latter will not.
                  Therefore, any contract the proxy wraps in the CALL style must
                  implement the Proxyable interface, in order that it can pass msg.sender
                  into the underlying contract as the state parameter, messageSender.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract Proxy is Owned {
                      Proxyable public target;
                      bool public useDELEGATECALL;
                  
                      constructor(address _owner) public Owned(_owner) {}
                  
                      function setTarget(Proxyable _target) external onlyOwner {
                          target = _target;
                          emit TargetUpdated(_target);
                      }
                  
                      function setUseDELEGATECALL(bool value) external onlyOwner {
                          useDELEGATECALL = value;
                      }
                  
                      function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
                          external
                          onlyTarget
                      {
                          uint size = callData.length;
                          bytes memory _callData = callData;
                  
                          assembly {
                              /* The first 32 bytes of callData contain its length (as specified by the abi). 
                               * Length is assumed to be a uint256 and therefore maximum of 32 bytes
                               * in length. It is also leftpadded to be a multiple of 32 bytes.
                               * This means moving call_data across 32 bytes guarantees we correctly access
                               * the data itself. */
                              switch numTopics
                                  case 0 {
                                      log0(add(_callData, 32), size)
                                  }
                                  case 1 {
                                      log1(add(_callData, 32), size, topic1)
                                  }
                                  case 2 {
                                      log2(add(_callData, 32), size, topic1, topic2)
                                  }
                                  case 3 {
                                      log3(add(_callData, 32), size, topic1, topic2, topic3)
                                  }
                                  case 4 {
                                      log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
                                  }
                          }
                      }
                  
                      function() external payable {
                          if (useDELEGATECALL) {
                              assembly {
                                  /* Copy call data into free memory region. */
                                  let free_ptr := mload(0x40)
                                  calldatacopy(free_ptr, 0, calldatasize)
                  
                                  /* Forward all gas and call data to the target contract. */
                                  let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
                                  returndatacopy(free_ptr, 0, returndatasize)
                  
                                  /* Revert if the call failed, otherwise return the result. */
                                  if iszero(result) {
                                      revert(free_ptr, returndatasize)
                                  }
                                  return(free_ptr, returndatasize)
                              }
                          } else {
                              /* Here we are as above, but must send the messageSender explicitly 
                               * since we are using CALL rather than DELEGATECALL. */
                              target.setMessageSender(msg.sender);
                              assembly {
                                  let free_ptr := mload(0x40)
                                  calldatacopy(free_ptr, 0, calldatasize)
                  
                                  /* We must explicitly forward ether to the underlying contract as well. */
                                  let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
                                  returndatacopy(free_ptr, 0, returndatasize)
                  
                                  if iszero(result) {
                                      revert(free_ptr, returndatasize)
                                  }
                                  return(free_ptr, returndatasize)
                              }
                          }
                      }
                  
                      modifier onlyTarget {
                          require(Proxyable(msg.sender) == target, "Must be proxy target");
                          _;
                      }
                  
                      event TargetUpdated(Proxyable newTarget);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Proxyable.sol
                  version:    1.1
                  author:     Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  checked:    Mike Spain
                  approved:   Samuel Brooks
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A proxyable contract that works hand in hand with the Proxy contract
                  to allow for anyone to interact with the underlying contract both
                  directly and through the proxy.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  // This contract should be treated like an abstract contract
                  contract Proxyable is Owned {
                      /* The proxy this contract exists behind. */
                      Proxy public proxy;
                      Proxy public integrationProxy;
                  
                      /* The caller of the proxy, passed through to this contract.
                       * Note that every function using this member must apply the onlyProxy or
                       * optionalProxy modifiers, otherwise their invocations can use stale values. */
                      address public messageSender;
                  
                      constructor(address _proxy, address _owner) public Owned(_owner) {
                          proxy = Proxy(_proxy);
                          emit ProxyUpdated(_proxy);
                      }
                  
                      function setProxy(address _proxy) external onlyOwner {
                          proxy = Proxy(_proxy);
                          emit ProxyUpdated(_proxy);
                      }
                  
                      function setIntegrationProxy(address _integrationProxy) external onlyOwner {
                          integrationProxy = Proxy(_integrationProxy);
                      }
                  
                      function setMessageSender(address sender) external onlyProxy {
                          messageSender = sender;
                      }
                  
                      modifier onlyProxy {
                          require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
                          _;
                      }
                  
                      modifier optionalProxy {
                          if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
                              messageSender = msg.sender;
                          }
                          _;
                      }
                  
                      modifier optionalProxy_onlyOwner {
                          if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
                              messageSender = msg.sender;
                          }
                          require(messageSender == owner, "Owner only function");
                          _;
                      }
                  
                      event ProxyUpdated(address proxyAddress);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       ExternStateToken.sol
                  version:    1.3
                  author:     Anton Jurisevic
                              Dominic Romanowski
                              Kevin Brown
                  
                  date:       2018-05-29
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  A partial ERC20 token contract, designed to operate with a proxy.
                  To produce a complete ERC20 token, transfer and transferFrom
                  tokens must be implemented, using the provided _byProxy internal
                  functions.
                  This contract utilises an external state for upgradeability.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  /**
                   * @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
                   */
                  contract ExternStateToken is SelfDestructible, Proxyable {
                      using SafeMath for uint;
                      using SafeDecimalMath for uint;
                  
                      /* ========== STATE VARIABLES ========== */
                  
                      /* Stores balances and allowances. */
                      TokenState public tokenState;
                  
                      /* Other ERC20 fields. */
                      string public name;
                      string public symbol;
                      uint public totalSupply;
                      uint8 public decimals;
                  
                      /**
                       * @dev Constructor.
                       * @param _proxy The proxy associated with this contract.
                       * @param _name Token's ERC20 name.
                       * @param _symbol Token's ERC20 symbol.
                       * @param _totalSupply The total supply of the token.
                       * @param _tokenState The TokenState contract address.
                       * @param _owner The owner of this contract.
                       */
                      constructor(
                          address _proxy,
                          TokenState _tokenState,
                          string _name,
                          string _symbol,
                          uint _totalSupply,
                          uint8 _decimals,
                          address _owner
                      ) public SelfDestructible(_owner) Proxyable(_proxy, _owner) {
                          tokenState = _tokenState;
                  
                          name = _name;
                          symbol = _symbol;
                          totalSupply = _totalSupply;
                          decimals = _decimals;
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      /**
                       * @notice Returns the ERC20 allowance of one party to spend on behalf of another.
                       * @param owner The party authorising spending of their funds.
                       * @param spender The party spending tokenOwner's funds.
                       */
                      function allowance(address owner, address spender) public view returns (uint) {
                          return tokenState.allowance(owner, spender);
                      }
                  
                      /**
                       * @notice Returns the ERC20 token balance of a given account.
                       */
                      function balanceOf(address account) public view returns (uint) {
                          return tokenState.balanceOf(account);
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      /**
                       * @notice Set the address of the TokenState contract.
                       * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
                       * as balances would be unreachable.
                       */
                      function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
                          tokenState = _tokenState;
                          emitTokenStateUpdated(_tokenState);
                      }
                  
                      function _internalTransfer(address from, address to, uint value) internal returns (bool) {
                          /* Disallow transfers to irretrievable-addresses. */
                          require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
                  
                          // Insufficient balance will be handled by the safe subtraction.
                          tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
                          tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
                  
                          // Emit a standard ERC20 transfer event
                          emitTransfer(from, to, value);
                  
                          return true;
                      }
                  
                      /**
                       * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
                       * the onlyProxy or optionalProxy modifiers.
                       */
                      function _transfer_byProxy(address from, address to, uint value) internal returns (bool) {
                          return _internalTransfer(from, to, value);
                      }
                  
                      /**
                       * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
                       * possessing the optionalProxy or optionalProxy modifiers.
                       */
                      function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) {
                          /* Insufficient allowance will be handled by the safe subtraction. */
                          tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
                          return _internalTransfer(from, to, value);
                      }
                  
                      /**
                       * @notice Approves spender to transfer on the message sender's behalf.
                       */
                      function approve(address spender, uint value) public optionalProxy returns (bool) {
                          address sender = messageSender;
                  
                          tokenState.setAllowance(sender, spender, value);
                          emitApproval(sender, spender, value);
                          return true;
                      }
                  
                      /* ========== EVENTS ========== */
                  
                      event Transfer(address indexed from, address indexed to, uint value);
                      bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
                  
                      function emitTransfer(address from, address to, uint value) internal {
                          proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
                      }
                  
                      event Approval(address indexed owner, address indexed spender, uint value);
                      bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
                  
                      function emitApproval(address owner, address spender, uint value) internal {
                          proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
                      }
                  
                      event TokenStateUpdated(address newTokenState);
                      bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
                  
                      function emitTokenStateUpdated(address newTokenState) internal {
                          proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
                      }
                  }
                  
                  
                  interface IExchanger {
                      function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
                  
                      function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint);
                  
                      function settlementOwing(address account, bytes32 currencyKey)
                          external
                          view
                          returns (uint reclaimAmount, uint rebateAmount);
                  
                      function settle(address from, bytes32 currencyKey) external returns (uint reclaimed, uint refunded);
                  
                      function exchange(
                          address from,
                          bytes32 sourceCurrencyKey,
                          uint sourceAmount,
                          bytes32 destinationCurrencyKey,
                          address destinationAddress
                      ) external returns (uint amountReceived);
                  
                      function calculateAmountAfterSettlement(address from, bytes32 currencyKey, uint amount, uint refunded)
                          external
                          view
                          returns (uint amountAfterSettlement);
                  }
                  
                  
                  interface IIssuer {
                      function issueSynths(address from, uint amount) external;
                  
                      function issueMaxSynths(address from) external;
                  
                      function burnSynths(address from, uint amount) external;
                  }
                  
                  
                  contract Synth is ExternStateToken, MixinResolver {
                      /* ========== STATE VARIABLES ========== */
                  
                      // Currency key which identifies this Synth to the Synthetix system
                      bytes32 public currencyKey;
                  
                      uint8 public constant DECIMALS = 18;
                  
                      // Where fees are pooled in sUSD
                      address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
                  
                      /* ========== CONSTRUCTOR ========== */
                  
                      constructor(
                          address _proxy,
                          TokenState _tokenState,
                          string _tokenName,
                          string _tokenSymbol,
                          address _owner,
                          bytes32 _currencyKey,
                          uint _totalSupply,
                          address _resolver
                      )
                          public
                          ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner)
                          MixinResolver(_owner, _resolver)
                      {
                          require(_proxy != address(0), "_proxy cannot be 0");
                          require(_owner != 0, "_owner cannot be 0");
                  
                          currencyKey = _currencyKey;
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function transfer(address to, uint value) public optionalProxy returns (bool) {
                          _ensureCanTransfer(messageSender, value);
                  
                          // transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee
                          if (to == FEE_ADDRESS) {
                              return _transferToFeeAddress(to, value);
                          }
                  
                          // transfers to 0x address will be burned
                          if (to == address(0)) {
                              return _internalBurn(messageSender, value);
                          }
                  
                          return super._internalTransfer(messageSender, to, value);
                      }
                  
                      function transferAndSettle(address to, uint value) public optionalProxy returns (bool) {
                          exchanger().settle(messageSender, currencyKey);
                  
                          // Save gas instead of calling transferableSynths
                          uint balanceAfter = tokenState.balanceOf(messageSender);
                  
                          // Reduce the value to transfer if balance is insufficient after reclaimed
                          value = value > balanceAfter ? balanceAfter : value;
                  
                          return super._internalTransfer(messageSender, to, value);
                      }
                  
                      function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) {
                          _ensureCanTransfer(from, value);
                  
                          return _internalTransferFrom(from, to, value);
                      }
                  
                      function transferFromAndSettle(address from, address to, uint value) public optionalProxy returns (bool) {
                          exchanger().settle(from, currencyKey);
                  
                          // Save gas instead of calling transferableSynths
                          uint balanceAfter = tokenState.balanceOf(from);
                  
                          // Reduce the value to transfer if balance is insufficient after reclaimed
                          value = value >= balanceAfter ? balanceAfter : value;
                  
                          return _internalTransferFrom(from, to, value);
                      }
                  
                      /**
                       * @notice _transferToFeeAddress function
                       * non-sUSD synths are exchanged into sUSD via synthInitiatedExchange
                       * notify feePool to record amount as fee paid to feePool */
                      function _transferToFeeAddress(address to, uint value) internal returns (bool) {
                          uint amountInUSD;
                  
                          // sUSD can be transferred to FEE_ADDRESS directly
                          if (currencyKey == "sUSD") {
                              amountInUSD = value;
                              super._internalTransfer(messageSender, to, value);
                          } else {
                              // else exchange synth into sUSD and send to FEE_ADDRESS
                              amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS);
                          }
                  
                          // Notify feePool to record sUSD to distribute as fees
                          feePool().recordFeePaid(amountInUSD);
                  
                          return true;
                      }
                  
                      // Allow synthetix to issue a certain number of synths from an account.
                      // forward call to _internalIssue
                      function issue(address account, uint amount) external onlyInternalContracts {
                          _internalIssue(account, amount);
                      }
                  
                      // Allow synthetix or another synth contract to burn a certain number of synths from an account.
                      // forward call to _internalBurn
                      function burn(address account, uint amount) external onlyInternalContracts {
                          _internalBurn(account, amount);
                      }
                  
                      function _internalIssue(address account, uint amount) internal {
                          tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
                          totalSupply = totalSupply.add(amount);
                          emitTransfer(address(0), account, amount);
                          emitIssued(account, amount);
                      }
                  
                      function _internalBurn(address account, uint amount) internal returns (bool) {
                          tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
                          totalSupply = totalSupply.sub(amount);
                          emitTransfer(account, address(0), amount);
                          emitBurned(account, amount);
                  
                          return true;
                      }
                  
                      // Allow owner to set the total supply on import.
                      function setTotalSupply(uint amount) external optionalProxy_onlyOwner {
                          totalSupply = amount;
                      }
                  
                      /* ========== VIEWS ========== */
                      function synthetix() internal view returns (ISynthetix) {
                          return ISynthetix(resolver.requireAndGetAddress("Synthetix", "Missing Synthetix address"));
                      }
                  
                      function feePool() internal view returns (IFeePool) {
                          return IFeePool(resolver.requireAndGetAddress("FeePool", "Missing FeePool address"));
                      }
                  
                      function exchanger() internal view returns (IExchanger) {
                          return IExchanger(resolver.requireAndGetAddress("Exchanger", "Missing Exchanger address"));
                      }
                  
                      function issuer() internal view returns (IIssuer) {
                          return IIssuer(resolver.requireAndGetAddress("Issuer", "Missing Issuer address"));
                      }
                  
                      function _ensureCanTransfer(address from, uint value) internal view {
                          require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period");
                          require(transferableSynths(from) >= value, "Transfer requires settle");
                      }
                  
                      function transferableSynths(address account) public view returns (uint) {
                          (uint reclaimAmount, ) = exchanger().settlementOwing(account, currencyKey);
                  
                          // Note: ignoring rebate amount here because a settle() is required in order to
                          // allow the transfer to actually work
                  
                          uint balance = tokenState.balanceOf(account);
                  
                          if (reclaimAmount > balance) {
                              return 0;
                          } else {
                              return balance.sub(reclaimAmount);
                          }
                      }
                  
                      /* ========== INTERNAL FUNCTIONS ========== */
                  
                      function _internalTransferFrom(address from, address to, uint value) internal returns (bool) {
                          // Skip allowance update in case of infinite allowance
                          if (tokenState.allowance(from, messageSender) != uint(-1)) {
                              // Reduce the allowance by the amount we're transferring.
                              // The safeSub call will handle an insufficient allowance.
                              tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
                          }
                  
                          return super._internalTransfer(from, to, value);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      modifier onlyInternalContracts() {
                          bool isSynthetix = msg.sender == address(synthetix());
                          bool isFeePool = msg.sender == address(feePool());
                          bool isExchanger = msg.sender == address(exchanger());
                          bool isIssuer = msg.sender == address(issuer());
                  
                          require(
                              isSynthetix || isFeePool || isExchanger || isIssuer,
                              "Only Synthetix, FeePool, Exchanger or Issuer contracts allowed"
                          );
                          _;
                      }
                  
                      /* ========== EVENTS ========== */
                      event Issued(address indexed account, uint value);
                      bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)");
                  
                      function emitIssued(address account, uint value) internal {
                          proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
                      }
                  
                      event Burned(address indexed account, uint value);
                      bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)");
                  
                      function emitBurned(address account, uint value) internal {
                          proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
                      }
                  }
                  
                  
                  /**
                   * @title Synthetix interface contract
                   * @notice Abstract contract to hold public getters
                   * @dev pseudo interface, actually declared as contract to hold the public getters
                   */
                  
                  
                  contract ISynthetix {
                      // ========== PUBLIC STATE VARIABLES ==========
                  
                      uint public totalSupply;
                  
                      mapping(bytes32 => Synth) public synths;
                  
                      mapping(address => bytes32) public synthsByAddress;
                  
                      // ========== PUBLIC FUNCTIONS ==========
                  
                      function balanceOf(address account) public view returns (uint);
                  
                      function transfer(address to, uint value) public returns (bool);
                  
                      function transferFrom(address from, address to, uint value) public returns (bool);
                  
                      function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
                          external
                          returns (uint amountReceived);
                  
                      function issueSynths(uint amount) external;
                  
                      function issueMaxSynths() external;
                  
                      function burnSynths(uint amount) external;
                  
                      function settle(bytes32 currencyKey) external returns (uint reclaimed, uint refunded);
                  
                      function collateralisationRatio(address issuer) public view returns (uint);
                  
                      function totalIssuedSynths(bytes32 currencyKey) public view returns (uint);
                  
                      function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) public view returns (uint);
                  
                      function debtBalanceOf(address issuer, bytes32 currencyKey) public view returns (uint);
                  
                      function remainingIssuableSynths(address issuer) public view returns (uint, uint);
                  
                      function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
                  
                      function emitSynthExchange(
                          address account,
                          bytes32 fromCurrencyKey,
                          uint fromAmount,
                          bytes32 toCurrencyKey,
                          uint toAmount,
                          address toAddress
                      ) external;
                  
                      function emitExchangeReclaim(address account, bytes32 currencyKey, uint amount) external;
                  
                      function emitExchangeRebate(address account, bytes32 currencyKey, uint amount) external;
                  }
                  
                  
                  contract Exchanger is MixinResolver {
                      using SafeMath for uint;
                      using SafeDecimalMath for uint;
                  
                      bool public exchangeEnabled;
                  
                      bytes32 private constant sUSD = "sUSD";
                  
                      uint public waitingPeriodSecs;
                  
                      constructor(address _owner, address _resolver) public MixinResolver(_owner, _resolver) {
                          exchangeEnabled = true;
                          waitingPeriodSecs = 3 minutes;
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      function exchangeState() internal view returns (IExchangeState) {
                          return IExchangeState(resolver.requireAndGetAddress("ExchangeState", "Missing ExchangeState address"));
                      }
                  
                      function exchangeRates() internal view returns (IExchangeRates) {
                          return IExchangeRates(resolver.requireAndGetAddress("ExchangeRates", "Missing ExchangeRates address"));
                      }
                  
                      function synthetix() internal view returns (ISynthetix) {
                          return ISynthetix(resolver.requireAndGetAddress("Synthetix", "Missing Synthetix address"));
                      }
                  
                      function feePool() internal view returns (IFeePool) {
                          return IFeePool(resolver.requireAndGetAddress("FeePool", "Missing FeePool address"));
                      }
                  
                      function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) public view returns (uint) {
                          return secsLeftInWaitingPeriodForExchange(exchangeState().getMaxTimestamp(account, currencyKey));
                      }
                  
                      // Determine the effective fee rate for the exchange, taking into considering swing trading
                      function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) {
                          // Get the base exchange fee rate
                          uint exchangeFeeRate = feePool().exchangeFeeRate();
                  
                          uint multiplier = 1;
                  
                          // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD.
                          // Note: this assumes shorts begin with 'i' and longs with 's'.
                          if (
                              (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != sUSD && destinationCurrencyKey[0] == 0x69) ||
                              (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != sUSD && destinationCurrencyKey[0] == 0x73)
                          ) {
                              // If so then double the exchange fee multipler
                              multiplier = 2;
                          }
                  
                          return exchangeFeeRate.mul(multiplier);
                      }
                  
                      function settlementOwing(address account, bytes32 currencyKey)
                          public
                          view
                          returns (uint reclaimAmount, uint rebateAmount)
                      {
                          // Need to sum up all reclaim and rebate amounts for the user and the currency key
                          uint numEntries = exchangeState().getLengthOfEntries(account, currencyKey);
                  
                          // For each unsettled exchange
                          for (uint i = 0; i < numEntries; i++) {
                              // fetch the entry from storage
                              (bytes32 src, uint amount, bytes32 dest, uint amountReceived, , , , ) = exchangeState().getEntryAt(
                                  account,
                                  currencyKey,
                                  i
                              );
                  
                              // determine the last round ids for src and dest pairs when period ended or latest if not over
                              (uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd) = getRoundIdsAtPeriodEnd(account, currencyKey, i);
                  
                              // given these round ids, determine what effective value they should have received
                              uint destinationAmount = exchangeRates().effectiveValueAtRound(
                                  src,
                                  amount,
                                  dest,
                                  srcRoundIdAtPeriodEnd,
                                  destRoundIdAtPeriodEnd
                              );
                  
                              // and deduct the fee from this amount
                              (uint amountShouldHaveReceived, ) = calculateExchangeAmountMinusFees(src, dest, destinationAmount);
                  
                              if (amountReceived > amountShouldHaveReceived) {
                                  // if they received more than they should have, add to the reclaim tally
                                  reclaimAmount = reclaimAmount.add(amountReceived.sub(amountShouldHaveReceived));
                              } else if (amountShouldHaveReceived > amountReceived) {
                                  // if less, add to the rebate tally
                                  rebateAmount = rebateAmount.add(amountShouldHaveReceived.sub(amountReceived));
                              }
                          }
                  
                          return (reclaimAmount, rebateAmount);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      function setWaitingPeriodSecs(uint _waitingPeriodSecs) external onlyOwner {
                          waitingPeriodSecs = _waitingPeriodSecs;
                      }
                  
                      function setExchangeEnabled(bool _exchangeEnabled) external onlyOwner {
                          exchangeEnabled = _exchangeEnabled;
                      }
                  
                      function calculateAmountAfterSettlement(address from, bytes32 currencyKey, uint amount, uint refunded)
                          public
                          view
                          returns (uint amountAfterSettlement)
                      {
                          amountAfterSettlement = amount;
                  
                          // balance of a synth will show an amount after settlement
                          uint balanceOfSourceAfterSettlement = synthetix().synths(currencyKey).balanceOf(from);
                  
                          // when there isn't enough supply (either due to reclamation settlement or because the number is too high)
                          if (amountAfterSettlement > balanceOfSourceAfterSettlement) {
                              // then the amount to exchange is reduced to their remaining supply
                              amountAfterSettlement = balanceOfSourceAfterSettlement;
                          }
                  
                          if (refunded > 0) {
                              amountAfterSettlement = amountAfterSettlement.add(refunded);
                          }
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function exchange(
                          address from,
                          bytes32 sourceCurrencyKey,
                          uint sourceAmount,
                          bytes32 destinationCurrencyKey,
                          address destinationAddress
                      )
                          external
                          // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us.
                          onlySynthetixorSynth
                          returns (uint amountReceived)
                      {
                          require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
                          require(sourceAmount > 0, "Zero amount");
                          require(exchangeEnabled, "Exchanging is disabled");
                  
                          (, uint refunded) = _internalSettle(from, sourceCurrencyKey);
                  
                          ISynthetix _synthetix = synthetix();
                          IExchangeRates _exRates = exchangeRates();
                  
                          uint sourceAmountAfterSettlement = calculateAmountAfterSettlement(from, sourceCurrencyKey, sourceAmount, refunded);
                  
                          // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires
                          // the subtraction to not overflow, which would happen if their balance is not sufficient.
                  
                          // Burn the source amount
                          _synthetix.synths(sourceCurrencyKey).burn(from, sourceAmountAfterSettlement);
                  
                          uint destinationAmount = _exRates.effectiveValue(
                              sourceCurrencyKey,
                              sourceAmountAfterSettlement,
                              destinationCurrencyKey
                          );
                  
                          uint fee;
                  
                          (amountReceived, fee) = calculateExchangeAmountMinusFees(
                              sourceCurrencyKey,
                              destinationCurrencyKey,
                              destinationAmount
                          );
                  
                          // // Issue their new synths
                          _synthetix.synths(destinationCurrencyKey).issue(destinationAddress, amountReceived);
                  
                          // Remit the fee if required
                          if (fee > 0) {
                              remitFee(_exRates, _synthetix, fee, destinationCurrencyKey);
                          }
                  
                          // Nothing changes as far as issuance data goes because the total value in the system hasn't changed.
                  
                          // Let the DApps know there was a Synth exchange
                          _synthetix.emitSynthExchange(
                              from,
                              sourceCurrencyKey,
                              sourceAmountAfterSettlement,
                              destinationCurrencyKey,
                              amountReceived,
                              destinationAddress
                          );
                  
                          // persist the exchange information for the dest key
                          appendExchange(
                              destinationAddress,
                              sourceCurrencyKey,
                              sourceAmountAfterSettlement,
                              destinationCurrencyKey,
                              amountReceived
                          );
                      }
                  
                      function settle(address from, bytes32 currencyKey) external returns (uint reclaimed, uint refunded) {
                          // Note: this function can be called by anyone on behalf of anyone else
                  
                          return _internalSettle(from, currencyKey);
                      }
                  
                      /* ========== INTERNAL FUNCTIONS ========== */
                  
                      function remitFee(IExchangeRates _exRates, ISynthetix _synthetix, uint fee, bytes32 currencyKey) internal {
                          // Remit the fee in sUSDs
                          uint usdFeeAmount = _exRates.effectiveValue(currencyKey, fee, sUSD);
                          _synthetix.synths(sUSD).issue(feePool().FEE_ADDRESS(), usdFeeAmount);
                          // Tell the fee pool about this.
                          feePool().recordFeePaid(usdFeeAmount);
                      }
                  
                      function _internalSettle(address from, bytes32 currencyKey) internal returns (uint reclaimed, uint refunded) {
                          require(maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot settle during waiting period");
                  
                          (uint reclaimAmount, uint rebateAmount) = settlementOwing(from, currencyKey);
                  
                          if (reclaimAmount > rebateAmount) {
                              reclaimed = reclaimAmount.sub(rebateAmount);
                              reclaim(from, currencyKey, reclaimed);
                          } else if (rebateAmount > reclaimAmount) {
                              refunded = rebateAmount.sub(reclaimAmount);
                              refund(from, currencyKey, refunded);
                          }
                  
                          // Now remove all entries, even if no reclaim and no rebate
                          exchangeState().removeEntries(from, currencyKey);
                      }
                  
                      function reclaim(address from, bytes32 currencyKey, uint amount) internal {
                          // burn amount from user
                          synthetix().synths(currencyKey).burn(from, amount);
                          synthetix().emitExchangeReclaim(from, currencyKey, amount);
                      }
                  
                      function refund(address from, bytes32 currencyKey, uint amount) internal {
                          // issue amount to user
                          synthetix().synths(currencyKey).issue(from, amount);
                          synthetix().emitExchangeRebate(from, currencyKey, amount);
                      }
                  
                      function secsLeftInWaitingPeriodForExchange(uint timestamp) internal view returns (uint) {
                          if (timestamp == 0 || now >= timestamp.add(waitingPeriodSecs)) {
                              return 0;
                          }
                  
                          return timestamp.add(waitingPeriodSecs).sub(now);
                      }
                  
                      function calculateExchangeAmountMinusFees(
                          bytes32 sourceCurrencyKey,
                          bytes32 destinationCurrencyKey,
                          uint destinationAmount
                      ) internal view returns (uint amountReceived, uint fee) {
                          // What's the fee on that currency that we should deduct?
                          amountReceived = destinationAmount;
                  
                          // Get the exchange fee rate
                          uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
                  
                          amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate));
                  
                          fee = destinationAmount.sub(amountReceived);
                      }
                  
                      function appendExchange(address account, bytes32 src, uint amount, bytes32 dest, uint amountReceived) internal {
                          IExchangeRates exRates = exchangeRates();
                          uint roundIdForSrc = exRates.getCurrentRoundId(src);
                          uint roundIdForDest = exRates.getCurrentRoundId(dest);
                          uint exchangeFeeRate = feePool().exchangeFeeRate();
                          exchangeState().appendExchangeEntry(
                              account,
                              src,
                              amount,
                              dest,
                              amountReceived,
                              exchangeFeeRate,
                              now,
                              roundIdForSrc,
                              roundIdForDest
                          );
                      }
                  
                      function getRoundIdsAtPeriodEnd(address account, bytes32 currencyKey, uint index)
                          internal
                          view
                          returns (uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd)
                      {
                          (bytes32 src, , bytes32 dest, , , uint timestamp, uint roundIdForSrc, uint roundIdForDest) = exchangeState()
                              .getEntryAt(account, currencyKey, index);
                  
                          IExchangeRates exRates = exchangeRates();
                          srcRoundIdAtPeriodEnd = exRates.getLastRoundIdBeforeElapsedSecs(src, roundIdForSrc, timestamp, waitingPeriodSecs);
                          destRoundIdAtPeriodEnd = exRates.getLastRoundIdBeforeElapsedSecs(dest, roundIdForDest, timestamp, waitingPeriodSecs);
                      }
                  
                      // ========== MODIFIERS ==========
                  
                      modifier onlySynthetixorSynth() {
                          ISynthetix _synthetix = synthetix();
                          require(
                              msg.sender == address(_synthetix) || _synthetix.synthsByAddress(msg.sender) != bytes32(0),
                              "Exchanger: Only synthetix or a synth contract can perform this action"
                          );
                          _;
                      }
                  }
                  
                  
                      

                  File 8 of 8: ExchangeState
                  /*
                  * Synthetix - ExchangeState.sol
                  *
                  * https://github.com/Synthetixio/synthetix
                  * https://synthetix.io
                  *
                  * MIT License
                  * ===========
                  *
                  * Copyright (c) 2020 Synthetix
                  *
                  * 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
                  */
                      
                  /* ===============================================
                  * Flattened with Solidifier by Coinage
                  * 
                  * https://solidifier.coina.ge
                  * ===============================================
                  */
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       Owned.sol
                  version:    1.1
                  author:     Anton Jurisevic
                              Dominic Romanowski
                  
                  date:       2018-2-26
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  An Owned contract, to be inherited by other contracts.
                  Requires its owner to be explicitly set in the constructor.
                  Provides an onlyOwner access modifier.
                  
                  To change owner, the current owner must nominate the next owner,
                  who then has to accept the nomination. The nomination can be
                  cancelled before it is accepted by the new owner by having the
                  previous owner change the nomination (setting it to 0).
                  
                  -----------------------------------------------------------------
                  */
                  
                  pragma solidity 0.4.25;
                  
                  
                  /**
                   * @title A contract with an owner.
                   * @notice Contract ownership can be transferred by first nominating the new owner,
                   * who must then accept the ownership, which prevents accidental incorrect ownership transfers.
                   */
                  contract Owned {
                      address public owner;
                      address public nominatedOwner;
                  
                      /**
                       * @dev Owned Constructor
                       */
                      constructor(address _owner) public {
                          require(_owner != address(0), "Owner address cannot be 0");
                          owner = _owner;
                          emit OwnerChanged(address(0), _owner);
                      }
                  
                      /**
                       * @notice Nominate a new owner of this contract.
                       * @dev Only the current owner may nominate a new owner.
                       */
                      function nominateNewOwner(address _owner) external onlyOwner {
                          nominatedOwner = _owner;
                          emit OwnerNominated(_owner);
                      }
                  
                      /**
                       * @notice Accept the nomination to be owner.
                       */
                      function acceptOwnership() external {
                          require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
                          emit OwnerChanged(owner, nominatedOwner);
                          owner = nominatedOwner;
                          nominatedOwner = address(0);
                      }
                  
                      modifier onlyOwner {
                          require(msg.sender == owner, "Only the contract owner may perform this action");
                          _;
                      }
                  
                      event OwnerNominated(address newOwner);
                      event OwnerChanged(address oldOwner, address newOwner);
                  }
                  
                  
                  /*
                  -----------------------------------------------------------------
                  FILE INFORMATION
                  -----------------------------------------------------------------
                  
                  file:       State.sol
                  version:    1.1
                  author:     Dominic Romanowski
                              Anton Jurisevic
                  
                  date:       2018-05-15
                  
                  -----------------------------------------------------------------
                  MODULE DESCRIPTION
                  -----------------------------------------------------------------
                  
                  This contract is used side by side with external state token
                  contracts, such as Synthetix and Synth.
                  It provides an easy way to upgrade contract logic while
                  maintaining all user balances and allowances. This is designed
                  to make the changeover as easy as possible, since mappings
                  are not so cheap or straightforward to migrate.
                  
                  The first deployed contract would create this state contract,
                  using it as its store of balances.
                  When a new contract is deployed, it links to the existing
                  state contract, whose owner would then change its associated
                  contract to the new one.
                  
                  -----------------------------------------------------------------
                  */
                  
                  
                  contract State is Owned {
                      // the address of the contract that can modify variables
                      // this can only be changed by the owner of this contract
                      address public associatedContract;
                  
                      constructor(address _owner, address _associatedContract) public Owned(_owner) {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== SETTERS ========== */
                  
                      // Change the associated contract to a new address
                      function setAssociatedContract(address _associatedContract) external onlyOwner {
                          associatedContract = _associatedContract;
                          emit AssociatedContractUpdated(_associatedContract);
                      }
                  
                      /* ========== MODIFIERS ========== */
                  
                      modifier onlyAssociatedContract {
                          require(msg.sender == associatedContract, "Only the associated contract can perform this action");
                          _;
                      }
                  
                      /* ========== EVENTS ========== */
                  
                      event AssociatedContractUpdated(address associatedContract);
                  }
                  
                  
                  contract ExchangeState is State {
                      struct ExchangeEntry {
                          bytes32 src;
                          uint amount;
                          bytes32 dest;
                          uint amountReceived;
                          uint exchangeFeeRate;
                          uint timestamp;
                          uint roundIdForSrc;
                          uint roundIdForDest;
                      }
                  
                      mapping(address => mapping(bytes32 => ExchangeEntry[])) public exchanges;
                  
                      uint public maxEntriesInQueue = 12;
                  
                      constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
                  
                      /* ========== SETTERS ========== */
                  
                      function setMaxEntriesInQueue(uint _maxEntriesInQueue) external onlyOwner {
                          maxEntriesInQueue = _maxEntriesInQueue;
                      }
                  
                      /* ========== MUTATIVE FUNCTIONS ========== */
                  
                      function appendExchangeEntry(
                          address account,
                          bytes32 src,
                          uint amount,
                          bytes32 dest,
                          uint amountReceived,
                          uint exchangeFeeRate,
                          uint timestamp,
                          uint roundIdForSrc,
                          uint roundIdForDest
                      ) external onlyAssociatedContract {
                          require(exchanges[account][dest].length < maxEntriesInQueue, "Max queue length reached");
                  
                          exchanges[account][dest].push(
                              ExchangeEntry({
                                  src: src,
                                  amount: amount,
                                  dest: dest,
                                  amountReceived: amountReceived,
                                  exchangeFeeRate: exchangeFeeRate,
                                  timestamp: timestamp,
                                  roundIdForSrc: roundIdForSrc,
                                  roundIdForDest: roundIdForDest
                              })
                          );
                      }
                  
                      function removeEntries(address account, bytes32 currencyKey) external onlyAssociatedContract {
                          delete exchanges[account][currencyKey];
                      }
                  
                      /* ========== VIEWS ========== */
                  
                      function getLengthOfEntries(address account, bytes32 currencyKey) external view returns (uint) {
                          return exchanges[account][currencyKey].length;
                      }
                  
                      function getEntryAt(address account, bytes32 currencyKey, uint index)
                          external
                          view
                          returns (
                              bytes32 src,
                              uint amount,
                              bytes32 dest,
                              uint amountReceived,
                              uint exchangeFeeRate,
                              uint timestamp,
                              uint roundIdForSrc,
                              uint roundIdForDest
                          )
                      {
                          ExchangeEntry storage entry = exchanges[account][currencyKey][index];
                          return (
                              entry.src,
                              entry.amount,
                              entry.dest,
                              entry.amountReceived,
                              entry.exchangeFeeRate,
                              entry.timestamp,
                              entry.roundIdForSrc,
                              entry.roundIdForDest
                          );
                      }
                  
                      function getMaxTimestamp(address account, bytes32 currencyKey) external view returns (uint) {
                          ExchangeEntry[] storage userEntries = exchanges[account][currencyKey];
                          uint timestamp = 0;
                          for (uint i = 0; i < userEntries.length; i++) {
                              if (userEntries[i].timestamp > timestamp) {
                                  timestamp = userEntries[i].timestamp;
                              }
                          }
                          return timestamp;
                      }
                  }