ETH Price: $2,513.33 (+0.86%)

Transaction Decoder

Block:
10679996 at Aug-17-2020 09:32:58 PM +UTC
Transaction Fee:
0.014313607 ETH $35.97
Gas Used:
185,891 Gas / 77 Gwei

Emitted Events:

136 ProxyERC20.Transfer( from=[Receiver] YAMSNXPool, to=[Sender] 0xad7d50d88dcfec80d97892469ad19b23997e6e54, value=1083778091161984499322 )
137 YAMSNXPool.Withdrawn( user=[Sender] 0xad7d50d88dcfec80d97892469ad19b23997e6e54, amount=1083778091161984499322 )
138 YAMDelegator.Transfer( from=[Receiver] YAMSNXPool, to=[Sender] 0xad7d50d88dcfec80d97892469ad19b23997e6e54, amount=418272661197026211099 )
139 YAMSNXPool.RewardPaid( user=[Sender] 0xad7d50d88dcfec80d97892469ad19b23997e6e54, reward=418272661197026211099 )

Account State Difference:

  Address   Before After State Difference Code
0x0e2298E3...c3f55DA16
(Nanopool)
2,886.029089369233140616 Eth2,886.043402976233140616 Eth0.014313607
0x5b1b5fEa...2385381dD
(Synthetix: Token State Synthetix)
0x5eF0de4b...d5E8fdEf5
0x6c3FC1FF...B807f132D
(Yam.Finance: SNX Pool)
0xaD7D50D8...3997E6E54
27.113687666671022017 Eth
Nonce: 30
27.099374059671022017 Eth
Nonce: 31
0.014313607

Execution Trace

YAMSNXPool.CALL( )
  • ProxyERC20.transfer( to=0xaD7D50D88DCfeC80D97892469AD19B23997E6E54, value=1083778091161984499322 ) => ( True )
    • Synthetix.setMessageSender( sender=0x6c3FC1FFDb14D92394f40eeC91D9Ce8B807f132D )
    • Synthetix.transfer( to=0xaD7D50D88DCfeC80D97892469AD19B23997E6E54, value=1083778091161984499322 ) => ( True )
      • SystemStatus.STATICCALL( )
      • SynthetixState.issuanceData( 0x6c3FC1FFDb14D92394f40eeC91D9Ce8B807f132D ) => ( initialDebtOwnership=0, debtEntryIndex=0 )
      • TokenState.balanceOf( 0x6c3FC1FFDb14D92394f40eeC91D9Ce8B807f132D ) => ( 5660140590490539754688182 )
      • TokenState.setBalanceOf( account=0x6c3FC1FFDb14D92394f40eeC91D9Ce8B807f132D, value=5659056812399377770188860 )
      • TokenState.balanceOf( 0xaD7D50D88DCfeC80D97892469AD19B23997E6E54 ) => ( 0 )
      • TokenState.setBalanceOf( account=0xaD7D50D88DCfeC80D97892469AD19B23997E6E54, value=1083778091161984499322 )
      • ProxyERC20._emit( callData=0x00000000000000000000000000000000000000000000003AC0713FCF3500FE7A, numTopics=3, topic1=DDF252AD1BE2C89B69C2B068FC378DAA952BA7F163C4A11628F55A4DF523B3EF, topic2=0000000000000000000000006C3FC1FFDB14D92394F40EEC91D9CE8B807F132D, topic3=000000000000000000000000AD7D50D88DCFEC80D97892469AD19B23997E6E54, topic4=0000000000000000000000000000000000000000000000000000000000000000 )
      • YAMDelegator.CALL( )
      • YAMDelegator.transfer( dst=0xaD7D50D88DCfeC80D97892469AD19B23997E6E54, amount=418272661197026211099 ) => ( True )
        • YAMDelegate.transfer( to=0xaD7D50D88DCfeC80D97892469AD19B23997E6E54, value=418272661197026211099 ) => ( True )
          File 1 of 8: YAMSNXPool
          /**
           *Submitted for verification at Etherscan.io on 2020-07-17
          */
          
          /*
             ____            __   __        __   _
            / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
           _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
          /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
               /___/
          
          * Synthetix: YAMRewards.sol
          *
          * Docs: https://docs.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
          */
          
          // File: @openzeppelin/contracts/math/Math.sol
          
          pragma solidity ^0.5.0;
          
          /**
           * @dev Standard math utilities missing in the Solidity language.
           */
          library Math {
              /**
               * @dev Returns the largest of two numbers.
               */
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a >= b ? a : b;
              }
          
              /**
               * @dev Returns the smallest of two numbers.
               */
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
          
              /**
               * @dev Returns the average of two numbers. The result is rounded towards
               * zero.
               */
              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b) / 2 can overflow, so we distribute
                  return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
              }
          }
          
          // File: @openzeppelin/contracts/math/SafeMath.sol
          
          pragma solidity ^0.5.0;
          
          /**
           * @dev Wrappers over Solidity's arithmetic operations with added overflow
           * checks.
           *
           * Arithmetic operations in Solidity wrap on overflow. This can easily result
           * in bugs, because programmers usually assume that an overflow raises an
           * error, which is the standard behavior in high level programming languages.
           * `SafeMath` restores this intuition by reverting the transaction when an
           * operation overflows.
           *
           * Using this library instead of the unchecked operations eliminates an entire
           * class of bugs, so it's recommended to use it always.
           */
          library SafeMath {
              /**
               * @dev Returns the addition of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `+` operator.
               *
               * Requirements:
               * - Addition cannot overflow.
               */
              function add(uint256 a, uint256 b) internal pure returns (uint256) {
                  uint256 c = a + b;
                  require(c >= a, "SafeMath: addition overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                  return sub(a, b, "SafeMath: subtraction overflow");
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               * - Subtraction cannot overflow.
               *
               * _Available since v2.4.0._
               */
              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b <= a, errorMessage);
                  uint256 c = a - b;
          
                  return c;
              }
          
              /**
               * @dev Returns the multiplication of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `*` operator.
               *
               * Requirements:
               * - Multiplication cannot overflow.
               */
              function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                  // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                  if (a == 0) {
                      return 0;
                  }
          
                  uint256 c = a * b;
                  require(c / a == b, "SafeMath: multiplication overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b) internal pure returns (uint256) {
                  return div(a, b, "SafeMath: division by zero");
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               * - The divisor cannot be zero.
               *
               * _Available since v2.4.0._
               */
              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  // Solidity only automatically asserts when dividing by 0
                  require(b > 0, errorMessage);
                  uint256 c = a / b;
                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
          
                  return c;
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                  return mod(a, b, "SafeMath: modulo by zero");
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts with custom message when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               * - The divisor cannot be zero.
               *
               * _Available since v2.4.0._
               */
              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b != 0, errorMessage);
                  return a % b;
              }
          }
          
          // File: @openzeppelin/contracts/GSN/Context.sol
          
          pragma solidity ^0.5.0;
          
          /*
           * @dev Provides information about the current execution context, including the
           * sender of the transaction and its data. While these are generally available
           * via msg.sender and msg.data, they should not be accessed in such a direct
           * manner, since when dealing with GSN meta-transactions the account sending and
           * paying for execution may not be the actual sender (as far as an application
           * is concerned).
           *
           * This contract is only required for intermediate, library-like contracts.
           */
          contract Context {
              // Empty internal constructor, to prevent people from mistakenly deploying
              // an instance of this contract, which should be used via inheritance.
              constructor () internal { }
              // solhint-disable-previous-line no-empty-blocks
          
              function _msgSender() internal view returns (address payable) {
                  return msg.sender;
              }
          
              function _msgData() internal view returns (bytes memory) {
                  this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                  return msg.data;
              }
          }
          
          // File: @openzeppelin/contracts/ownership/Ownable.sol
          
          pragma solidity ^0.5.0;
          
          /**
           * @dev Contract module which provides a basic access control mechanism, where
           * there is an account (an owner) that can be granted exclusive access to
           * specific functions.
           *
           * This module is used through inheritance. It will make available the modifier
           * `onlyOwner`, which can be applied to your functions to restrict their use to
           * the owner.
           */
          contract Ownable is Context {
              address private _owner;
          
              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          
              /**
               * @dev Initializes the contract setting the deployer as the initial owner.
               */
              constructor () internal {
                  _owner = _msgSender();
                  emit OwnershipTransferred(address(0), _owner);
              }
          
              /**
               * @dev Returns the address of the current owner.
               */
              function owner() public view returns (address) {
                  return _owner;
              }
          
              /**
               * @dev Throws if called by any account other than the owner.
               */
              modifier onlyOwner() {
                  require(isOwner(), "Ownable: caller is not the owner");
                  _;
              }
          
              /**
               * @dev Returns true if the caller is the current owner.
               */
              function isOwner() public view returns (bool) {
                  return _msgSender() == _owner;
              }
          
              /**
               * @dev Leaves the contract without owner. It will not be possible to call
               * `onlyOwner` functions anymore. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby removing any functionality that is only available to the owner.
               */
              function renounceOwnership() public onlyOwner {
                  emit OwnershipTransferred(_owner, address(0));
                  _owner = address(0);
              }
          
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public onlyOwner {
                  _transferOwnership(newOwner);
              }
          
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               */
              function _transferOwnership(address newOwner) internal {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  emit OwnershipTransferred(_owner, newOwner);
                  _owner = newOwner;
              }
          }
          
          // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
          
          pragma solidity ^0.5.0;
          
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
           * the optional functions; to access them see {ERC20Detailed}.
           */
          interface IERC20 {
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
          
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
          
              /**
               * @dev Moves `amount` tokens from the caller's account to `recipient`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address recipient, uint256 amount) external returns (bool);
          
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
          
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
          
              /**
               * @dev Moves `amount` tokens from `sender` to `recipient` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
          
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
          
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
          }
          
          // File: @openzeppelin/contracts/utils/Address.sol
          
          pragma solidity ^0.5.5;
          
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * This test is non-exhaustive, and there may be false-negatives: during the
               * execution of a contract's constructor, its address will be reported as
               * not containing a contract.
               *
               * IMPORTANT: It is unsafe to assume that an address for which this
               * function returns false is an externally-owned account (EOA) and not a
               * contract.
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies in extcodesize, which returns 0 for contracts in
                  // construction, since the code is only stored at the end of the
                  // constructor execution.
          
                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                  // for accounts without code, i.e. `keccak256('')`
                  bytes32 codehash;
                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                  // solhint-disable-next-line no-inline-assembly
                  assembly { codehash := extcodehash(account) }
                  return (codehash != 0x0 && codehash != accountHash);
              }
          
              /**
               * @dev Converts an `address` into `address payable`. Note that this is
               * simply a type cast: the actual underlying value is not changed.
               *
               * _Available since v2.4.0._
               */
              function toPayable(address account) internal pure returns (address payable) {
                  return address(uint160(account));
              }
          
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               *
               * _Available since v2.4.0._
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
          
                  // solhint-disable-next-line avoid-call-value
                  (bool success, ) = recipient.call.value(amount)("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
          }
          
          // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
          
          pragma solidity ^0.5.0;
          
          
          
          
          /**
           * @title SafeERC20
           * @dev Wrappers around ERC20 operations that throw on failure (when the token
           * contract returns false). Tokens that return no value (and instead revert or
           * throw on failure) are also supported, non-reverting calls are assumed to be
           * successful.
           * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
           * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
           */
          library SafeERC20 {
              using SafeMath for uint256;
              using Address for address;
          
              function safeTransfer(IERC20 token, address to, uint256 value) internal {
                  callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
              }
          
              function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                  callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
              }
          
              function safeApprove(IERC20 token, address spender, uint256 value) internal {
                  // safeApprove should only be called when setting an initial allowance,
                  // or when resetting it to zero. To increase and decrease it, use
                  // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                  // solhint-disable-next-line max-line-length
                  require((value == 0) || (token.allowance(address(this), spender) == 0),
                      "SafeERC20: approve from non-zero to non-zero allowance"
                  );
                  callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
              }
          
              function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  uint256 newAllowance = token.allowance(address(this), spender).add(value);
                  callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
          
              function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                  callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
          
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               */
              function callOptionalReturn(IERC20 token, bytes memory data) private {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves.
          
                  // A Solidity high level call has three parts:
                  //  1. The target address is checked to verify it contains contract code
                  //  2. The call itself is made, and success asserted
                  //  3. The return value is decoded, which in turn checks the size of the returned data.
                  // solhint-disable-next-line max-line-length
                  require(address(token).isContract(), "SafeERC20: call to non-contract");
          
                  // solhint-disable-next-line avoid-low-level-calls
                  (bool success, bytes memory returndata) = address(token).call(data);
                  require(success, "SafeERC20: low-level call failed");
          
                  if (returndata.length > 0) { // Return data is optional
                      // solhint-disable-next-line max-line-length
                      require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                  }
              }
          }
          
          // File: contracts/IRewardDistributionRecipient.sol
          
          pragma solidity ^0.5.0;
          
          
          
          contract IRewardDistributionRecipient is Ownable {
              address public rewardDistribution;
          
              function notifyRewardAmount(uint256 reward) external;
          
              modifier onlyRewardDistribution() {
                  require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
                  _;
              }
          
              function setRewardDistribution(address _rewardDistribution)
                  external
                  onlyOwner
              {
                  rewardDistribution = _rewardDistribution;
              }
          }
          
          // File: contracts/CurveRewards.sol
          
          pragma solidity ^0.5.0;
          
          
          interface YAM {
              function yamsScalingFactor() external returns (uint256);
          }
          
          
          
          contract LPTokenWrapper {
              using SafeMath for uint256;
              using SafeERC20 for IERC20;
          
              IERC20 public snx = IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F);
          
              uint256 private _totalSupply;
              mapping(address => uint256) private _balances;
          
              function totalSupply() public view returns (uint256) {
                  return _totalSupply;
              }
          
              function balanceOf(address account) public view returns (uint256) {
                  return _balances[account];
              }
          
              function stake(uint256 amount) public {
                  _totalSupply = _totalSupply.add(amount);
                  _balances[msg.sender] = _balances[msg.sender].add(amount);
                  snx.safeTransferFrom(msg.sender, address(this), amount);
              }
          
              function withdraw(uint256 amount) public {
                  _totalSupply = _totalSupply.sub(amount);
                  _balances[msg.sender] = _balances[msg.sender].sub(amount);
                  snx.safeTransfer(msg.sender, amount);
              }
          }
          
          contract YAMSNXPool is LPTokenWrapper, IRewardDistributionRecipient {
              IERC20 public yam = IERC20(0x0e2298E3B3390e3b945a5456fBf59eCc3f55DA16);
              uint256 public constant DURATION = 625000; // ~7 1/4 days
          
              uint256 public starttime = 1597172400; // 2020-08-11 19:00:00 (UTC UTC +00:00)
              uint256 public periodFinish = 0;
              uint256 public rewardRate = 0;
              uint256 public lastUpdateTime;
              uint256 public rewardPerTokenStored;
              mapping(address => uint256) public userRewardPerTokenPaid;
              mapping(address => uint256) public rewards;
          
              event RewardAdded(uint256 reward);
              event Staked(address indexed user, uint256 amount);
              event Withdrawn(address indexed user, uint256 amount);
              event RewardPaid(address indexed user, uint256 reward);
          
              modifier checkStart() {
                  require(block.timestamp >= starttime,"not start");
                  _;
              }
          
              modifier updateReward(address account) {
                  rewardPerTokenStored = rewardPerToken();
                  lastUpdateTime = lastTimeRewardApplicable();
                  if (account != address(0)) {
                      rewards[account] = earned(account);
                      userRewardPerTokenPaid[account] = rewardPerTokenStored;
                  }
                  _;
              }
          
              function lastTimeRewardApplicable() public view returns (uint256) {
                  return Math.min(block.timestamp, periodFinish);
              }
          
              function rewardPerToken() public view returns (uint256) {
                  if (totalSupply() == 0) {
                      return rewardPerTokenStored;
                  }
                  return
                      rewardPerTokenStored.add(
                          lastTimeRewardApplicable()
                              .sub(lastUpdateTime)
                              .mul(rewardRate)
                              .mul(1e18)
                              .div(totalSupply())
                      );
              }
          
              function earned(address account) public view returns (uint256) {
                  return
                      balanceOf(account)
                          .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                          .div(1e18)
                          .add(rewards[account]);
              }
          
              // stake visibility is public as overriding LPTokenWrapper's stake() function
              function stake(uint256 amount) public updateReward(msg.sender) checkStart {
                  require(amount > 0, "Cannot stake 0");
                  super.stake(amount);
                  emit Staked(msg.sender, amount);
              }
          
              function withdraw(uint256 amount) public updateReward(msg.sender) checkStart {
                  require(amount > 0, "Cannot withdraw 0");
                  super.withdraw(amount);
                  emit Withdrawn(msg.sender, amount);
              }
          
              function exit() external {
                  withdraw(balanceOf(msg.sender));
                  getReward();
              }
          
              function getReward() public updateReward(msg.sender) checkStart {
                  uint256 reward = earned(msg.sender);
                  if (reward > 0) {
                      rewards[msg.sender] = 0;
                      uint256 scalingFactor = YAM(address(yam)).yamsScalingFactor();
                      uint256 trueReward = reward.mul(scalingFactor).div(10**18);
                      yam.safeTransfer(msg.sender, trueReward);
                      emit RewardPaid(msg.sender, trueReward);
                  }
              }
          
              function notifyRewardAmount(uint256 reward)
                  external
                  onlyRewardDistribution
                  updateReward(address(0))
              {
                  if (block.timestamp > starttime) {
                    if (block.timestamp >= periodFinish) {
                        rewardRate = reward.div(DURATION);
                    } else {
                        uint256 remaining = periodFinish.sub(block.timestamp);
                        uint256 leftover = remaining.mul(rewardRate);
                        rewardRate = reward.add(leftover).div(DURATION);
                    }
                    lastUpdateTime = block.timestamp;
                    periodFinish = block.timestamp.add(DURATION);
                    emit RewardAdded(reward);
                  } else {
                    rewardRate = reward.div(DURATION);
                    lastUpdateTime = starttime;
                    periodFinish = starttime.add(DURATION);
                    emit RewardAdded(reward);
                  }
              }
          }

          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: YAMDelegator
          pragma solidity 0.5.17;
          
          
          library SafeMath {
              /**
               * @dev Returns the addition of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `+` operator.
               *
               * Requirements:
               *
               * - Addition cannot overflow.
               */
              function add(uint256 a, uint256 b) internal pure returns (uint256) {
                  uint256 c = a + b;
                  require(c >= a, "SafeMath: addition overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               *
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                  return sub(a, b, "SafeMath: subtraction overflow");
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               *
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b <= a, errorMessage);
                  uint256 c = a - b;
          
                  return c;
              }
          
              /**
               * @dev Returns the multiplication of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `*` operator.
               *
               * Requirements:
               *
               * - Multiplication cannot overflow.
               */
              function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                  // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                  if (a == 0) {
                      return 0;
                  }
          
                  uint256 c = a * b;
                  require(c / a == b, "SafeMath: multiplication overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b) internal pure returns (uint256) {
                  return div(a, b, "SafeMath: division by zero");
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b > 0, errorMessage);
                  uint256 c = a / b;
                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
          
                  return c;
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                  return mod(a, b, "SafeMath: modulo by zero");
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts with custom message when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b != 0, errorMessage);
                  return a % b;
              }
          }
          
          
          contract YAMTokenStorage {
          
              using SafeMath for uint256;
          
              /**
               * @dev Guard variable for re-entrancy checks. Not currently used
               */
              bool internal _notEntered;
          
              /**
               * @notice EIP-20 token name for this token
               */
              string public name;
          
              /**
               * @notice EIP-20 token symbol for this token
               */
              string public symbol;
          
              /**
               * @notice EIP-20 token decimals for this token
               */
              uint8 public decimals;
          
              /**
               * @notice Governor for this contract
               */
              address public gov;
          
              /**
               * @notice Pending governance for this contract
               */
              address public pendingGov;
          
              /**
               * @notice Approved rebaser for this contract
               */
              address public rebaser;
          
              /**
               * @notice Reserve address of YAM protocol
               */
              address public incentivizer;
          
              /**
               * @notice Total supply of YAMs
               */
              uint256 public totalSupply;
          
              /**
               * @notice Internal decimals used to handle scaling factor
               */
              uint256 public constant internalDecimals = 10**24;
          
              /**
               * @notice Used for percentage maths
               */
              uint256 public constant BASE = 10**18;
          
              /**
               * @notice Scaling factor that adjusts everyone's balances
               */
              uint256 public yamsScalingFactor;
          
              mapping (address => uint256) internal _yamBalances;
          
              mapping (address => mapping (address => uint256)) internal _allowedFragments;
          
              uint256 public initSupply;
          
          }
          
          
          contract YAMGovernanceStorage {
              /// @notice A record of each accounts delegate
              mapping (address => address) internal _delegates;
          
              /// @notice A checkpoint for marking number of votes from a given block
              struct Checkpoint {
                  uint32 fromBlock;
                  uint256 votes;
              }
          
              /// @notice A record of votes checkpoints for each account, by index
              mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
          
              /// @notice The number of checkpoints for each account
              mapping (address => uint32) public numCheckpoints;
          
              /// @notice The EIP-712 typehash for the contract's domain
              bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
          
              /// @notice The EIP-712 typehash for the delegation struct used by the contract
              bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
          
              /// @notice A record of states for signing / validating signatures
              mapping (address => uint) public nonces;
          }
          
          
          contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
          
              /// @notice An event thats emitted when an account changes its delegate
              event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
          
              /// @notice An event thats emitted when a delegate account's vote balance changes
              event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
          
              /**
               * @notice Event emitted when tokens are rebased
               */
              event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
          
              /*** Gov Events ***/
          
              /**
               * @notice Event emitted when pendingGov is changed
               */
              event NewPendingGov(address oldPendingGov, address newPendingGov);
          
              /**
               * @notice Event emitted when gov is changed
               */
              event NewGov(address oldGov, address newGov);
          
              /**
               * @notice Sets the rebaser contract
               */
              event NewRebaser(address oldRebaser, address newRebaser);
          
              /**
               * @notice Sets the incentivizer contract
               */
              event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
          
              /* - ERC20 Events - */
          
              /**
               * @notice EIP20 Transfer event
               */
              event Transfer(address indexed from, address indexed to, uint amount);
          
              /**
               * @notice EIP20 Approval event
               */
              event Approval(address indexed owner, address indexed spender, uint amount);
          
              /* - Extra Events - */
              /**
               * @notice Tokens minted event
               */
              event Mint(address to, uint256 amount);
          
              // Public functions
              function transfer(address to, uint256 value) external returns(bool);
              function transferFrom(address from, address to, uint256 value) external returns(bool);
              function balanceOf(address who) external view returns(uint256);
              function balanceOfUnderlying(address who) external view returns(uint256);
              function allowance(address owner_, address spender) external view returns(uint256);
              function approve(address spender, uint256 value) external returns (bool);
              function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
              function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
              function maxScalingFactor() external view returns (uint256);
          
              /* - Governance Functions - */
              function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
              function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
              function delegate(address delegatee) external;
              function delegates(address delegator) external view returns (address);
              function getCurrentVotes(address account) external view returns (uint256);
          
              /* - Permissioned/Governance functions - */
              function mint(address to, uint256 amount) external returns (bool);
              function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
              function _setRebaser(address rebaser_) external;
              function _setIncentivizer(address incentivizer_) external;
              function _setPendingGov(address pendingGov_) external;
              function _acceptGov() external;
          }
          
          
          contract YAMDelegationStorage {
              /**
               * @notice Implementation address for this contract
               */
              address public implementation;
          }
          
          contract YAMDelegatorInterface is YAMDelegationStorage {
              /**
               * @notice Emitted when implementation is changed
               */
              event NewImplementation(address oldImplementation, address newImplementation);
          
              /**
               * @notice Called by the gov to update the implementation of the delegator
               * @param implementation_ The address of the new implementation for delegation
               * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
               * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
               */
              function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
          }
          
          contract YAMDelegator is YAMTokenInterface, YAMDelegatorInterface {
              /**
               * @notice Construct a new YAM
               * @param name_ ERC-20 name of this token
               * @param symbol_ ERC-20 symbol of this token
               * @param decimals_ ERC-20 decimal precision of this token
               * @param initSupply_ Initial token amount
               * @param implementation_ The address of the implementation the contract delegates to
               * @param becomeImplementationData The encoded args for becomeImplementation
               */
              constructor(
                  string memory name_,
                  string memory symbol_,
                  uint8 decimals_,
                  uint256 initSupply_,
                  address implementation_,
                  bytes memory becomeImplementationData
              )
                  public
              {
          
          
                  // Creator of the contract is gov during initialization
                  gov = msg.sender;
          
                  // First delegate gets to initialize the delegator (i.e. storage contract)
                  delegateTo(
                      implementation_,
                      abi.encodeWithSignature(
                          "initialize(string,string,uint8,address,uint256)",
                          name_,
                          symbol_,
                          decimals_,
                          msg.sender,
                          initSupply_
                      )
                  );
          
                  // New implementations always get set via the settor (post-initialize)
                  _setImplementation(implementation_, false, becomeImplementationData);
          
              }
          
              /**
               * @notice Called by the gov to update the implementation of the delegator
               * @param implementation_ The address of the new implementation for delegation
               * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
               * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
               */
              function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
                  require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");
          
                  if (allowResign) {
                      delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
                  }
          
                  address oldImplementation = implementation;
                  implementation = implementation_;
          
                  delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
          
                  emit NewImplementation(oldImplementation, implementation);
              }
          
              /**
               * @notice Sender supplies assets into the market and receives cTokens in exchange
               * @dev Accrues interest whether or not the operation succeeds, unless reverted
               * @param mintAmount The amount of the underlying asset to supply
               * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
               */
              function mint(address to, uint256 mintAmount)
                  external
                  returns (bool)
              {
                  to; mintAmount; // Shh
                  delegateAndReturn();
              }
          
              /**
               * @notice Transfer `amount` tokens from `msg.sender` to `dst`
               * @param dst The address of the destination account
               * @param amount The number of tokens to transfer
               * @return Whether or not the transfer succeeded
               */
              function transfer(address dst, uint256 amount)
                  external
                  returns (bool)
              {
                  dst; amount; // Shh
                  delegateAndReturn();
              }
          
              /**
               * @notice Transfer `amount` tokens from `src` to `dst`
               * @param src The address of the source account
               * @param dst The address of the destination account
               * @param amount The number of tokens to transfer
               * @return Whether or not the transfer succeeded
               */
              function transferFrom(
                  address src,
                  address dst,
                  uint256 amount
              )
                  external
                  returns (bool)
              {
                  src; dst; amount; // Shh
                  delegateAndReturn();
              }
          
              /**
               * @notice Approve `spender` to transfer up to `amount` from `src`
               * @dev This will overwrite the approval amount for `spender`
               *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
               * @param spender The address of the account which may transfer tokens
               * @param amount The number of tokens that are approved (-1 means infinite)
               * @return Whether or not the approval succeeded
               */
              function approve(
                  address spender,
                  uint256 amount
              )
                  external
                  returns (bool)
              {
                  spender; amount; // Shh
                  delegateAndReturn();
              }
          
              /**
               * @dev Increase the amount of tokens that an owner has allowed to a spender.
               * This method should be used instead of approve() to avoid the double approval vulnerability
               * described above.
               * @param spender The address which will spend the funds.
               * @param addedValue The amount of tokens to increase the allowance by.
               */
              function increaseAllowance(
                  address spender,
                  uint256 addedValue
              )
                  external
                  returns (bool)
              {
                  spender; addedValue; // Shh
                  delegateAndReturn();
              }
          
              function maxScalingFactor()
                  external
                  view
                  returns (uint256)
              {
                  delegateToViewAndReturn();
              }
          
              function rebase(
                  uint256 epoch,
                  uint256 indexDelta,
                  bool positive
              )
                  external
                  returns (uint256)
              {
                  epoch; indexDelta; positive;
                  delegateAndReturn();
              }
          
              /**
               * @dev Decrease the amount of tokens that an owner has allowed to a spender.
               *
               * @param spender The address which will spend the funds.
               * @param subtractedValue The amount of tokens to decrease the allowance by.
               */
              function decreaseAllowance(
                  address spender,
                  uint256 subtractedValue
              )
                  external
                  returns (bool)
              {
                  spender; subtractedValue; // Shh
                  delegateAndReturn();
              }
          
              /**
               * @notice Get the current allowance from `owner` for `spender`
               * @param owner The address of the account which owns the tokens to be spent
               * @param spender The address of the account which may transfer tokens
               * @return The number of tokens allowed to be spent (-1 means infinite)
               */
              function allowance(
                  address owner,
                  address spender
              )
                  external
                  view
                  returns (uint256)
              {
                  owner; spender; // Shh
                  delegateToViewAndReturn();
              }
          
              /**
               * @notice Get the current allowance from `owner` for `spender`
               * @param delegator The address of the account which has designated a delegate
               * @return Address of delegatee
               */
              function delegates(
                  address delegator
              )
                  external
                  view
                  returns (address)
              {
                  delegator; // Shh
                  delegateToViewAndReturn();
              }
          
              /**
               * @notice Get the token balance of the `owner`
               * @param owner The address of the account to query
               * @return The number of tokens owned by `owner`
               */
              function balanceOf(address owner)
                  external
                  view
                  returns (uint256)
              {
                  owner; // Shh
                  delegateToViewAndReturn();
              }
          
              /**
               * @notice Currently unused. For future compatability
               * @param owner The address of the account to query
               * @return The number of underlying tokens owned by `owner`
               */
              function balanceOfUnderlying(address owner)
                  external
                  view
                  returns (uint256)
              {
                  owner; // Shh
                  delegateToViewAndReturn();
              }
          
              /*** Gov Functions ***/
          
              /**
                * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
                * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
                * @param newPendingGov New pending gov.
                */
              function _setPendingGov(address newPendingGov)
                  external
              {
                  newPendingGov; // Shh
                  delegateAndReturn();
              }
          
              function _setRebaser(address rebaser_)
                  external
              {
                  rebaser_; // Shh
                  delegateAndReturn();
              }
          
              function _setIncentivizer(address incentivizer_)
                  external
              {
                  incentivizer_; // Shh
                  delegateAndReturn();
              }
          
              /**
                * @notice Accepts transfer of gov rights. msg.sender must be pendingGov
                * @dev Gov function for pending gov to accept role and update gov
                * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                */
              function _acceptGov()
                  external
              {
                  delegateAndReturn();
              }
          
          
              function getPriorVotes(address account, uint blockNumber)
                  external
                  view
                  returns (uint256)
              {
                  account; blockNumber;
                  delegateToViewAndReturn();
              }
          
              function delegateBySig(
                  address delegatee,
                  uint nonce,
                  uint expiry,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              )
                  external
              {
                  delegatee; nonce; expiry; v; r; s;
                  delegateAndReturn();
              }
          
              function delegate(address delegatee)
                  external
              {
                  delegatee;
                  delegateAndReturn();
              }
          
              function getCurrentVotes(address account)
                  external
                  view
                  returns (uint256)
              {
                  account;
                  delegateToViewAndReturn();
              }
          
              /**
               * @notice Internal method to delegate execution to another contract
               * @dev It returns to the external caller whatever the implementation returns or forwards reverts
               * @param callee The contract to delegatecall
               * @param data The raw data to delegatecall
               * @return The returned bytes from the delegatecall
               */
              function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
                  (bool success, bytes memory returnData) = callee.delegatecall(data);
                  assembly {
                      if eq(success, 0) {
                          revert(add(returnData, 0x20), returndatasize)
                      }
                  }
                  return returnData;
              }
          
              /**
               * @notice Delegates execution to the implementation contract
               * @dev It returns to the external caller whatever the implementation returns or forwards reverts
               * @param data The raw data to delegatecall
               * @return The returned bytes from the delegatecall
               */
              function delegateToImplementation(bytes memory data) public returns (bytes memory) {
                  return delegateTo(implementation, data);
              }
          
              /**
               * @notice Delegates execution to an implementation contract
               * @dev It returns to the external caller whatever the implementation returns or forwards reverts
               *  There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
               * @param data The raw data to delegatecall
               * @return The returned bytes from the delegatecall
               */
              function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
                  (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
                  assembly {
                      if eq(success, 0) {
                          revert(add(returnData, 0x20), returndatasize)
                      }
                  }
                  return abi.decode(returnData, (bytes));
              }
          
              function delegateToViewAndReturn() private view returns (bytes memory) {
                  (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
          
                  assembly {
                      let free_mem_ptr := mload(0x40)
                      returndatacopy(free_mem_ptr, 0, returndatasize)
          
                      switch success
                      case 0 { revert(free_mem_ptr, returndatasize) }
                      default { return(add(free_mem_ptr, 0x40), returndatasize) }
                  }
              }
          
              function delegateAndReturn() private returns (bytes memory) {
                  (bool success, ) = implementation.delegatecall(msg.data);
          
                  assembly {
                      let free_mem_ptr := mload(0x40)
                      returndatacopy(free_mem_ptr, 0, returndatasize)
          
                      switch success
                      case 0 { revert(free_mem_ptr, returndatasize) }
                      default { return(free_mem_ptr, returndatasize) }
                  }
              }
          
              /**
               * @notice Delegates execution to an implementation contract
               * @dev It returns to the external caller whatever the implementation returns or forwards reverts
               */
              function () external payable {
                  require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback");
          
                  // delegate all other functions to current implementation
                  delegateAndReturn();
              }
          }

          File 4 of 8: Synthetix
          /*
          
          ⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠
          
          This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS!
          
          This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Synthetix release!
          The proxy for this contract can be found here:
          
          https://contracts.synthetix.io/ProxyERC20
          
          *//*
             ____            __   __        __   _
            / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
           _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
          /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
               /___/
          
          * Synthetix: Synthetix.sol
          *
          * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/Synthetix.sol
          * Docs: https://docs.synthetix.io/contracts/Synthetix
          *
          * Contract Dependencies: 
          *	- ExternStateToken
          *	- IAddressResolver
          *	- IERC20
          *	- ISynthetix
          *	- MixinResolver
          *	- Owned
          *	- Proxyable
          *	- SelfDestructible
          *	- State
          * Libraries: 
          *	- Math
          *	- SafeDecimalMath
          *	- SafeMath
          *
          * 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;
          
          
          interface IERC20 {
              // ERC20 Optional Views
              function name() external view returns (string memory);
          
              function symbol() external view returns (string memory);
          
              function decimals() external view returns (uint8);
          
              // Views
              function totalSupply() external view returns (uint);
          
              function balanceOf(address owner) external view returns (uint);
          
              function allowance(address owner, address spender) external view returns (uint);
          
              // Mutative functions
              function transfer(address to, uint value) external returns (bool);
          
              function approve(address spender, uint value) external returns (bool);
          
              function transferFrom(
                  address from,
                  address to,
                  uint value
              ) external returns (bool);
          
              // Events
              event Transfer(address indexed from, address indexed to, uint value);
          
              event Approval(address indexed owner, address indexed spender, uint value);
          }
          
          
          // https://docs.synthetix.io/contracts/Owned
          contract Owned {
              address public owner;
              address public nominatedOwner;
          
              constructor(address _owner) public {
                  require(_owner != address(0), "Owner address cannot be 0");
                  owner = _owner;
                  emit OwnerChanged(address(0), _owner);
              }
          
              function nominateNewOwner(address _owner) external onlyOwner {
                  nominatedOwner = _owner;
                  emit OwnerNominated(_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);
          }
          
          
          // Inheritance
          
          
          // https://docs.synthetix.io/contracts/SelfDestructible
          contract SelfDestructible is Owned {
              uint public constant SELFDESTRUCT_DELAY = 4 weeks;
          
              uint public initiationTime;
              bool public selfDestructInitiated;
          
              address public selfDestructBeneficiary;
          
              constructor() internal {
                  // This contract is abstract, and thus cannot be instantiated directly
                  require(owner != address(0), "Owner must be set");
                  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 payable _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");
                  emit SelfDestructed(selfDestructBeneficiary);
                  selfdestruct(address(uint160(selfDestructBeneficiary)));
              }
          
              event SelfDestructTerminated();
              event SelfDestructed(address beneficiary);
              event SelfDestructInitiated(uint selfDestructDelay);
              event SelfDestructBeneficiaryUpdated(address newBeneficiary);
          }
          
          
          // Inheritance
          
          
          // Internal references
          
          
          // https://docs.synthetix.io/contracts/Proxy
          contract Proxy is Owned {
              Proxyable public target;
          
              constructor(address _owner) public Owned(_owner) {}
          
              function setTarget(Proxyable _target) external onlyOwner {
                  target = _target;
                  emit TargetUpdated(_target);
              }
          
              function _emit(
                  bytes calldata 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)
                          }
                  }
              }
          
              // solhint-disable no-complex-fallback
              function() external payable {
                  // Mutable call setting Proxyable.messageSender as this is using call not 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);
          }
          
          
          // Inheritance
          
          
          // Internal references
          
          
          // https://docs.synthetix.io/contracts/Proxyable
          contract Proxyable is Owned {
              // This contract should be treated like an abstract contract
          
              /* 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 payable _proxy) internal {
                  // This contract is abstract, and thus cannot be instantiated directly
                  require(owner != address(0), "Owner must be set");
          
                  proxy = Proxy(_proxy);
                  emit ProxyUpdated(_proxy);
              }
          
              function setProxy(address payable _proxy) external onlyOwner {
                  proxy = Proxy(_proxy);
                  emit ProxyUpdated(_proxy);
              }
          
              function setIntegrationProxy(address payable _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);
          }
          
          
          /**
           * @dev Wrappers over Solidity's arithmetic operations with added overflow
           * checks.
           *
           * Arithmetic operations in Solidity wrap on overflow. This can easily result
           * in bugs, because programmers usually assume that an overflow raises an
           * error, which is the standard behavior in high level programming languages.
           * `SafeMath` restores this intuition by reverting the transaction when an
           * operation overflows.
           *
           * Using this library instead of the unchecked operations eliminates an entire
           * class of bugs, so it's recommended to use it always.
           */
          library SafeMath {
              /**
               * @dev Returns the addition of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `+` operator.
               *
               * Requirements:
               * - Addition cannot overflow.
               */
              function add(uint256 a, uint256 b) internal pure returns (uint256) {
                  uint256 c = a + b;
                  require(c >= a, "SafeMath: addition overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                  require(b <= a, "SafeMath: subtraction overflow");
                  uint256 c = a - b;
          
                  return c;
              }
          
              /**
               * @dev Returns the multiplication of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `*` operator.
               *
               * Requirements:
               * - Multiplication cannot overflow.
               */
              function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                  // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                  if (a == 0) {
                      return 0;
                  }
          
                  uint256 c = a * b;
                  require(c / a == b, "SafeMath: multiplication overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b) internal pure returns (uint256) {
                  // Solidity only automatically asserts when dividing by 0
                  require(b > 0, "SafeMath: division by zero");
                  uint256 c = a / b;
                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
          
                  return c;
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                  require(b != 0, "SafeMath: modulo by zero");
                  return a % b;
              }
          }
          
          
          // Libraries
          
          
          // https://docs.synthetix.io/contracts/SafeDecimalMath
          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;
              }
          }
          
          
          // Inheritance
          
          
          // https://docs.synthetix.io/contracts/State
          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 _associatedContract) internal {
                  // This contract is abstract, and thus cannot be instantiated directly
                  require(owner != address(0), "Owner must be set");
          
                  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);
          }
          
          
          // Inheritance
          
          
          // https://docs.synthetix.io/contracts/TokenState
          contract TokenState is Owned, State {
              /* ERC20 fields. */
              mapping(address => uint) public balanceOf;
              mapping(address => mapping(address => uint)) public allowance;
          
              constructor(address _owner, address _associatedContract) public Owned(_owner) State(_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;
              }
          }
          
          
          // Inheritance
          
          
          // Libraries
          
          
          // Internal references
          
          
          // https://docs.synthetix.io/contracts/ExternStateToken
          contract ExternStateToken is Owned, 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;
          
              constructor(
                  address payable _proxy,
                  TokenState _tokenState,
                  string memory _name,
                  string memory _symbol,
                  uint _totalSupply,
                  uint8 _decimals,
                  address _owner
              ) public Owned(_owner) SelfDestructible() Proxyable(_proxy) {
                  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) external 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(address(_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 _transferByProxy(
                  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 _transferFromByProxy(
                  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 ========== */
              function addressToBytes32(address input) internal pure returns (bytes32) {
                  return bytes32(uint256(uint160(input)));
              }
          
              event Transfer(address indexed from, address indexed to, uint value);
              bytes32 internal 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, addressToBytes32(from), addressToBytes32(to), 0);
              }
          
              event Approval(address indexed owner, address indexed spender, uint value);
              bytes32 internal 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, addressToBytes32(owner), addressToBytes32(spender), 0);
              }
          
              event TokenStateUpdated(address newTokenState);
              bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
          
              function emitTokenStateUpdated(address newTokenState) internal {
                  proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
              }
          }
          
          
          interface IAddressResolver {
              function getAddress(bytes32 name) external view returns (address);
          
              function getSynth(bytes32 key) external view returns (address);
          
              function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
          }
          
          
          interface ISynth {
              // Views
              function currencyKey() external view returns (bytes32);
          
              function transferableSynths(address account) external view returns (uint);
          
              // Mutative functions
              function transferAndSettle(address to, uint value) external returns (bool);
          
              function transferFromAndSettle(
                  address from,
                  address to,
                  uint value
              ) external returns (bool);
          
              // Restricted: used internally to Synthetix
              function burn(address account, uint amount) external;
          
              function issue(address account, uint amount) external;
          }
          
          
          interface IIssuer {
              // Views
              function anySynthOrSNXRateIsStale() external view returns (bool anyRateStale);
          
              function availableCurrencyKeys() external view returns (bytes32[] memory);
          
              function availableSynthCount() external view returns (uint);
          
              function availableSynths(uint index) external view returns (ISynth);
          
              function canBurnSynths(address account) external view returns (bool);
          
              function collateral(address account) external view returns (uint);
          
              function collateralisationRatio(address issuer) external view returns (uint);
          
              function collateralisationRatioAndAnyRatesStale(address _issuer)
                  external
                  view
                  returns (uint cratio, bool anyRateIsStale);
          
              function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
          
              function lastIssueEvent(address account) external view returns (uint);
          
              function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
          
              function remainingIssuableSynths(address issuer)
                  external
                  view
                  returns (
                      uint maxIssuable,
                      uint alreadyIssued,
                      uint totalSystemDebt
                  );
          
              function synths(bytes32 currencyKey) external view returns (ISynth);
          
              function synthsByAddress(address synthAddress) external view returns (bytes32);
          
              function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
          
              function transferableSynthetixAndAnyRateIsStale(address account, uint balance)
                  external
                  view
                  returns (uint transferable, bool anyRateIsStale);
          
              // Restricted: used internally to Synthetix
              function issueSynths(address from, uint amount) external;
          
              function issueSynthsOnBehalf(
                  address issueFor,
                  address from,
                  uint amount
              ) external;
          
              function issueMaxSynths(address from) external;
          
              function issueMaxSynthsOnBehalf(address issueFor, address from) external;
          
              function burnSynths(address from, uint amount) external;
          
              function burnSynthsOnBehalf(
                  address burnForAddress,
                  address from,
                  uint amount
              ) external;
          
              function burnSynthsToTarget(address from) external;
          
              function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
          
              function liquidateDelinquentAccount(address account, uint susdAmount, address liquidator) external returns (uint totalRedeemed, uint amountToLiquidate);
          }
          
          
          // Inheritance
          
          
          // https://docs.synthetix.io/contracts/AddressResolver
          contract AddressResolver is Owned, IAddressResolver {
              mapping(bytes32 => address) public repository;
          
              constructor(address _owner) public Owned(_owner) {}
          
              /* ========== MUTATIVE FUNCTIONS ========== */
          
              function importAddresses(bytes32[] calldata names, address[] calldata destinations) external 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) external view returns (address) {
                  return repository[name];
              }
          
              function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
                  address _foundAddress = repository[name];
                  require(_foundAddress != address(0), reason);
                  return _foundAddress;
              }
          
              function getSynth(bytes32 key) external view returns (address) {
                  IIssuer issuer = IIssuer(repository["Issuer"]);
                  require(address(issuer) != address(0), "Cannot find Issuer address");
                  return address(issuer.synths(key));
              }
          }
          
          
          // Inheritance
          
          
          // Internal references
          
          
          // https://docs.synthetix.io/contracts/MixinResolver
          contract MixinResolver is Owned {
              AddressResolver public resolver;
          
              mapping(bytes32 => address) private addressCache;
          
              bytes32[] public resolverAddressesRequired;
          
              uint public constant MAX_ADDRESSES_FROM_RESOLVER = 24;
          
              constructor(address _resolver, bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory _addressesToCache) internal {
                  // This contract is abstract, and thus cannot be instantiated directly
                  require(owner != address(0), "Owner must be set");
          
                  for (uint i = 0; i < _addressesToCache.length; i++) {
                      if (_addressesToCache[i] != bytes32(0)) {
                          resolverAddressesRequired.push(_addressesToCache[i]);
                      } else {
                          // End early once an empty item is found - assumes there are no empty slots in
                          // _addressesToCache
                          break;
                      }
                  }
                  resolver = AddressResolver(_resolver);
                  // Do not sync the cache as addresses may not be in the resolver yet
              }
          
              /* ========== SETTERS ========== */
              function setResolverAndSyncCache(AddressResolver _resolver) external onlyOwner {
                  resolver = _resolver;
          
                  for (uint i = 0; i < resolverAddressesRequired.length; i++) {
                      bytes32 name = resolverAddressesRequired[i];
                      // Note: can only be invoked once the resolver has all the targets needed added
                      addressCache[name] = resolver.requireAndGetAddress(name, "Resolver missing target");
                  }
              }
          
              /* ========== VIEWS ========== */
          
              function requireAndGetAddress(bytes32 name, string memory reason) internal view returns (address) {
                  address _foundAddress = addressCache[name];
                  require(_foundAddress != address(0), reason);
                  return _foundAddress;
              }
          
              // Note: this could be made external in a utility contract if addressCache was made public
              // (used for deployment)
              function isResolverCached(AddressResolver _resolver) external view returns (bool) {
                  if (resolver != _resolver) {
                      return false;
                  }
          
                  // otherwise, check everything
                  for (uint i = 0; i < resolverAddressesRequired.length; i++) {
                      bytes32 name = resolverAddressesRequired[i];
                      // false if our cache is invalid or if the resolver doesn't have the required address
                      if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
                          return false;
                      }
                  }
          
                  return true;
              }
          
              // Note: can be made external into a utility contract (used for deployment)
              function getResolverAddressesRequired()
                  external
                  view
                  returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory addressesRequired)
              {
                  for (uint i = 0; i < resolverAddressesRequired.length; i++) {
                      addressesRequired[i] = resolverAddressesRequired[i];
                  }
              }
          
              /* ========== INTERNAL FUNCTIONS ========== */
              function appendToAddressCache(bytes32 name) internal {
                  resolverAddressesRequired.push(name);
                  require(resolverAddressesRequired.length < MAX_ADDRESSES_FROM_RESOLVER, "Max resolver cache size met");
                  // Because this is designed to be called internally in constructors, we don't
                  // check the address exists already in the resolver
                  addressCache[name] = resolver.getAddress(name);
              }
          }
          
          
          interface ISynthetix {
              // Views
              function anySynthOrSNXRateIsStale() external view returns (bool anyRateStale);
          
              function availableCurrencyKeys() external view returns (bytes32[] memory);
          
              function availableSynthCount() external view returns (uint);
          
              function availableSynths(uint index) external view returns (ISynth);
          
              function collateral(address account) external view returns (uint);
          
              function collateralisationRatio(address issuer) external view returns (uint);
          
              function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
          
              function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
          
              function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
          
              function remainingIssuableSynths(address issuer)
                  external
                  view
                  returns (
                      uint maxIssuable,
                      uint alreadyIssued,
                      uint totalSystemDebt
                  );
          
              function synths(bytes32 currencyKey) external view returns (ISynth);
          
              function synthsByAddress(address synthAddress) external view returns (bytes32);
          
              function totalIssuedSynths(bytes32 currencyKey) external view returns (uint);
          
              function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint);
          
              function transferableSynthetix(address account) external view returns (uint transferable);
          
              // Mutative Functions
              function burnSynths(uint amount) external;
          
              function burnSynthsOnBehalf(address burnForAddress, uint amount) external;
          
              function burnSynthsToTarget() external;
          
              function burnSynthsToTargetOnBehalf(address burnForAddress) external;
          
              function exchange(
                  bytes32 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes32 destinationCurrencyKey
              ) external returns (uint amountReceived);
          
              function exchangeOnBehalf(
                  address exchangeForAddress,
                  bytes32 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes32 destinationCurrencyKey
              ) external returns (uint amountReceived);
          
              function issueMaxSynths() external;
          
              function issueMaxSynthsOnBehalf(address issueForAddress) external;
          
              function issueSynths(uint amount) external;
          
              function issueSynthsOnBehalf(address issueForAddress, uint amount) external;
          
              function mint() external returns (bool);
          
              function settle(bytes32 currencyKey)
                  external
                  returns (
                      uint reclaimed,
                      uint refunded,
                      uint numEntries
                  );
          
              function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool);
          }
          
          
          interface ISynthetixState {
              // Views
              function debtLedger(uint index) external view returns (uint);
          
              function issuanceRatio() external view returns (uint);
          
              function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
          
              function debtLedgerLength() external view returns (uint);
          
              function hasIssued(address account) external view returns (bool);
          
              function lastDebtLedgerEntry() external view returns (uint);
          
              // Mutative functions
              function incrementTotalIssuerCount() external;
          
              function decrementTotalIssuerCount() external;
          
              function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
          
              function appendDebtLedgerValue(uint value) external;
          
              function clearIssuanceData(address account) external;
          }
          
          
          interface ISystemStatus {
              // Views
              function requireSystemActive() external view;
          
              function requireIssuanceActive() external view;
          
              function requireExchangeActive() external view;
          
              function requireSynthActive(bytes32 currencyKey) external view;
          
              function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
          }
          
          
          interface IExchanger {
              // Views
              function calculateAmountAfterSettlement(
                  address from,
                  bytes32 currencyKey,
                  uint amount,
                  uint refunded
              ) external view returns (uint amountAfterSettlement);
          
              function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
          
              function settlementOwing(address account, bytes32 currencyKey)
                  external
                  view
                  returns (
                      uint reclaimAmount,
                      uint rebateAmount,
                      uint numEntries
                  );
          
              function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
          
              function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
                  external
                  view
                  returns (uint exchangeFeeRate);
          
              function getAmountsForExchange(
                  uint sourceAmount,
                  bytes32 sourceCurrencyKey,
                  bytes32 destinationCurrencyKey
              )
                  external
                  view
                  returns (
                      uint amountReceived,
                      uint fee,
                      uint exchangeFeeRate
                  );
          
              // Mutative functions
              function exchange(
                  address from,
                  bytes32 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes32 destinationCurrencyKey,
                  address destinationAddress
              ) external returns (uint amountReceived);
          
              function exchangeOnBehalf(
                  address exchangeForAddress,
                  address from,
                  bytes32 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes32 destinationCurrencyKey
              ) external returns (uint amountReceived);
          
              function settle(address from, bytes32 currencyKey)
                  external
                  returns (
                      uint reclaimed,
                      uint refunded,
                      uint numEntries
                  );
          }
          
          
          // Libraries
          
          
          // https://docs.synthetix.io/contracts/Math
          library Math {
              using SafeMath for uint;
              using SafeDecimalMath for uint;
          
              /**
               * @dev Uses "exponentiation by squaring" algorithm where cost is 0(logN)
               * vs 0(N) for naive repeated multiplication.
               * Calculates x^n with x as fixed-point and n as regular unsigned int.
               * Calculates to 18 digits of precision with SafeDecimalMath.unit()
               */
              function powDecimal(uint x, uint n) internal pure returns (uint) {
                  // https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/
          
                  uint result = SafeDecimalMath.unit();
                  while (n > 0) {
                      if (n % 2 != 0) {
                          result = result.multiplyDecimal(x);
                      }
                      x = x.multiplyDecimal(x);
                      n /= 2;
                  }
                  return result;
              }
          }
          
          
          // Inheritance
          
          
          // Libraries
          
          
          // Internal references
          
          
          // https://docs.synthetix.io/contracts/SupplySchedule
          contract SupplySchedule is Owned {
              using SafeMath for uint;
              using SafeDecimalMath for uint;
              using Math for uint;
          
              // Time of the last inflation supply mint event
              uint public lastMintEvent;
          
              // Counter for number of weeks since the start of supply inflation
              uint public weekCounter;
          
              // The number of SNX rewarded to the caller of Synthetix.mint()
              uint public minterReward = 200 * SafeDecimalMath.unit();
          
              // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate.
              // 75e6 * SafeDecimalMath.unit() / 52
              uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307;
          
              // Address of the SynthetixProxy for the onlySynthetix modifier
              address payable public synthetixProxy;
          
              // Max SNX rewards for minter
              uint public constant MAX_MINTER_REWARD = 200 * 1e18;
          
              // How long each inflation period is before mint can be called
              uint public constant MINT_PERIOD_DURATION = 1 weeks;
          
              uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00
              uint public constant MINT_BUFFER = 1 days;
              uint8 public constant SUPPLY_DECAY_START = 40; // Week 40
              uint8 public constant SUPPLY_DECAY_END = 234; //  Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay)
          
              // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate
              uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly
          
              // Percentage growth of terminal supply per annum
              uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa
          
              constructor(
                  address _owner,
                  uint _lastMintEvent,
                  uint _currentWeek
              ) public Owned(_owner) {
                  lastMintEvent = _lastMintEvent;
                  weekCounter = _currentWeek;
              }
          
              // ========== VIEWS ==========
          
              /**
               * @return The amount of SNX mintable for the inflationary supply
               */
              function mintableSupply() external view returns (uint) {
                  uint totalAmount;
          
                  if (!isMintable()) {
                      return totalAmount;
                  }
          
                  uint remainingWeeksToMint = weeksSinceLastIssuance();
          
                  uint currentWeek = weekCounter;
          
                  // Calculate total mintable supply from exponential decay function
                  // The decay function stops after week 234
                  while (remainingWeeksToMint > 0) {
                      currentWeek++;
          
                      if (currentWeek < SUPPLY_DECAY_START) {
                          // If current week is before supply decay we add initial supply to mintableSupply
                          totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY);
                          remainingWeeksToMint--;
                      } else if (currentWeek <= SUPPLY_DECAY_END) {
                          // if current week before supply decay ends we add the new supply for the week
                          // diff between current week and (supply decay start week - 1)
                          uint decayCount = currentWeek.sub(SUPPLY_DECAY_START - 1);
          
                          totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount));
                          remainingWeeksToMint--;
                      } else {
                          // Terminal supply is calculated on the total supply of Synthetix including any new supply
                          // We can compound the remaining week's supply at the fixed terminal rate
                          uint totalSupply = IERC20(synthetixProxy).totalSupply();
                          uint currentTotalSupply = totalSupply.add(totalAmount);
          
                          totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint));
                          remainingWeeksToMint = 0;
                      }
                  }
          
                  return totalAmount;
              }
          
              /**
               * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY
               * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * ()
               */
              function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) {
                  // Apply exponential decay function to number of weeks since
                  // start of inflation smoothing to calculate diminishing supply for the week.
                  uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter);
                  uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay);
          
                  return supplyForWeek;
              }
          
              /**
               * @return A unit amount of terminal inflation supply
               * @dev Weekly compound rate based on number of weeks
               */
              function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) {
                  // rate = (1 + weekly rate) ^ num of weeks
                  uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks);
          
                  // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks
                  return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit()));
              }
          
              /**
               * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor)
               * @return Calculate the numberOfWeeks since last mint rounded down to 1 week
               */
              function weeksSinceLastIssuance() public view returns (uint) {
                  // Get weeks since lastMintEvent
                  // If lastMintEvent not set or 0, then start from inflation start date.
                  uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE);
                  return timeDiff.div(MINT_PERIOD_DURATION);
              }
          
              /**
               * @return boolean whether the MINT_PERIOD_DURATION (7 days)
               * has passed since the lastMintEvent.
               * */
              function isMintable() public view returns (bool) {
                  if (now - lastMintEvent > MINT_PERIOD_DURATION) {
                      return true;
                  }
                  return false;
              }
          
              // ========== MUTATIVE FUNCTIONS ==========
          
              /**
               * @notice Record the mint event from Synthetix by incrementing the inflation
               * week counter for the number of weeks minted (probabaly always 1)
               * and store the time of the event.
               * @param supplyMinted the amount of SNX the total supply was inflated by.
               * */
              function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) {
                  uint numberOfWeeksIssued = weeksSinceLastIssuance();
          
                  // add number of weeks minted to weekCounter
                  weekCounter = weekCounter.add(numberOfWeeksIssued);
          
                  // Update mint event to latest week issued (start date + number of weeks issued * seconds in week)
                  // 1 day time buffer is added so inflation is minted after feePeriod closes
                  lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER);
          
                  emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now);
                  return true;
              }
          
              /**
               * @notice Sets the reward amount of SNX for the caller of the public
               * function Synthetix.mint().
               * This incentivises anyone to mint the inflationary supply and the mintr
               * Reward will be deducted from the inflationary supply and sent to the caller.
               * @param amount the amount of SNX to reward the minter.
               * */
              function setMinterReward(uint amount) external onlyOwner {
                  require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward");
                  minterReward = amount;
                  emit MinterRewardUpdated(minterReward);
              }
          
              // ========== SETTERS ========== */
          
              /**
               * @notice Set the SynthetixProxy should it ever change.
               * SupplySchedule requires Synthetix address as it has the authority
               * to record mint event.
               * */
              function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner {
                  require(address(_synthetixProxy) != address(0), "Address cannot be 0");
                  synthetixProxy = address(uint160(address(_synthetixProxy)));
                  emit SynthetixProxyUpdated(synthetixProxy);
              }
          
              // ========== MODIFIERS ==========
          
              /**
               * @notice Only the Synthetix contract is authorised to call this function
               * */
              modifier onlySynthetix() {
                  require(
                      msg.sender == address(Proxy(address(synthetixProxy)).target()),
                      "Only the synthetix contract can perform this action"
                  );
                  _;
              }
          
              /* ========== EVENTS ========== */
              /**
               * @notice Emitted when the inflationary supply is minted
               * */
              event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp);
          
              /**
               * @notice Emitted when the SNX minter reward amount is updated
               * */
              event MinterRewardUpdated(uint newRewardAmount);
          
              /**
               * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address
               * */
              event SynthetixProxyUpdated(address newAddress);
          }
          
          
          interface IRewardsDistribution {
              // Mutative functions
              function distributeRewards(uint amount) external returns (bool);
          }
          
          
          // Inheritance
          
          
          // Internal references
          
          
          // https://docs.synthetix.io/contracts/Synthetix
          contract Synthetix is IERC20, ExternStateToken, MixinResolver, ISynthetix {
              // ========== STATE VARIABLES ==========
          
              // Available Synths which can be used with the system
              string public constant TOKEN_NAME = "Synthetix Network Token";
              string public constant TOKEN_SYMBOL = "SNX";
              uint8 public constant DECIMALS = 18;
              bytes32 public constant sUSD = "sUSD";
          
              /* ========== ADDRESS RESOLVER CONFIGURATION ========== */
          
              bytes32 private constant CONTRACT_SYNTHETIXSTATE = "SynthetixState";
              bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
              bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
              bytes32 private constant CONTRACT_ISSUER = "Issuer";
              bytes32 private constant CONTRACT_SUPPLYSCHEDULE = "SupplySchedule";
              bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
          
              bytes32[24] private addressesToCache = [
                  CONTRACT_SYSTEMSTATUS,
                  CONTRACT_EXCHANGER,
                  CONTRACT_ISSUER,
                  CONTRACT_SUPPLYSCHEDULE,
                  CONTRACT_REWARDSDISTRIBUTION,
                  CONTRACT_SYNTHETIXSTATE
              ];
          
              // ========== CONSTRUCTOR ==========
          
              constructor(
                  address payable _proxy,
                  TokenState _tokenState,
                  address _owner,
                  uint _totalSupply,
                  address _resolver
              )
                  public
                  ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
                  MixinResolver(_resolver, addressesToCache)
              {}
          
              /* ========== VIEWS ========== */
          
              function synthetixState() internal view returns (ISynthetixState) {
                  return ISynthetixState(requireAndGetAddress(CONTRACT_SYNTHETIXSTATE, "Missing SynthetixState address"));
              }
          
              function systemStatus() internal view returns (ISystemStatus) {
                  return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS, "Missing SystemStatus address"));
              }
          
              function exchanger() internal view returns (IExchanger) {
                  return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER, "Missing Exchanger address"));
              }
          
              function issuer() internal view returns (IIssuer) {
                  return IIssuer(requireAndGetAddress(CONTRACT_ISSUER, "Missing Issuer address"));
              }
          
              function supplySchedule() internal view returns (SupplySchedule) {
                  return SupplySchedule(requireAndGetAddress(CONTRACT_SUPPLYSCHEDULE, "Missing SupplySchedule address"));
              }
          
              function rewardsDistribution() internal view returns (IRewardsDistribution) {
                  return
                      IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION, "Missing RewardsDistribution address"));
              }
          
              function debtBalanceOf(address account, bytes32 currencyKey) external view returns (uint) {
                  return issuer().debtBalanceOf(account, currencyKey);
              }
          
              function totalIssuedSynths(bytes32 currencyKey) external view returns (uint) {
                  return issuer().totalIssuedSynths(currencyKey, false);
              }
          
              function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint) {
                  return issuer().totalIssuedSynths(currencyKey, true);
              }
          
              function availableCurrencyKeys() external view returns (bytes32[] memory) {
                  return issuer().availableCurrencyKeys();
              }
          
              function availableSynthCount() external view returns (uint) {
                  return issuer().availableSynthCount();
              }
          
              function availableSynths(uint index) external view returns (ISynth) {
                  return issuer().availableSynths(index);
              }
          
              function synths(bytes32 currencyKey) external view returns (ISynth) {
                  return issuer().synths(currencyKey);
              }
          
              function synthsByAddress(address synthAddress) external view returns (bytes32) {
                  return issuer().synthsByAddress(synthAddress);
              }
          
              function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) {
                  return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0;
              }
          
              function anySynthOrSNXRateIsStale() external view returns (bool anyRateStale) {
                  return issuer().anySynthOrSNXRateIsStale();
              }
          
              function maxIssuableSynths(address account) external view returns (uint maxIssuable) {
                  return issuer().maxIssuableSynths(account);
              }
          
              function remainingIssuableSynths(address account)
                  external
                  view
                  returns (
                      uint maxIssuable,
                      uint alreadyIssued,
                      uint totalSystemDebt
                  )
              {
                  return issuer().remainingIssuableSynths(account);
              }
          
              function _canTransfer(address account, uint value) internal view returns (bool) {
                  (uint initialDebtOwnership, ) = synthetixState().issuanceData(account);
          
                  if (initialDebtOwnership > 0) {
                      (uint transferable, bool anyRateIsStale) = issuer().transferableSynthetixAndAnyRateIsStale(
                          account,
                          tokenState.balanceOf(account)
                      );
                      require(value <= transferable, "Cannot transfer staked or escrowed SNX");
                      require(!anyRateIsStale, "A synth or SNX rate is stale");
                  }
                  return true;
              }
          
              // ========== MUTATIVE FUNCTIONS ==========
          
              function transfer(address to, uint value) external optionalProxy systemActive returns (bool) {
                  // Ensure they're not trying to exceed their locked amount -- only if they have debt.
                  _canTransfer(messageSender, value);
          
                  // Perform the transfer: if there is a problem an exception will be thrown in this call.
                  _transferByProxy(messageSender, to, value);
          
                  return true;
              }
          
              function transferFrom(
                  address from,
                  address to,
                  uint value
              ) external optionalProxy systemActive returns (bool) {
                  // Ensure they're not trying to exceed their locked amount -- only if they have debt.
                  _canTransfer(from, value);
          
                  // Perform the transfer: if there is a problem,
                  // an exception will be thrown in this call.
                  return _transferFromByProxy(messageSender, from, to, value);
              }
          
              function issueSynths(uint amount) external issuanceActive optionalProxy {
                  return issuer().issueSynths(messageSender, amount);
              }
          
              function issueSynthsOnBehalf(address issueForAddress, uint amount) external issuanceActive optionalProxy {
                  return issuer().issueSynthsOnBehalf(issueForAddress, messageSender, amount);
              }
          
              function issueMaxSynths() external issuanceActive optionalProxy {
                  return issuer().issueMaxSynths(messageSender);
              }
          
              function issueMaxSynthsOnBehalf(address issueForAddress) external issuanceActive optionalProxy {
                  return issuer().issueMaxSynthsOnBehalf(issueForAddress, messageSender);
              }
          
              function burnSynths(uint amount) external issuanceActive optionalProxy {
                  return issuer().burnSynths(messageSender, amount);
              }
          
              function burnSynthsOnBehalf(address burnForAddress, uint amount) external issuanceActive optionalProxy {
                  return issuer().burnSynthsOnBehalf(burnForAddress, messageSender, amount);
              }
          
              function burnSynthsToTarget() external issuanceActive optionalProxy {
                  return issuer().burnSynthsToTarget(messageSender);
              }
          
              function burnSynthsToTargetOnBehalf(address burnForAddress) external issuanceActive optionalProxy {
                  return issuer().burnSynthsToTargetOnBehalf(burnForAddress, messageSender);
              }
          
              function exchange(
                  bytes32 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes32 destinationCurrencyKey
              ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
                  return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender);
              }
          
              function exchangeOnBehalf(
                  address exchangeForAddress,
                  bytes32 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes32 destinationCurrencyKey
              ) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
                  return
                      exchanger().exchangeOnBehalf(
                          exchangeForAddress,
                          messageSender,
                          sourceCurrencyKey,
                          sourceAmount,
                          destinationCurrencyKey
                      );
              }
          
              function settle(bytes32 currencyKey)
                  external
                  optionalProxy
                  returns (
                      uint reclaimed,
                      uint refunded,
                      uint numEntriesSettled
                  )
              {
                  return exchanger().settle(messageSender, currencyKey);
              }
          
              function collateralisationRatio(address _issuer) external view returns (uint) {
                  return issuer().collateralisationRatio(_issuer);
              }
          
              function collateral(address account) external view returns (uint) {
                  return issuer().collateral(account);
              }
          
              function transferableSynthetix(address account) external view returns (uint transferable) {
                  (transferable, ) = issuer().transferableSynthetixAndAnyRateIsStale(account, tokenState.balanceOf(account));
              }
          
              function mint() external issuanceActive returns (bool) {
                  require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set");
          
                  SupplySchedule _supplySchedule = supplySchedule();
                  IRewardsDistribution _rewardsDistribution = rewardsDistribution();
          
                  uint supplyToMint = _supplySchedule.mintableSupply();
                  require(supplyToMint > 0, "No supply is mintable");
          
                  // record minting event before mutation to token supply
                  _supplySchedule.recordMintEvent(supplyToMint);
          
                  // Set minted SNX balance to RewardEscrow's balance
                  // Minus the minterReward and set balance of minter to add reward
                  uint minterReward = _supplySchedule.minterReward();
                  // Get the remainder
                  uint amountToDistribute = supplyToMint.sub(minterReward);
          
                  // Set the token balance to the RewardsDistribution contract
                  tokenState.setBalanceOf(
                      address(_rewardsDistribution),
                      tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute)
                  );
                  emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute);
          
                  // Kick off the distribution of rewards
                  _rewardsDistribution.distributeRewards(amountToDistribute);
          
                  // Assign the minters reward.
                  tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
                  emitTransfer(address(this), msg.sender, minterReward);
          
                  totalSupply = totalSupply.add(supplyToMint);
          
                  return true;
              }
          
              function liquidateDelinquentAccount(address account, uint susdAmount)
                  external
                  systemActive
                  optionalProxy
                  returns (bool)
              {
                  (uint totalRedeemed, uint amountLiquidated) = issuer().liquidateDelinquentAccount(
                      account,
                      susdAmount,
                      messageSender
                  );
          
                  emitAccountLiquidated(account, totalRedeemed, amountLiquidated, messageSender);
          
                  // Transfer SNX redeemed to messageSender
                  // Reverts if amount to redeem is more than balanceOf account, ie due to escrowed balance
                  return _transferByProxy(account, messageSender, totalRedeemed);
              }
          
              // ========== MODIFIERS ==========
          
              modifier onlyExchanger() {
                  require(msg.sender == address(exchanger()), "Only Exchanger can invoke this");
                  _;
              }
          
              modifier systemActive() {
                  systemStatus().requireSystemActive();
                  _;
              }
          
              modifier issuanceActive() {
                  systemStatus().requireIssuanceActive();
                  _;
              }
          
              modifier exchangeActive(bytes32 src, bytes32 dest) {
                  systemStatus().requireExchangeActive();
                  systemStatus().requireSynthsActive(src, dest);
                  _;
              }
          
              // ========== EVENTS ==========
          
              event SynthExchange(
                  address indexed account,
                  bytes32 fromCurrencyKey,
                  uint256 fromAmount,
                  bytes32 toCurrencyKey,
                  uint256 toAmount,
                  address toAddress
              );
              bytes32 internal constant SYNTHEXCHANGE_SIG = keccak256(
                  "SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"
              );
          
              function emitSynthExchange(
                  address account,
                  bytes32 fromCurrencyKey,
                  uint256 fromAmount,
                  bytes32 toCurrencyKey,
                  uint256 toAmount,
                  address toAddress
              ) external onlyExchanger {
                  proxy._emit(
                      abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
                      2,
                      SYNTHEXCHANGE_SIG,
                      addressToBytes32(account),
                      0,
                      0
                  );
              }
          
              event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount);
              bytes32 internal constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)");
          
              function emitExchangeReclaim(
                  address account,
                  bytes32 currencyKey,
                  uint256 amount
              ) external onlyExchanger {
                  proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, addressToBytes32(account), 0, 0);
              }
          
              event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount);
              bytes32 internal constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)");
          
              function emitExchangeRebate(
                  address account,
                  bytes32 currencyKey,
                  uint256 amount
              ) external onlyExchanger {
                  proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, addressToBytes32(account), 0, 0);
              }
          
              event AccountLiquidated(address indexed account, uint snxRedeemed, uint amountLiquidated, address liquidator);
              bytes32 internal constant ACCOUNTLIQUIDATED_SIG = keccak256("AccountLiquidated(address,uint256,uint256,address)");
          
              function emitAccountLiquidated(
                  address account,
                  uint256 snxRedeemed,
                  uint256 amountLiquidated,
                  address liquidator
              ) internal {
                  proxy._emit(
                      abi.encode(snxRedeemed, amountLiquidated, liquidator),
                      2,
                      ACCOUNTLIQUIDATED_SIG,
                      addressToBytes32(account),
                      0,
                      0
                  );
              }
          }
          
          
              

          File 5 of 8: SystemStatus
          /*
             ____            __   __        __   _
            / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
           _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
          /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
               /___/
          
          * Synthetix: SystemStatus.sol
          *
          * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/SystemStatus.sol
          * Docs: https://docs.synthetix.io/contracts/SystemStatus
          *
          * Contract Dependencies: 
          *	- Owned
          * Libraries: (none)
          *
          * 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.25;
          
          
          // https://docs.synthetix.io/contracts/Owned
          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);
          }
          
          
          // https://docs.synthetix.io/contracts/SystemStatus
          contract SystemStatus is Owned {
              struct Status {
                  bool canSuspend;
                  bool canResume;
              }
          
              mapping(bytes32 => mapping(address => Status)) public accessControl;
          
              struct Suspension {
                  bool suspended;
                  // reason is an integer code,
                  // 0 => no reason, 1 => upgrading, 2+ => defined by system usage
                  uint248 reason;
              }
          
              uint248 public constant SUSPENSION_REASON_UPGRADE = 1;
          
              bytes32 public constant SECTION_SYSTEM = "System";
              bytes32 public constant SECTION_ISSUANCE = "Issuance";
              bytes32 public constant SECTION_EXCHANGE = "Exchange";
              bytes32 public constant SECTION_SYNTH = "Synth";
          
              Suspension public systemSuspension;
          
              Suspension public issuanceSuspension;
          
              Suspension public exchangeSuspension;
          
              mapping(bytes32 => Suspension) public synthSuspension;
          
              constructor(address _owner) public Owned(_owner) {
                  _internalUpdateAccessControl(SECTION_SYSTEM, _owner, true, true);
                  _internalUpdateAccessControl(SECTION_ISSUANCE, _owner, true, true);
                  _internalUpdateAccessControl(SECTION_EXCHANGE, _owner, true, true);
                  _internalUpdateAccessControl(SECTION_SYNTH, _owner, true, true);
              }
          
              /* ========== VIEWS ========== */
              function requireSystemActive() external view {
                  _internalRequireSystemActive();
              }
          
              function requireIssuanceActive() external view {
                  // Issuance requires the system be active
                  _internalRequireSystemActive();
                  require(!issuanceSuspension.suspended, "Issuance is suspended. Operation prohibited");
              }
          
              function requireExchangeActive() external view {
                  // Issuance requires the system be active
                  _internalRequireSystemActive();
                  require(!exchangeSuspension.suspended, "Exchange is suspended. Operation prohibited");
              }
          
              function requireSynthActive(bytes32 currencyKey) external view {
                  // Synth exchange and transfer requires the system be active
                  _internalRequireSystemActive();
                  require(!synthSuspension[currencyKey].suspended, "Synth is suspended. Operation prohibited");
              }
          
              function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view {
                  // Synth exchange and transfer requires the system be active
                  _internalRequireSystemActive();
          
                  require(
                      !synthSuspension[sourceCurrencyKey].suspended && !synthSuspension[destinationCurrencyKey].suspended,
                      "One or more synths are suspended. Operation prohibited"
                  );
              }
          
              function isSystemUpgrading() external view returns (bool) {
                  return systemSuspension.suspended && systemSuspension.reason == SUSPENSION_REASON_UPGRADE;
              }
          
              function getSynthSuspensions(bytes32[] synths)
                  external
                  view
                  returns (bool[] memory suspensions, uint256[] memory reasons)
              {
                  suspensions = new bool[](synths.length);
                  reasons = new uint256[](synths.length);
          
                  for (uint i = 0; i < synths.length; i++) {
                      suspensions[i] = synthSuspension[synths[i]].suspended;
                      reasons[i] = synthSuspension[synths[i]].reason;
                  }
              }
          
              /* ========== MUTATIVE FUNCTIONS ========== */
              function updateAccessControl(bytes32 section, address account, bool canSuspend, bool canResume) external onlyOwner {
                  _internalUpdateAccessControl(section, account, canSuspend, canResume);
              }
          
              function suspendSystem(uint256 reason) external {
                  _requireAccessToSuspend(SECTION_SYSTEM);
                  systemSuspension.suspended = true;
                  systemSuspension.reason = uint248(reason);
                  emit SystemSuspended(systemSuspension.reason);
              }
          
              function resumeSystem() external {
                  _requireAccessToResume(SECTION_SYSTEM);
                  systemSuspension.suspended = false;
                  emit SystemResumed(uint256(systemSuspension.reason));
                  systemSuspension.reason = 0;
              }
          
              function suspendIssuance(uint256 reason) external {
                  _requireAccessToSuspend(SECTION_ISSUANCE);
                  issuanceSuspension.suspended = true;
                  issuanceSuspension.reason = uint248(reason);
                  emit IssuanceSuspended(reason);
              }
          
              function resumeIssuance() external {
                  _requireAccessToResume(SECTION_ISSUANCE);
                  issuanceSuspension.suspended = false;
                  emit IssuanceResumed(uint256(issuanceSuspension.reason));
                  issuanceSuspension.reason = 0;
              }
          
              function suspendExchange(uint256 reason) external {
                  _requireAccessToSuspend(SECTION_EXCHANGE);
                  exchangeSuspension.suspended = true;
                  exchangeSuspension.reason = uint248(reason);
                  emit ExchangeSuspended(reason);
              }
          
              function resumeExchange() external {
                  _requireAccessToResume(SECTION_EXCHANGE);
                  exchangeSuspension.suspended = false;
                  emit ExchangeResumed(uint256(exchangeSuspension.reason));
                  exchangeSuspension.reason = 0;
              }
          
              function suspendSynth(bytes32 currencyKey, uint256 reason) external {
                  _requireAccessToSuspend(SECTION_SYNTH);
                  synthSuspension[currencyKey].suspended = true;
                  synthSuspension[currencyKey].reason = uint248(reason);
                  emit SynthSuspended(currencyKey, reason);
              }
          
              function resumeSynth(bytes32 currencyKey) external {
                  _requireAccessToResume(SECTION_SYNTH);
                  emit SynthResumed(currencyKey, uint256(synthSuspension[currencyKey].reason));
                  delete synthSuspension[currencyKey];
              }
          
              /* ========== INTERNAL FUNCTIONS ========== */
          
              function _requireAccessToSuspend(bytes32 section) internal view {
                  require(accessControl[section][msg.sender].canSuspend, "Restricted to access control list");
              }
          
              function _requireAccessToResume(bytes32 section) internal view {
                  require(accessControl[section][msg.sender].canResume, "Restricted to access control list");
              }
          
              function _internalRequireSystemActive() internal view {
                  require(
                      !systemSuspension.suspended,
                      systemSuspension.reason == SUSPENSION_REASON_UPGRADE
                          ? "Synthetix is suspended, upgrade in progress... please stand by"
                          : "Synthetix is suspended. Operation prohibited"
                  );
              }
          
              function _internalUpdateAccessControl(bytes32 section, address account, bool canSuspend, bool canResume) internal {
                  require(
                      section == SECTION_SYSTEM ||
                          section == SECTION_ISSUANCE ||
                          section == SECTION_EXCHANGE ||
                          section == SECTION_SYNTH,
                      "Invalid section supplied"
                  );
                  accessControl[section][account].canSuspend = canSuspend;
                  accessControl[section][account].canResume = canResume;
                  emit AccessControlUpdated(section, account, canSuspend, canResume);
              }
          
              /* ========== EVENTS ========== */
          
              event SystemSuspended(uint256 reason);
              event SystemResumed(uint256 reason);
          
              event IssuanceSuspended(uint256 reason);
              event IssuanceResumed(uint256 reason);
          
              event ExchangeSuspended(uint256 reason);
              event ExchangeResumed(uint256 reason);
          
              event SynthSuspended(bytes32 currencyKey, uint256 reason);
              event SynthResumed(bytes32 currencyKey, uint256 reason);
          
              event AccessControlUpdated(bytes32 indexed section, address indexed account, bool canSuspend, bool canResume);
          }
          
          
              

          File 6 of 8: SynthetixState
          /* ===============================================
          * 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;
          
              /* 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 setMessageSender(address sender)
                  external
                  onlyProxy
              {
                  messageSender = sender;
              }
          
              modifier onlyProxy {
                  require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
                  _;
              }
          
              modifier optionalProxy
              {
                  if (Proxy(msg.sender) != proxy) {
                      messageSender = msg.sender;
                  }
                  _;
              }
          
              modifier optionalProxy_onlyOwner
              {
                  if (Proxy(msg.sender) != proxy) {
                      messageSender = msg.sender;
                  }
                  require(messageSender == owner, "This action can only be performed by the owner");
                  _;
              }
          
              event ProxyUpdated(address proxyAddress);
          }
          
          
          /*
          -----------------------------------------------------------------
          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)
                  Owned(_owner)
                  public
              {
                  require(_owner != address(0), "Owner must not be the zero address");
                  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 the zero address");
                  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 has not yet been initiated");
                  require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
                  address beneficiary = selfDestructBeneficiary;
                  emit SelfDestructed(beneficiary);
                  selfdestruct(beneficiary);
              }
          
              event SelfDestructTerminated();
              event SelfDestructed(address beneficiary);
              event SelfDestructInitiated(uint selfDestructDelay);
              event SelfDestructBeneficiaryUpdated(address newBeneficiary);
          }
          
          
          /**
           * @title SafeMath
           * @dev Math operations with safety checks that revert on error
           */
          library SafeMath {
          
            /**
            * @dev Multiplies two numbers, reverts on overflow.
            */
            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
              // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
              // benefit is lost if 'b' is also tested.
              // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
              if (a == 0) {
                return 0;
              }
          
              uint256 c = a * b;
              require(c / a == b);
          
              return c;
            }
          
            /**
            * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
            */
            function div(uint256 a, uint256 b) internal pure returns (uint256) {
              require(b > 0); // Solidity only automatically asserts when dividing by 0
              uint256 c = a / b;
              // assert(a == b * c + a % b); // There is no case in which this doesn't hold
          
              return c;
            }
          
            /**
            * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
            */
            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
              require(b <= a);
              uint256 c = a - b;
          
              return c;
            }
          
            /**
            * @dev Adds two numbers, reverts on overflow.
            */
            function add(uint256 a, uint256 b) internal pure returns (uint256) {
              uint256 c = a + b;
              require(c >= a);
          
              return c;
            }
          
            /**
            * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
            * reverts when dividing by zero.
            */
            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
              require(b != 0);
              return a % b;
            }
          }
          
          
          /*
          
          -----------------------------------------------------------------
          FILE 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:       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 INFORMATION
          -----------------------------------------------------------------
          
          file:       ExternStateToken.sol
          version:    1.0
          author:     Kevin Brown
          date:       2018-08-06
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          This contract offers a modifer that can prevent reentrancy on
          particular actions. It will not work if you put it on multiple
          functions that can be called from each other. Specifically guard
          external entry points to the contract with the modifier only.
          
          -----------------------------------------------------------------
          */
          
          
          contract ReentrancyPreventer {
              /* ========== MODIFIERS ========== */
              bool isInFunctionBody = false;
          
              modifier preventReentrancy {
                  require(!isInFunctionBody, "Reverted to prevent reentrancy");
                  isInFunctionBody = true;
                  _;
                  isInFunctionBody = false;
              }
          }
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       TokenFallback.sol
          version:    1.0
          author:     Kevin Brown
          date:       2018-08-10
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          This contract provides the logic that's used to call tokenFallback()
          when transfers happen.
          
          It's pulled out into its own module because it's needed in two
          places, so instead of copy/pasting this logic and maininting it
          both in Fee Token and Extern State Token, it's here and depended
          on by both contracts.
          
          -----------------------------------------------------------------
          */
          
          
          contract TokenFallbackCaller is ReentrancyPreventer {
              function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data)
                  internal
                  preventReentrancy
              {
                  /*
                      If we're transferring to a contract and it implements the tokenFallback function, call it.
                      This isn't ERC223 compliant because we don't revert if the contract doesn't implement tokenFallback.
                      This is because many DEXes and other contracts that expect to work with the standard
                      approve / transferFrom workflow don't implement tokenFallback but can still process our tokens as
                      usual, so it feels very harsh and likely to cause trouble if we add this restriction after having
                      previously gone live with a vanilla ERC20.
                  */
          
                  // Is the to address a contract? We can check the code size on that address and know.
                  uint length;
          
                  // solium-disable-next-line security/no-inline-assembly
                  assembly {
                      // Retrieve the size of the code on the recipient address
                      length := extcodesize(recipient)
                  }
          
                  // If there's code there, it's a contract
                  if (length > 0) {
                      // Now we need to optionally call tokenFallback(address from, uint value).
                      // We can't call it the normal way because that reverts when the recipient doesn't implement the function.
          
                      // solium-disable-next-line security/no-low-level-calls
                      recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
          
                      // And yes, we specifically don't care if this call fails, so we're not checking the return value.
                  }
              }
          }
          
          
          /*
          -----------------------------------------------------------------
          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, TokenFallbackCaller {
          
              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)
                  SelfDestructible(_owner)
                  Proxyable(_proxy, _owner)
                  public
              {
                  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, bytes data) 
                  internal
                  returns (bool)
              { 
                  /* Disallow transfers to irretrievable-addresses. */
                  require(to != address(0), "Cannot transfer to the 0 address");
                  require(to != address(this), "Cannot transfer to the underlying contract");
                  require(to != address(proxy), "Cannot transfer to the proxy contract");
          
                  // 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));
          
                  // If the recipient is a contract, we need to call tokenFallback on it so they can do ERC223
                  // actions when receiving our tokens. Unlike the standard, however, we don't revert if the
                  // recipient contract doesn't implement tokenFallback.
                  callTokenFallbackIfNeeded(from, to, value, data);
                  
                  // 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, bytes data)
                  internal
                  returns (bool)
              {
                  return _internalTransfer(from, to, value, data);
              }
          
              /**
               * @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, bytes data)
                  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, data);
              }
          
              /**
               * @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);
              }
          }
          
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       Synth.sol
          version:    2.0
          author:     Kevin Brown
          date:       2018-09-13
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          Synthetix-backed stablecoin contract.
          
          This contract issues synths, which are tokens that mirror various
          flavours of fiat currency.
          
          Synths are issuable by Synthetix Network Token (SNX) holders who 
          have to lock up some value of their SNX to issue S * Cmax synths. 
          Where Cmax issome value less than 1.
          
          A configurable fee is charged on synth transfers and deposited
          into a common pot, which Synthetix holders may withdraw from once
          per fee period.
          
          -----------------------------------------------------------------
          */
          
          
          contract Synth is ExternStateToken {
          
              /* ========== STATE VARIABLES ========== */
          
              FeePool public feePool;
              Synthetix public synthetix;
          
              // Currency key which identifies this Synth to the Synthetix system
              bytes4 public currencyKey;
          
              uint8 constant DECIMALS = 18;
          
              /* ========== CONSTRUCTOR ========== */
          
              constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, FeePool _feePool,
                  string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey
              )
                  ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner)
                  public
              {
                  require(_proxy != 0, "_proxy cannot be 0");
                  require(address(_synthetix) != 0, "_synthetix cannot be 0");
                  require(address(_feePool) != 0, "_feePool cannot be 0");
                  require(_owner != 0, "_owner cannot be 0");
                  require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use");
          
                  feePool = _feePool;
                  synthetix = _synthetix;
                  currencyKey = _currencyKey;
              }
          
              /* ========== SETTERS ========== */
          
              function setSynthetix(Synthetix _synthetix)
                  external
                  optionalProxy_onlyOwner
              {
                  synthetix = _synthetix;
                  emitSynthetixUpdated(_synthetix);
              }
          
              function setFeePool(FeePool _feePool)
                  external
                  optionalProxy_onlyOwner
              {
                  feePool = _feePool;
                  emitFeePoolUpdated(_feePool);
              }
          
              /* ========== MUTATIVE FUNCTIONS ========== */
          
              /**
               * @notice Override ERC20 transfer function in order to 
               * subtract the transaction fee and send it to the fee pool
               * for SNX holders to claim. */
              function transfer(address to, uint value)
                  public
                  optionalProxy
                  notFeeAddress(messageSender)
                  returns (bool)
              {
                  uint amountReceived = feePool.amountReceivedFromTransfer(value);
                  uint fee = value.sub(amountReceived);
          
                  // Send the fee off to the fee pool.
                  synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
          
                  // And send their result off to the destination address
                  bytes memory empty;
                  return _internalTransfer(messageSender, to, amountReceived, empty);
              }
          
              /**
               * @notice Override ERC223 transfer function in order to 
               * subtract the transaction fee and send it to the fee pool
               * for SNX holders to claim. */
              function transfer(address to, uint value, bytes data)
                  public
                  optionalProxy
                  notFeeAddress(messageSender)
                  returns (bool)
              {
                  uint amountReceived = feePool.amountReceivedFromTransfer(value);
                  uint fee = value.sub(amountReceived);
          
                  // Send the fee off to the fee pool, which we don't want to charge an additional fee on
                  synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
          
                  // And send their result off to the destination address
                  return _internalTransfer(messageSender, to, amountReceived, data);
              }
          
              /**
               * @notice Override ERC20 transferFrom function in order to 
               * subtract the transaction fee and send it to the fee pool
               * for SNX holders to claim. */
              function transferFrom(address from, address to, uint value)
                  public
                  optionalProxy
                  notFeeAddress(from)
                  returns (bool)
              {
                  // The fee is deducted from the amount sent.
                  uint amountReceived = feePool.amountReceivedFromTransfer(value);
                  uint fee = value.sub(amountReceived);
          
                  // 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));
          
                  // Send the fee off to the fee pool.
                  synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
          
                  bytes memory empty;
                  return _internalTransfer(from, to, amountReceived, empty);
              }
          
              /**
               * @notice Override ERC223 transferFrom function in order to 
               * subtract the transaction fee and send it to the fee pool
               * for SNX holders to claim. */
              function transferFrom(address from, address to, uint value, bytes data)
                  public
                  optionalProxy
                  notFeeAddress(from)
                  returns (bool)
              {
                  // The fee is deducted from the amount sent.
                  uint amountReceived = feePool.amountReceivedFromTransfer(value);
                  uint fee = value.sub(amountReceived);
          
                  // 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));
          
                  // Send the fee off to the fee pool, which we don't want to charge an additional fee on
                  synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
          
                  return _internalTransfer(from, to, amountReceived, data);
              }
          
              /* Subtract the transfer fee from the senders account so the 
               * receiver gets the exact amount specified to send. */
              function transferSenderPaysFee(address to, uint value)
                  public
                  optionalProxy
                  notFeeAddress(messageSender)
                  returns (bool)
              {
                  uint fee = feePool.transferFeeIncurred(value);
          
                  // Send the fee off to the fee pool, which we don't want to charge an additional fee on
                  synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
          
                  // And send their transfer amount off to the destination address
                  bytes memory empty;
                  return _internalTransfer(messageSender, to, value, empty);
              }
          
              /* Subtract the transfer fee from the senders account so the 
               * receiver gets the exact amount specified to send. */
              function transferSenderPaysFee(address to, uint value, bytes data)
                  public
                  optionalProxy
                  notFeeAddress(messageSender)
                  returns (bool)
              {
                  uint fee = feePool.transferFeeIncurred(value);
          
                  // Send the fee off to the fee pool, which we don't want to charge an additional fee on
                  synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
          
                  // And send their transfer amount off to the destination address
                  return _internalTransfer(messageSender, to, value, data);
              }
          
              /* Subtract the transfer fee from the senders account so the 
               * to address receives the exact amount specified to send. */
              function transferFromSenderPaysFee(address from, address to, uint value)
                  public
                  optionalProxy
                  notFeeAddress(from)
                  returns (bool)
              {
                  uint fee = feePool.transferFeeIncurred(value);
          
                  // 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.add(fee)));
          
                  // Send the fee off to the fee pool, which we don't want to charge an additional fee on
                  synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
          
                  bytes memory empty;
                  return _internalTransfer(from, to, value, empty);
              }
          
              /* Subtract the transfer fee from the senders account so the 
               * to address receives the exact amount specified to send. */
              function transferFromSenderPaysFee(address from, address to, uint value, bytes data)
                  public
                  optionalProxy
                  notFeeAddress(from)
                  returns (bool)
              {
                  uint fee = feePool.transferFeeIncurred(value);
          
                  // 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.add(fee)));
          
                  // Send the fee off to the fee pool, which we don't want to charge an additional fee on
                  synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
          
                  return _internalTransfer(from, to, value, data);
              }
          
              // Override our internal transfer to inject preferred currency support
              function _internalTransfer(address from, address to, uint value, bytes data)
                  internal
                  returns (bool)
              {
                  bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to);
          
                  // Do they have a preferred currency that's not us? If so we need to exchange
                  if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) {
                      return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to);
                  } else {
                      // Otherwise we just transfer
                      return super._internalTransfer(from, to, value, data);
                  }
              }
          
              // Allow synthetix to issue a certain number of synths from an account.
              function issue(address account, uint amount)
                  external
                  onlySynthetixOrFeePool
              {
                  tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
                  totalSupply = totalSupply.add(amount);
                  emitTransfer(address(0), account, amount);
                  emitIssued(account, amount);
              }
          
              // Allow synthetix or another synth contract to burn a certain number of synths from an account.
              function burn(address account, uint amount)
                  external
                  onlySynthetixOrFeePool
              {
                  tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
                  totalSupply = totalSupply.sub(amount);
                  emitTransfer(account, address(0), amount);
                  emitBurned(account, amount);
              }
          
              // Allow synthetix to trigger a token fallback call from our synths so users get notified on
              // exchange as well as transfer
              function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount)
                  external
                  onlySynthetixOrFeePool
              {
                  bytes memory empty;
                  callTokenFallbackIfNeeded(sender, recipient, amount, empty);
              }
          
              /* ========== MODIFIERS ========== */
          
              modifier onlySynthetixOrFeePool() {
                  bool isSynthetix = msg.sender == address(synthetix);
                  bool isFeePool = msg.sender == address(feePool);
          
                  require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action");
                  _;
              }
          
              modifier notFeeAddress(address account) {
                  require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address");
                  _;
              }
          
              /* ========== EVENTS ========== */
          
              event SynthetixUpdated(address newSynthetix);
              bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
              function emitSynthetixUpdated(address newSynthetix) internal {
                  proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
              }
          
              event FeePoolUpdated(address newFeePool);
              bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)");
              function emitFeePoolUpdated(address newFeePool) internal {
                  proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0);
              }
          
              event Issued(address indexed account, uint value);
              bytes32 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 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:       FeePool.sol
          version:    1.0
          author:     Kevin Brown
          date:       2018-10-15
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          The FeePool is a place for users to interact with the fees that
          have been generated from the Synthetix system if they've helped
          to create the economy.
          
          Users stake Synthetix to create Synths. As Synth users transact,
          a small fee is deducted from each transaction, which collects
          in the fee pool. Fees are immediately converted to XDRs, a type
          of reserve currency similar to SDRs used by the IMF:
          https://www.imf.org/en/About/Factsheets/Sheets/2016/08/01/14/51/Special-Drawing-Right-SDR
          
          Users are entitled to withdraw fees from periods that they participated
          in fully, e.g. they have to stake before the period starts. They
          can withdraw fees for the last 6 periods as a single lump sum.
          Currently fee periods are 7 days long, meaning it's assumed
          users will withdraw their fees approximately once a month. Fees
          which are not withdrawn are redistributed to the whole pool,
          enabling these non-claimed fees to go back to the rest of the commmunity.
          
          Fees can be withdrawn in any synth currency.
          
          -----------------------------------------------------------------
          */
          
          
          contract FeePool is Proxyable, SelfDestructible {
          
              using SafeMath for uint;
              using SafeDecimalMath for uint;
          
              Synthetix public synthetix;
          
              // A percentage fee charged on each transfer.
              uint public transferFeeRate;
          
              // Transfer fee may not exceed 10%.
              uint constant public MAX_TRANSFER_FEE_RATE = SafeDecimalMath.unit() / 10;
          
              // A percentage fee charged on each exchange between currencies.
              uint public exchangeFeeRate;
          
              // Exchange fee may not exceed 10%.
              uint constant public MAX_EXCHANGE_FEE_RATE = SafeDecimalMath.unit() / 10;
          
              // The address with the authority to distribute fees.
              address public feeAuthority;
          
              // Where fees are pooled in XDRs.
              address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
          
              // This struct represents the issuance activity that's happened in a fee period.
              struct FeePeriod {
                  uint feePeriodId;
                  uint startingDebtIndex;
                  uint startTime;
                  uint feesToDistribute;
                  uint feesClaimed;
              }
          
              // The last 6 fee periods are all that you can claim from.
              // These are stored and managed from [0], such that [0] is always
              // the most recent fee period, and [5] is always the oldest fee
              // period that users can claim for.
              uint8 constant public FEE_PERIOD_LENGTH = 6;
              FeePeriod[FEE_PERIOD_LENGTH] public recentFeePeriods;
          
              // The next fee period will have this ID.
              uint public nextFeePeriodId;
          
              // How long a fee period lasts at a minimum. It is required for the
              // fee authority to roll over the periods, so they are not guaranteed
              // to roll over at exactly this duration, but the contract enforces
              // that they cannot roll over any quicker than this duration.
              uint public feePeriodDuration = 1 weeks;
          
              // The fee period must be between 1 day and 60 days.
              uint public constant MIN_FEE_PERIOD_DURATION = 1 days;
              uint public constant MAX_FEE_PERIOD_DURATION = 60 days;
          
              // The last period a user has withdrawn their fees in, identified by the feePeriodId
              mapping(address => uint) public lastFeeWithdrawal;
          
              // Users receive penalties if their collateralisation ratio drifts out of our desired brackets
              // We precompute the brackets and penalties to save gas.
              uint constant TWENTY_PERCENT = (20 * SafeDecimalMath.unit()) / 100;
              uint constant TWENTY_FIVE_PERCENT = (25 * SafeDecimalMath.unit()) / 100;
              uint constant THIRTY_PERCENT = (30 * SafeDecimalMath.unit()) / 100;
              uint constant FOURTY_PERCENT = (40 * SafeDecimalMath.unit()) / 100;
              uint constant FIFTY_PERCENT = (50 * SafeDecimalMath.unit()) / 100;
              uint constant SEVENTY_FIVE_PERCENT = (75 * SafeDecimalMath.unit()) / 100;
          
              constructor(address _proxy, address _owner, Synthetix _synthetix, address _feeAuthority, uint _transferFeeRate, uint _exchangeFeeRate)
                  SelfDestructible(_owner)
                  Proxyable(_proxy, _owner)
                  public
              {
                  // Constructed fee rates should respect the maximum fee rates.
                  require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
                  require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Constructed exchange fee rate should respect the maximum fee rate");
          
                  synthetix = _synthetix;
                  feeAuthority = _feeAuthority;
                  transferFeeRate = _transferFeeRate;
                  exchangeFeeRate = _exchangeFeeRate;
          
                  // Set our initial fee period
                  recentFeePeriods[0].feePeriodId = 1;
                  recentFeePeriods[0].startTime = now;
                  // Gas optimisation: These do not need to be initialised. They start at 0.
                  // recentFeePeriods[0].startingDebtIndex = 0;
                  // recentFeePeriods[0].feesToDistribute = 0;
          
                  // And the next one starts at 2.
                  nextFeePeriodId = 2;
              }
          
              /**
               * @notice Set the exchange fee, anywhere within the range 0-10%.
               * @dev The fee rate is in decimal format, with UNIT being the value of 100%.
               */
              function setExchangeFeeRate(uint _exchangeFeeRate)
                  external
                  optionalProxy_onlyOwner
              {
                  require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Exchange fee rate must be below MAX_EXCHANGE_FEE_RATE");
          
                  exchangeFeeRate = _exchangeFeeRate;
          
                  emitExchangeFeeUpdated(_exchangeFeeRate);
              }
          
              /**
               * @notice Set the transfer fee, anywhere within the range 0-10%.
               * @dev The fee rate is in decimal format, with UNIT being the value of 100%.
               */
              function setTransferFeeRate(uint _transferFeeRate)
                  external
                  optionalProxy_onlyOwner
              {
                  require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
          
                  transferFeeRate = _transferFeeRate;
          
                  emitTransferFeeUpdated(_transferFeeRate);
              }
          
              /**
               * @notice Set the address of the user/contract responsible for collecting or
               * distributing fees.
               */
              function setFeeAuthority(address _feeAuthority)
                  external
                  optionalProxy_onlyOwner
              {
                  feeAuthority = _feeAuthority;
          
                  emitFeeAuthorityUpdated(_feeAuthority);
              }
          
              /**
               * @notice Set the fee period duration
               */
              function setFeePeriodDuration(uint _feePeriodDuration)
                  external
                  optionalProxy_onlyOwner
              {
                  require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, "New fee period cannot be less than minimum fee period duration");
                  require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, "New fee period cannot be greater than maximum fee period duration");
          
                  feePeriodDuration = _feePeriodDuration;
          
                  emitFeePeriodDurationUpdated(_feePeriodDuration);
              }
          
              /**
               * @notice Set the synthetix contract
               */
              function setSynthetix(Synthetix _synthetix)
                  external
                  optionalProxy_onlyOwner
              {
                  require(address(_synthetix) != address(0), "New Synthetix must be non-zero");
          
                  synthetix = _synthetix;
          
                  emitSynthetixUpdated(_synthetix);
              }
          
              /**
               * @notice The Synthetix contract informs us when fees are paid.
               */
              function feePaid(bytes4 currencyKey, uint amount)
                  external
                  onlySynthetix
              {
                  uint xdrAmount = synthetix.effectiveValue(currencyKey, amount, "XDR");
          
                  // Which we keep track of in XDRs in our fee pool.
                  recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.add(xdrAmount);
              }
          
              /**
               * @notice Close the current fee period and start a new one. Only callable by the fee authority.
               */
              function closeCurrentFeePeriod()
                  external
                  onlyFeeAuthority
              {
                  require(recentFeePeriods[0].startTime <= (now - feePeriodDuration), "It is too early to close the current fee period");
          
                  FeePeriod memory secondLastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 2];
                  FeePeriod memory lastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 1];
          
                  // Any unclaimed fees from the last period in the array roll back one period.
                  // Because of the subtraction here, they're effectively proportionally redistributed to those who
                  // have already claimed from the old period, available in the new period.
                  // The subtraction is important so we don't create a ticking time bomb of an ever growing
                  // number of fees that can never decrease and will eventually overflow at the end of the fee pool.
                  recentFeePeriods[FEE_PERIOD_LENGTH - 2].feesToDistribute = lastFeePeriod.feesToDistribute
                      .sub(lastFeePeriod.feesClaimed)
                      .add(secondLastFeePeriod.feesToDistribute);
          
                  // Shift the previous fee periods across to make room for the new one.
                  // Condition checks for overflow when uint subtracts one from zero
                  // Could be written with int instead of uint, but then we have to convert everywhere
                  // so it felt better from a gas perspective to just change the condition to check
                  // for overflow after subtracting one from zero.
                  for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) {
                      uint next = i + 1;
          
                      recentFeePeriods[next].feePeriodId = recentFeePeriods[i].feePeriodId;
                      recentFeePeriods[next].startingDebtIndex = recentFeePeriods[i].startingDebtIndex;
                      recentFeePeriods[next].startTime = recentFeePeriods[i].startTime;
                      recentFeePeriods[next].feesToDistribute = recentFeePeriods[i].feesToDistribute;
                      recentFeePeriods[next].feesClaimed = recentFeePeriods[i].feesClaimed;
                  }
          
                  // Clear the first element of the array to make sure we don't have any stale values.
                  delete recentFeePeriods[0];
          
                  // Open up the new fee period
                  recentFeePeriods[0].feePeriodId = nextFeePeriodId;
                  recentFeePeriods[0].startingDebtIndex = synthetix.synthetixState().debtLedgerLength();
                  recentFeePeriods[0].startTime = now;
          
                  nextFeePeriodId = nextFeePeriodId.add(1);
          
                  emitFeePeriodClosed(recentFeePeriods[1].feePeriodId);
              }
          
              /**
              * @notice Claim fees for last period when available or not already withdrawn.
              * @param currencyKey Synth currency you wish to receive the fees in.
              */
              function claimFees(bytes4 currencyKey)
                  external
                  optionalProxy
                  returns (bool)
              {
                  uint availableFees = feesAvailable(messageSender, "XDR");
          
                  require(availableFees > 0, "No fees available for period, or fees already claimed");
          
                  lastFeeWithdrawal[messageSender] = recentFeePeriods[1].feePeriodId;
          
                  // Record the fee payment in our recentFeePeriods
                  _recordFeePayment(availableFees);
          
                  // Send them their fees
                  _payFees(messageSender, availableFees, currencyKey);
          
                  emitFeesClaimed(messageSender, availableFees);
          
                  return true;
              }
          
              /**
               * @notice Record the fee payment in our recentFeePeriods.
               * @param xdrAmount The amout of fees priced in XDRs.
               */
              function _recordFeePayment(uint xdrAmount)
                  internal
              {
                  // Don't assign to the parameter
                  uint remainingToAllocate = xdrAmount;
          
                  // Start at the oldest period and record the amount, moving to newer periods
                  // until we've exhausted the amount.
                  // The condition checks for overflow because we're going to 0 with an unsigned int.
                  for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
                      uint delta = recentFeePeriods[i].feesToDistribute.sub(recentFeePeriods[i].feesClaimed);
          
                      if (delta > 0) {
                          // Take the smaller of the amount left to claim in the period and the amount we need to allocate
                          uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate;
          
                          recentFeePeriods[i].feesClaimed = recentFeePeriods[i].feesClaimed.add(amountInPeriod);
                          remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
          
                          // No need to continue iterating if we've recorded the whole amount;
                          if (remainingToAllocate == 0) return;
                      }
                  }
          
                  // If we hit this line, we've exhausted our fee periods, but still have more to allocate. Wat?
                  // If this happens it's a definite bug in the code, so assert instead of require.
                  assert(remainingToAllocate == 0);
              }
          
              /**
              * @notice Send the fees to claiming address.
              * @param account The address to send the fees to.
              * @param xdrAmount The amount of fees priced in XDRs.
              * @param destinationCurrencyKey The synth currency the user wishes to receive their fees in (convert to this currency).
              */
              function _payFees(address account, uint xdrAmount, bytes4 destinationCurrencyKey)
                  internal
                  notFeeAddress(account)
              {
                  require(account != address(0), "Account can't be 0");
                  require(account != address(this), "Can't send fees to fee pool");
                  require(account != address(proxy), "Can't send fees to proxy");
                  require(account != address(synthetix), "Can't send fees to synthetix");
          
                  Synth xdrSynth = synthetix.synths("XDR");
                  Synth destinationSynth = synthetix.synths(destinationCurrencyKey);
          
                  // Note: We don't need to check the fee pool balance as the burn() below will do a safe subtraction which requires
                  // the subtraction to not overflow, which would happen if the balance is not sufficient.
          
                  // Burn the source amount
                  xdrSynth.burn(FEE_ADDRESS, xdrAmount);
          
                  // How much should they get in the destination currency?
                  uint destinationAmount = synthetix.effectiveValue("XDR", xdrAmount, destinationCurrencyKey);
          
                  // There's no fee on withdrawing fees, as that'd be way too meta.
          
                  // Mint their new synths
                  destinationSynth.issue(account, destinationAmount);
          
                  // Nothing changes as far as issuance data goes because the total value in the system hasn't changed.
          
                  // Call the ERC223 transfer callback if needed
                  destinationSynth.triggerTokenFallbackIfNeeded(FEE_ADDRESS, account, destinationAmount);
              }
          
              /**
               * @notice Calculate the Fee charged on top of a value being sent
               * @return Return the fee charged
               */
              function transferFeeIncurred(uint value)
                  public
                  view
                  returns (uint)
              {
                  return value.multiplyDecimal(transferFeeRate);
          
                  // Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
                  // This is on the basis that transfers less than this value will result in a nil fee.
                  // Probably too insignificant to worry about, but the following code will achieve it.
                  //      if (fee == 0 && transferFeeRate != 0) {
                  //          return _value;
                  //      }
                  //      return fee;
              }
          
              /**
               * @notice The value that you would need to send so that the recipient receives
               * a specified value.
               * @param value The value you want the recipient to receive
               */
              function transferredAmountToReceive(uint value)
                  external
                  view
                  returns (uint)
              {
                  return value.add(transferFeeIncurred(value));
              }
          
              /**
               * @notice The amount the recipient will receive if you send a certain number of tokens.
               * @param value The amount of tokens you intend to send.
               */
              function amountReceivedFromTransfer(uint value)
                  external
                  view
                  returns (uint)
              {
                  return value.divideDecimal(transferFeeRate.add(SafeDecimalMath.unit()));
              }
          
              /**
               * @notice Calculate the fee charged on top of a value being sent via an exchange
               * @return Return the fee charged
               */
              function exchangeFeeIncurred(uint value)
                  public
                  view
                  returns (uint)
              {
                  return value.multiplyDecimal(exchangeFeeRate);
          
                  // Exchanges less than the reciprocal of exchangeFeeRate should be completely eaten up by fees.
                  // This is on the basis that exchanges less than this value will result in a nil fee.
                  // Probably too insignificant to worry about, but the following code will achieve it.
                  //      if (fee == 0 && exchangeFeeRate != 0) {
                  //          return _value;
                  //      }
                  //      return fee;
              }
          
              /**
               * @notice The value that you would need to get after currency exchange so that the recipient receives
               * a specified value.
               * @param value The value you want the recipient to receive
               */
              function exchangedAmountToReceive(uint value)
                  external
                  view
                  returns (uint)
              {
                  return value.add(exchangeFeeIncurred(value));
              }
          
              /**
               * @notice The amount the recipient will receive if you are performing an exchange and the
               * destination currency will be worth a certain number of tokens.
               * @param value The amount of destination currency tokens they received after the exchange.
               */
              function amountReceivedFromExchange(uint value)
                  external
                  view
                  returns (uint)
              {
                  return value.divideDecimal(exchangeFeeRate.add(SafeDecimalMath.unit()));
              }
          
              /**
               * @notice The total fees available in the system to be withdrawn, priced in currencyKey currency
               * @param currencyKey The currency you want to price the fees in
               */
              function totalFeesAvailable(bytes4 currencyKey)
                  external
                  view
                  returns (uint)
              {
                  uint totalFees = 0;
          
                  // Fees in fee period [0] are not yet available for withdrawal
                  for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
                      totalFees = totalFees.add(recentFeePeriods[i].feesToDistribute);
                      totalFees = totalFees.sub(recentFeePeriods[i].feesClaimed);
                  }
          
                  return synthetix.effectiveValue("XDR", totalFees, currencyKey);
              }
          
              /**
               * @notice The fees available to be withdrawn by a specific account, priced in currencyKey currency
               * @param currencyKey The currency you want to price the fees in
               */
              function feesAvailable(address account, bytes4 currencyKey)
                  public
                  view
                  returns (uint)
              {
                  // Add up the fees
                  uint[FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);
          
                  uint totalFees = 0;
          
                  // Fees in fee period [0] are not yet available for withdrawal
                  for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
                      totalFees = totalFees.add(userFees[i]);
                  }
          
                  // And convert them to their desired currency
                  return synthetix.effectiveValue("XDR", totalFees, currencyKey);
              }
          
              /**
               * @notice The penalty a particular address would incur if its fees were withdrawn right now
               * @param account The address you want to query the penalty for
               */
              function currentPenalty(address account)
                  public
                  view
                  returns (uint)
              {
                  uint ratio = synthetix.collateralisationRatio(account);
          
                  // Users receive a different amount of fees depending on how their collateralisation ratio looks right now.
                  // 0% - 20%: Fee is calculated based on percentage of economy issued.
                  // 20% - 30%: 25% reduction in fees
                  // 30% - 40%: 50% reduction in fees
                  // >40%: 75% reduction in fees
                  if (ratio <= TWENTY_PERCENT) {
                      return 0;
                  } else if (ratio > TWENTY_PERCENT && ratio <= THIRTY_PERCENT) {
                      return TWENTY_FIVE_PERCENT;
                  } else if (ratio > THIRTY_PERCENT && ratio <= FOURTY_PERCENT) {
                      return FIFTY_PERCENT;
                  }
          
                  return SEVENTY_FIVE_PERCENT;
              }
          
              /**
               * @notice Calculates fees by period for an account, priced in XDRs
               * @param account The address you want to query the fees by penalty for
               */
              function feesByPeriod(address account)
                  public
                  view
                  returns (uint[FEE_PERIOD_LENGTH])
              {
                  uint[FEE_PERIOD_LENGTH] memory result;
          
                  // What's the user's debt entry index and the debt they owe to the system
                  uint initialDebtOwnership;
                  uint debtEntryIndex;
                  (initialDebtOwnership, debtEntryIndex) = synthetix.synthetixState().issuanceData(account);
          
                  // If they don't have any debt ownership, they don't have any fees
                  if (initialDebtOwnership == 0) return result;
          
                  // If there are no XDR synths, then they don't have any fees
                  uint totalSynths = synthetix.totalIssuedSynths("XDR");
                  if (totalSynths == 0) return result;
          
                  uint debtBalance = synthetix.debtBalanceOf(account, "XDR");
                  uint userOwnershipPercentage = debtBalance.divideDecimal(totalSynths);
                  uint penalty = currentPenalty(account);
                  
                  // Go through our fee periods and figure out what we owe them.
                  // The [0] fee period is not yet ready to claim, but it is a fee period that they can have
                  // fees owing for, so we need to report on it anyway.
                  for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) {
                      // Were they a part of this period in its entirety?
                      // We don't allow pro-rata participation to reduce the ability to game the system by
                      // issuing and burning multiple times in a period or close to the ends of periods.
                      if (recentFeePeriods[i].startingDebtIndex > debtEntryIndex &&
                          lastFeeWithdrawal[account] < recentFeePeriods[i].feePeriodId) {
          
                          // And since they were, they're entitled to their percentage of the fees in this period
                          uint feesFromPeriodWithoutPenalty = recentFeePeriods[i].feesToDistribute
                              .multiplyDecimal(userOwnershipPercentage);
          
                          // Less their penalty if they have one.
                          uint penaltyFromPeriod = feesFromPeriodWithoutPenalty.multiplyDecimal(penalty);
                          uint feesFromPeriod = feesFromPeriodWithoutPenalty.sub(penaltyFromPeriod);
          
                          result[i] = feesFromPeriod;
                      }
                  }
          
                  return result;
              }
          
              modifier onlyFeeAuthority
              {
                  require(msg.sender == feeAuthority, "Only the fee authority can perform this action");
                  _;
              }
          
              modifier onlySynthetix
              {
                  require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action");
                  _;
              }
          
              modifier notFeeAddress(address account) {
                  require(account != FEE_ADDRESS, "Fee address not allowed");
                  _;
              }
          
              event TransferFeeUpdated(uint newFeeRate);
              bytes32 constant TRANSFERFEEUPDATED_SIG = keccak256("TransferFeeUpdated(uint256)");
              function emitTransferFeeUpdated(uint newFeeRate) internal {
                  proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEEUPDATED_SIG, 0, 0, 0);
              }
          
              event ExchangeFeeUpdated(uint newFeeRate);
              bytes32 constant EXCHANGEFEEUPDATED_SIG = keccak256("ExchangeFeeUpdated(uint256)");
              function emitExchangeFeeUpdated(uint newFeeRate) internal {
                  proxy._emit(abi.encode(newFeeRate), 1, EXCHANGEFEEUPDATED_SIG, 0, 0, 0);
              }
          
              event FeePeriodDurationUpdated(uint newFeePeriodDuration);
              bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
              function emitFeePeriodDurationUpdated(uint newFeePeriodDuration) internal {
                  proxy._emit(abi.encode(newFeePeriodDuration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
              }
          
              event FeeAuthorityUpdated(address newFeeAuthority);
              bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
              function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
                  proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
              }
          
              event FeePeriodClosed(uint feePeriodId);
              bytes32 constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)");
              function emitFeePeriodClosed(uint feePeriodId) internal {
                  proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0);
              }
          
              event FeesClaimed(address account, uint xdrAmount);
              bytes32 constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256)");
              function emitFeesClaimed(address account, uint xdrAmount) internal {
                  proxy._emit(abi.encode(account, xdrAmount), 1, FEESCLAIMED_SIG, 0, 0, 0);
              }
          
              event SynthetixUpdated(address newSynthetix);
              bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
              function emitSynthetixUpdated(address newSynthetix) internal {
                  proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
              }
          }
          
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       LimitedSetup.sol
          version:    1.1
          author:     Anton Jurisevic
          
          date:       2018-05-15
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          A contract with a limited setup period. Any function modified
          with the setup modifier will cease to work after the
          conclusion of the configurable-length post-construction setup period.
          
          -----------------------------------------------------------------
          */
          
          
          /**
           * @title Any function decorated with the modifier this contract provides
           * deactivates after a specified setup period.
           */
          contract LimitedSetup {
          
              uint setupExpiryTime;
          
              /**
               * @dev LimitedSetup Constructor.
               * @param setupDuration The time the setup period will last for.
               */
              constructor(uint setupDuration)
                  public
              {
                  setupExpiryTime = now + setupDuration;
              }
          
              modifier onlyDuringSetup
              {
                  require(now < setupExpiryTime, "Can only perform this action during setup");
                  _;
              }
          }
          
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       SynthetixEscrow.sol
          version:    1.1
          author:     Anton Jurisevic
                      Dominic Romanowski
                      Mike Spain
          
          date:       2018-05-29
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          This contract allows the foundation to apply unique vesting
          schedules to synthetix funds sold at various discounts in the token
          sale. SynthetixEscrow gives users the ability to inspect their
          vested funds, their quantities and vesting dates, and to withdraw
          the fees that accrue on those funds.
          
          The fees are handled by withdrawing the entire fee allocation
          for all SNX inside the escrow contract, and then allowing
          the contract itself to subdivide that pool up proportionally within
          itself. Every time the fee period rolls over in the main Synthetix
          contract, the SynthetixEscrow fee pool is remitted back into the
          main fee pool to be redistributed in the next fee period.
          
          -----------------------------------------------------------------
          */
          
          
          /**
           * @title A contract to hold escrowed SNX and free them at given schedules.
           */
          contract SynthetixEscrow is Owned, LimitedSetup(8 weeks) {
          
              using SafeMath for uint;
          
              /* The corresponding Synthetix contract. */
              Synthetix public synthetix;
          
              /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
               * These are the times at which each given quantity of SNX vests. */
              mapping(address => uint[2][]) public vestingSchedules;
          
              /* An account's total vested synthetix balance to save recomputing this for fee extraction purposes. */
              mapping(address => uint) public totalVestedAccountBalance;
          
              /* The total remaining vested balance, for verifying the actual synthetix balance of this contract against. */
              uint public totalVestedBalance;
          
              uint constant TIME_INDEX = 0;
              uint constant QUANTITY_INDEX = 1;
          
              /* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
              uint constant MAX_VESTING_ENTRIES = 20;
          
          
              /* ========== CONSTRUCTOR ========== */
          
              constructor(address _owner, Synthetix _synthetix)
                  Owned(_owner)
                  public
              {
                  synthetix = _synthetix;
              }
          
          
              /* ========== SETTERS ========== */
          
              function setSynthetix(Synthetix _synthetix)
                  external
                  onlyOwner
              {
                  synthetix = _synthetix;
                  emit SynthetixUpdated(_synthetix);
              }
          
          
              /* ========== VIEW FUNCTIONS ========== */
          
              /**
               * @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
               */
              function balanceOf(address account)
                  public
                  view
                  returns (uint)
              {
                  return totalVestedAccountBalance[account];
              }
          
              /**
               * @notice The number of vesting dates in an account's schedule.
               */
              function numVestingEntries(address account)
                  public
                  view
                  returns (uint)
              {
                  return vestingSchedules[account].length;
              }
          
              /**
               * @notice Get a particular schedule entry for an account.
               * @return A pair of uints: (timestamp, synthetix quantity).
               */
              function getVestingScheduleEntry(address account, uint index)
                  public
                  view
                  returns (uint[2])
              {
                  return vestingSchedules[account][index];
              }
          
              /**
               * @notice Get the time at which a given schedule entry will vest.
               */
              function getVestingTime(address account, uint index)
                  public
                  view
                  returns (uint)
              {
                  return getVestingScheduleEntry(account,index)[TIME_INDEX];
              }
          
              /**
               * @notice Get the quantity of SNX associated with a given schedule entry.
               */
              function getVestingQuantity(address account, uint index)
                  public
                  view
                  returns (uint)
              {
                  return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
              }
          
              /**
               * @notice Obtain the index of the next schedule entry that will vest for a given user.
               */
              function getNextVestingIndex(address account)
                  public
                  view
                  returns (uint)
              {
                  uint len = numVestingEntries(account);
                  for (uint i = 0; i < len; i++) {
                      if (getVestingTime(account, i) != 0) {
                          return i;
                      }
                  }
                  return len;
              }
          
              /**
               * @notice Obtain the next schedule entry that will vest for a given user.
               * @return A pair of uints: (timestamp, synthetix quantity). */
              function getNextVestingEntry(address account)
                  public
                  view
                  returns (uint[2])
              {
                  uint index = getNextVestingIndex(account);
                  if (index == numVestingEntries(account)) {
                      return [uint(0), 0];
                  }
                  return getVestingScheduleEntry(account, index);
              }
          
              /**
               * @notice Obtain the time at which the next schedule entry will vest for a given user.
               */
              function getNextVestingTime(address account)
                  external
                  view
                  returns (uint)
              {
                  return getNextVestingEntry(account)[TIME_INDEX];
              }
          
              /**
               * @notice Obtain the quantity which the next schedule entry will vest for a given user.
               */
              function getNextVestingQuantity(address account)
                  external
                  view
                  returns (uint)
              {
                  return getNextVestingEntry(account)[QUANTITY_INDEX];
              }
          
          
              /* ========== MUTATIVE FUNCTIONS ========== */
          
              /**
               * @notice Withdraws a quantity of SNX back to the synthetix contract.
               * @dev This may only be called by the owner during the contract's setup period.
               */
              function withdrawSynthetix(uint quantity)
                  external
                  onlyOwner
                  onlyDuringSetup
              {
                  synthetix.transfer(synthetix, quantity);
              }
          
              /**
               * @notice Destroy the vesting information associated with an account.
               */
              function purgeAccount(address account)
                  external
                  onlyOwner
                  onlyDuringSetup
              {
                  delete vestingSchedules[account];
                  totalVestedBalance = totalVestedBalance.sub(totalVestedAccountBalance[account]);
                  delete totalVestedAccountBalance[account];
              }
          
              /**
               * @notice Add a new vesting entry at a given time and quantity to an account's schedule.
               * @dev A call to this should be accompanied by either enough balance already available
               * in this contract, or a corresponding call to synthetix.endow(), to ensure that when
               * the funds are withdrawn, there is enough balance, as well as correctly calculating
               * the fees.
               * This may only be called by the owner during the contract's setup period.
               * Note; although this function could technically be used to produce unbounded
               * arrays, it's only in the foundation's command to add to these lists.
               * @param account The account to append a new vesting entry to.
               * @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
               * @param quantity The quantity of SNX that will vest.
               */
              function appendVestingEntry(address account, uint time, uint quantity)
                  public
                  onlyOwner
                  onlyDuringSetup
              {
                  /* No empty or already-passed vesting entries allowed. */
                  require(now < time, "Time must be in the future");
                  require(quantity != 0, "Quantity cannot be zero");
          
                  /* There must be enough balance in the contract to provide for the vesting entry. */
                  totalVestedBalance = totalVestedBalance.add(quantity);
                  require(totalVestedBalance <= synthetix.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
          
                  /* Disallow arbitrarily long vesting schedules in light of the gas limit. */
                  uint scheduleLength = vestingSchedules[account].length;
                  require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
          
                  if (scheduleLength == 0) {
                      totalVestedAccountBalance[account] = quantity;
                  } else {
                      /* Disallow adding new vested SNX earlier than the last one.
                       * Since entries are only appended, this means that no vesting date can be repeated. */
                      require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
                      totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(quantity);
                  }
          
                  vestingSchedules[account].push([time, quantity]);
              }
          
              /**
               * @notice Construct a vesting schedule to release a quantities of SNX
               * over a series of intervals.
               * @dev Assumes that the quantities are nonzero
               * and that the sequence of timestamps is strictly increasing.
               * This may only be called by the owner during the contract's setup period.
               */
              function addVestingSchedule(address account, uint[] times, uint[] quantities)
                  external
                  onlyOwner
                  onlyDuringSetup
              {
                  for (uint i = 0; i < times.length; i++) {
                      appendVestingEntry(account, times[i], quantities[i]);
                  }
          
              }
          
              /**
               * @notice Allow a user to withdraw any SNX in their schedule that have vested.
               */
              function vest()
                  external
              {
                  uint numEntries = numVestingEntries(msg.sender);
                  uint total;
                  for (uint i = 0; i < numEntries; i++) {
                      uint time = getVestingTime(msg.sender, i);
                      /* The list is sorted; when we reach the first future time, bail out. */
                      if (time > now) {
                          break;
                      }
                      uint qty = getVestingQuantity(msg.sender, i);
                      if (qty == 0) {
                          continue;
                      }
          
                      vestingSchedules[msg.sender][i] = [0, 0];
                      total = total.add(qty);
                  }
          
                  if (total != 0) {
                      totalVestedBalance = totalVestedBalance.sub(total);
                      totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].sub(total);
                      synthetix.transfer(msg.sender, total);
                      emit Vested(msg.sender, now, total);
                  }
              }
          
          
              /* ========== EVENTS ========== */
          
              event SynthetixUpdated(address newSynthetix);
          
              event Vested(address indexed beneficiary, uint time, uint value);
          }
          
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       ExchangeRates.sol
          version:    1.0
          author:     Kevin Brown
          date:       2018-09-12
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          A contract that any other contract in the Synthetix system can query
          for the current market value of various assets, including
          crypto assets as well as various fiat assets.
          
          This contract assumes that rate updates will completely update
          all rates to their current values. If a rate shock happens
          on a single asset, the oracle will still push updated rates
          for all other assets.
          
          -----------------------------------------------------------------
          */
          
          
          /**
           * @title The repository for exchange rates
           */
          contract ExchangeRates is SelfDestructible {
          
              using SafeMath for uint;
          
              // Exchange rates stored by currency code, e.g. 'SNX', or 'sUSD'
              mapping(bytes4 => uint) public rates;
          
              // Update times stored by currency code, e.g. 'SNX', or 'sUSD'
              mapping(bytes4 => uint) public lastRateUpdateTimes;
          
              // The address of the oracle which pushes rate updates to this contract
              address public oracle;
          
              // Do not allow the oracle to submit times any further forward into the future than this constant.
              uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
          
              // How long will the contract assume the rate of any asset is correct
              uint public rateStalePeriod = 3 hours;
          
              // Each participating currency in the XDR basket is represented as a currency key with
              // equal weighting.
              // There are 5 participating currencies, so we'll declare that clearly.
              bytes4[5] public xdrParticipants;
          
              //
              // ========== CONSTRUCTOR ==========
          
              /**
               * @dev Constructor
               * @param _owner The owner of this contract.
               * @param _oracle The address which is able to update rate information.
               * @param _currencyKeys The initial currency keys to store (in order).
               * @param _newRates The initial currency amounts for each currency (in order).
               */
              constructor(
                  // SelfDestructible (Ownable)
                  address _owner,
          
                  // Oracle values - Allows for rate updates
                  address _oracle,
                  bytes4[] _currencyKeys,
                  uint[] _newRates
              )
                  /* Owned is initialised in SelfDestructible */
                  SelfDestructible(_owner)
                  public
              {
                  require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
          
                  oracle = _oracle;
          
                  // The sUSD rate is always 1 and is never stale.
                  rates["sUSD"] = SafeDecimalMath.unit();
                  lastRateUpdateTimes["sUSD"] = now;
          
                  // These are the currencies that make up the XDR basket.
                  // These are hard coded because:
                  //  - This way users can depend on the calculation and know it won't change for this deployment of the contract.
                  //  - Adding new currencies would likely introduce some kind of weighting factor, which
                  //    isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1.
                  //  - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract
                  //    then point the system at the new version.
                  xdrParticipants = [
                      bytes4("sUSD"),
                      bytes4("sAUD"),
                      bytes4("sCHF"),
                      bytes4("sEUR"),
                      bytes4("sGBP")
                  ];
          
                  internalUpdateRates(_currencyKeys, _newRates, now);
              }
          
              /* ========== SETTERS ========== */
          
              /**
               * @notice Set the rates stored in this contract
               * @param currencyKeys The currency keys you wish to update the rates for (in order)
               * @param newRates The rates for each currency (in order)
               * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract
               *                 This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even
               *                 if it takes a long time for the transaction to confirm.
               */
              function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
                  external
                  onlyOracle
                  returns(bool)
              {
                  return internalUpdateRates(currencyKeys, newRates, timeSent);
              }
          
              /**
               * @notice Internal function which sets the rates stored in this contract
               * @param currencyKeys The currency keys you wish to update the rates for (in order)
               * @param newRates The rates for each currency (in order)
               * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract
               *                 This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even
               *                 if it takes a long time for the transaction to confirm.
               */
              function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
                  internal
                  returns(bool)
              {
                  require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
                  require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
          
                  // Loop through each key and perform update.
                  for (uint i = 0; i < currencyKeys.length; i++) {
                      // Should not set any rate to zero ever, as no asset will ever be
                      // truely worthless and still valid. In this scenario, we should
                      // delete the rate and remove it from the system.
                      require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
                      require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
          
                      // We should only update the rate if it's at least the same age as the last rate we've got.
                      if (timeSent >= lastRateUpdateTimes[currencyKeys[i]]) {
                          // Ok, go ahead with the update.
                          rates[currencyKeys[i]] = newRates[i];
                          lastRateUpdateTimes[currencyKeys[i]] = timeSent;
                      }
                  }
          
                  emit RatesUpdated(currencyKeys, newRates);
          
                  // Now update our XDR rate.
                  updateXDRRate(timeSent);
          
                  return true;
              }
          
              /**
               * @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated.
               */
              function updateXDRRate(uint timeSent)
                  internal
              {
                  uint total = 0;
          
                  for (uint i = 0; i < xdrParticipants.length; i++) {
                      total = rates[xdrParticipants[i]].add(total);
                  }
          
                  // Set the rate
                  rates["XDR"] = total;
          
                  // Record that we updated the XDR rate.
                  lastRateUpdateTimes["XDR"] = timeSent;
          
                  // Emit our updated event separate to the others to save
                  // moving data around between arrays.
                  bytes4[] memory eventCurrencyCode = new bytes4[](1);
                  eventCurrencyCode[0] = "XDR";
          
                  uint[] memory eventRate = new uint[](1);
                  eventRate[0] = rates["XDR"];
          
                  emit RatesUpdated(eventCurrencyCode, eventRate);
              }
          
              /**
               * @notice Delete a rate stored in the contract
               * @param currencyKey The currency key you wish to delete the rate for
               */
              function deleteRate(bytes4 currencyKey)
                  external
                  onlyOracle
              {
                  require(rates[currencyKey] > 0, "Rate is zero");
          
                  delete rates[currencyKey];
                  delete lastRateUpdateTimes[currencyKey];
          
                  emit RateDeleted(currencyKey);
              }
          
              /**
               * @notice Set the Oracle that pushes the rate information to this contract
               * @param _oracle The new oracle address
               */
              function setOracle(address _oracle)
                  external
                  onlyOwner
              {
                  oracle = _oracle;
                  emit OracleUpdated(oracle);
              }
          
              /**
               * @notice Set the stale period on the updated rate variables
               * @param _time The new rateStalePeriod
               */
              function setRateStalePeriod(uint _time)
                  external
                  onlyOwner
              {
                  rateStalePeriod = _time;
                  emit RateStalePeriodUpdated(rateStalePeriod);
              }
          
              /* ========== VIEWS ========== */
          
              /**
               * @notice Retrieve the rate for a specific currency
               */
              function rateForCurrency(bytes4 currencyKey)
                  public
                  view
                  returns (uint)
              {
                  return rates[currencyKey];
              }
          
              /**
               * @notice Retrieve the rates for a list of currencies
               */
              function ratesForCurrencies(bytes4[] currencyKeys)
                  public
                  view
                  returns (uint[])
              {
                  uint[] memory _rates = new uint[](currencyKeys.length);
          
                  for (uint8 i = 0; i < currencyKeys.length; i++) {
                      _rates[i] = rates[currencyKeys[i]];
                  }
          
                  return _rates;
              }
          
              /**
               * @notice Retrieve a list of last update times for specific currencies
               */
              function lastRateUpdateTimeForCurrency(bytes4 currencyKey)
                  public
                  view
                  returns (uint)
              {
                  return lastRateUpdateTimes[currencyKey];
              }
          
              /**
               * @notice Retrieve the last update time for a specific currency
               */
              function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys)
                  public
                  view
                  returns (uint[])
              {
                  uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
          
                  for (uint8 i = 0; i < currencyKeys.length; i++) {
                      lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]];
                  }
          
                  return lastUpdateTimes;
              }
          
              /**
               * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period.
               */
              function rateIsStale(bytes4 currencyKey)
                  external
                  view
                  returns (bool)
              {
                  // sUSD is a special case and is never stale.
                  if (currencyKey == "sUSD") return false;
          
                  return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now;
              }
          
              /**
               * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period.
               */
              function anyRateIsStale(bytes4[] currencyKeys)
                  external
                  view
                  returns (bool)
              {
                  // Loop through each key and check whether the data point is stale.
                  uint256 i = 0;
          
                  while (i < currencyKeys.length) {
                      // sUSD is a special case and is never false
                      if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) {
                          return true;
                      }
                      i += 1;
                  }
          
                  return false;
              }
          
              /* ========== MODIFIERS ========== */
          
              modifier onlyOracle
              {
                  require(msg.sender == oracle, "Only the oracle can perform this action");
                  _;
              }
          
              /* ========== EVENTS ========== */
          
              event OracleUpdated(address newOracle);
              event RateStalePeriodUpdated(uint rateStalePeriod);
              event RatesUpdated(bytes4[] currencyKeys, uint[] newRates);
              event RateDeleted(bytes4 currencyKey);
          }
          
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       Synthetix.sol
          version:    2.0
          author:     Kevin Brown
                      Gavin Conway
          date:       2018-09-14
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          Synthetix token contract. SNX is a transferable ERC20 token,
          and also give its holders the following privileges.
          An owner of SNX has the right to issue synths in all synth flavours.
          
          After a fee period terminates, the duration and fees collected for that
          period are computed, and the next period begins. Thus an account may only
          withdraw the fees owed to them for the previous period, and may only do
          so once per period. Any unclaimed fees roll over into the common pot for
          the next period.
          
          == Average Balance Calculations ==
          
          The fee entitlement of a synthetix holder is proportional to their average
          issued synth balance over the last fee period. This is computed by
          measuring the area under the graph of a user's issued synth balance over
          time, and then when a new fee period begins, dividing through by the
          duration of the fee period.
          
          We need only update values when the balances of an account is modified.
          This occurs when issuing or burning for issued synth balances,
          and when transferring for synthetix balances. This is for efficiency,
          and adds an implicit friction to interacting with SNX.
          A synthetix holder pays for his own recomputation whenever he wants to change
          his position, which saves the foundation having to maintain a pot dedicated
          to resourcing this.
          
          A hypothetical user's balance history over one fee period, pictorially:
          
                s ____
                 |    |
                 |    |___ p
                 |____|___|___ __ _  _
                 f    t   n
          
          Here, the balance was s between times f and t, at which time a transfer
          occurred, updating the balance to p, until n, when the present transfer occurs.
          When a new transfer occurs at time n, the balance being p,
          we must:
          
            - Add the area p * (n - t) to the total area recorded so far
            - Update the last transfer time to n
          
          So if this graph represents the entire current fee period,
          the average SNX held so far is ((t-f)*s + (n-t)*p) / (n-f).
          The complementary computations must be performed for both sender and
          recipient.
          
          Note that a transfer keeps global supply of SNX invariant.
          The sum of all balances is constant, and unmodified by any transfer.
          So the sum of all balances multiplied by the duration of a fee period is also
          constant, and this is equivalent to the sum of the area of every user's
          time/balance graph. Dividing through by that duration yields back the total
          synthetix supply. So, at the end of a fee period, we really do yield a user's
          average share in the synthetix supply over that period.
          
          A slight wrinkle is introduced if we consider the time r when the fee period
          rolls over. Then the previous fee period k-1 is before r, and the current fee
          period k is afterwards. If the last transfer took place before r,
          but the latest transfer occurred afterwards:
          
          k-1       |        k
                s __|_
                 |  | |
                 |  | |____ p
                 |__|_|____|___ __ _  _
                    |
                 f  | t    n
                    r
          
          In this situation the area (r-f)*s contributes to fee period k-1, while
          the area (t-r)*s contributes to fee period k. We will implicitly consider a
          zero-value transfer to have occurred at time r. Their fee entitlement for the
          previous period will be finalised at the time of their first transfer during the
          current fee period, or when they query or withdraw their fee entitlement.
          
          In the implementation, the duration of different fee periods may be slightly irregular,
          as the check that they have rolled over occurs only when state-changing synthetix
          operations are performed.
          
          == Issuance and Burning ==
          
          In this version of the synthetix contract, synths can only be issued by
          those that have been nominated by the synthetix foundation. Synths are assumed
          to be valued at $1, as they are a stable unit of account.
          
          All synths issued require a proportional value of SNX to be locked,
          where the proportion is governed by the current issuance ratio. This
          means for every $1 of SNX locked up, $(issuanceRatio) synths can be issued.
          i.e. to issue 100 synths, 100/issuanceRatio dollars of SNX need to be locked up.
          
          To determine the value of some amount of SNX(S), an oracle is used to push
          the price of SNX (P_S) in dollars to the contract. The value of S
          would then be: S * P_S.
          
          Any SNX that are locked up by this issuance process cannot be transferred.
          The amount that is locked floats based on the price of SNX. If the price
          of SNX moves up, less SNX are locked, so they can be issued against,
          or transferred freely. If the price of SNX moves down, more SNX are locked,
          even going above the initial wallet balance.
          
          -----------------------------------------------------------------
          */
          
          
          /**
           * @title Synthetix ERC20 contract.
           * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances,
           * but it also computes the quantity of fees each synthetix holder is entitled to.
           */
          contract Synthetix is ExternStateToken {
          
              // ========== STATE VARIABLES ==========
          
              // Available Synths which can be used with the system
              Synth[] public availableSynths;
              mapping(bytes4 => Synth) public synths;
          
              FeePool public feePool;
              SynthetixEscrow public escrow;
              ExchangeRates public exchangeRates;
              SynthetixState public synthetixState;
          
              uint constant SYNTHETIX_SUPPLY = 1e8 * SafeDecimalMath.unit();
              string constant TOKEN_NAME = "Synthetix";
              string constant TOKEN_SYMBOL = "SNX";
              uint8 constant DECIMALS = 18;
          
              // ========== CONSTRUCTOR ==========
          
              /**
               * @dev Constructor
               * @param _tokenState A pre-populated contract containing token balances.
               * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
               * @param _owner The owner of this contract.
               */
              constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState,
                  address _owner, ExchangeRates _exchangeRates, FeePool _feePool
              )
                  ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, SYNTHETIX_SUPPLY, DECIMALS, _owner)
                  public
              {
                  synthetixState = _synthetixState;
                  exchangeRates = _exchangeRates;
                  feePool = _feePool;
              }
          
              // ========== SETTERS ========== */
          
              /**
               * @notice Add an associated Synth contract to the Synthetix system
               * @dev Only the contract owner may call this.
               */
              function addSynth(Synth synth)
                  external
                  optionalProxy_onlyOwner
              {
                  bytes4 currencyKey = synth.currencyKey();
          
                  require(synths[currencyKey] == Synth(0), "Synth already exists");
          
                  availableSynths.push(synth);
                  synths[currencyKey] = synth;
          
                  emitSynthAdded(currencyKey, synth);
              }
          
              /**
               * @notice Remove an associated Synth contract from the Synthetix system
               * @dev Only the contract owner may call this.
               */
              function removeSynth(bytes4 currencyKey)
                  external
                  optionalProxy_onlyOwner
              {
                  require(synths[currencyKey] != address(0), "Synth does not exist");
                  require(synths[currencyKey].totalSupply() == 0, "Synth supply exists");
                  require(currencyKey != "XDR", "Cannot remove XDR synth");
          
                  // Save the address we're removing for emitting the event at the end.
                  address synthToRemove = synths[currencyKey];
          
                  // Remove the synth from the availableSynths array.
                  for (uint8 i = 0; i < availableSynths.length; i++) {
                      if (availableSynths[i] == synthToRemove) {
                          delete availableSynths[i];
          
                          // Copy the last synth into the place of the one we just deleted
                          // If there's only one synth, this is synths[0] = synths[0].
                          // If we're deleting the last one, it's also a NOOP in the same way.
                          availableSynths[i] = availableSynths[availableSynths.length - 1];
          
                          // Decrease the size of the array by one.
                          availableSynths.length--;
          
                          break;
                      }
                  }
          
                  // And remove it from the synths mapping
                  delete synths[currencyKey];
          
                  emitSynthRemoved(currencyKey, synthToRemove);
              }
          
              /**
               * @notice Set the associated synthetix escrow contract.
               * @dev Only the contract owner may call this.
               */
              function setEscrow(SynthetixEscrow _escrow)
                  external
                  optionalProxy_onlyOwner
              {
                  escrow = _escrow;
                  // Note: No event here as our contract exceeds max contract size
                  // with these events, and it's unlikely people will need to
                  // track these events specifically.
              }
          
              /**
               * @notice Set the ExchangeRates contract address where rates are held.
               * @dev Only callable by the contract owner.
               */
              function setExchangeRates(ExchangeRates _exchangeRates)
                  external
                  optionalProxy_onlyOwner
              {
                  exchangeRates = _exchangeRates;
                  // Note: No event here as our contract exceeds max contract size
                  // with these events, and it's unlikely people will need to
                  // track these events specifically.
              }
          
              /**
               * @notice Set the synthetixState contract address where issuance data is held.
               * @dev Only callable by the contract owner.
               */
              function setSynthetixState(SynthetixState _synthetixState)
                  external
                  optionalProxy_onlyOwner
              {
                  synthetixState = _synthetixState;
          
                  emitStateContractChanged(_synthetixState);
              }
          
              /**
               * @notice Set your preferred currency. Note: This does not automatically exchange any balances you've held previously in
               * other synth currencies in this address, it will apply for any new payments you receive at this address.
               */
              function setPreferredCurrency(bytes4 currencyKey)
                  external
                  optionalProxy
              {
                  require(currencyKey == 0 || !exchangeRates.rateIsStale(currencyKey), "Currency rate is stale or doesn't exist.");
          
                  synthetixState.setPreferredCurrency(messageSender, currencyKey);
          
                  emitPreferredCurrencyChanged(messageSender, currencyKey);
              }
          
              // ========== VIEWS ==========
          
              /**
               * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency
               * @param sourceCurrencyKey The currency the amount is specified in
               * @param sourceAmount The source amount, specified in UNIT base
               * @param destinationCurrencyKey The destination currency
               */
              function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
                  public
                  view
                  rateNotStale(sourceCurrencyKey)
                  rateNotStale(destinationCurrencyKey)
                  returns (uint)
              {
                  // If there's no change in the currency, then just return the amount they gave us
                  if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
          
                  // Calculate the effective value by going from source -> USD -> destination
                  return sourceAmount.multiplyDecimalRound(exchangeRates.rateForCurrency(sourceCurrencyKey))
                      .divideDecimalRound(exchangeRates.rateForCurrency(destinationCurrencyKey));
              }
          
              /**
               * @notice Total amount of synths issued by the system, priced in currencyKey
               * @param currencyKey The currency to value the synths in
               */
              function totalIssuedSynths(bytes4 currencyKey)
                  public
                  view
                  rateNotStale(currencyKey)
                  returns (uint)
              {
                  uint total = 0;
                  uint currencyRate = exchangeRates.rateForCurrency(currencyKey);
          
                  for (uint8 i = 0; i < availableSynths.length; i++) {
                      // Ensure the rate isn't stale.
                      // TODO: Investigate gas cost optimisation of doing a single call with all keys in it vs
                      // individual calls like this.
                      require(!exchangeRates.rateIsStale(availableSynths[i].currencyKey()), "Rate is stale");
          
                      // What's the total issued value of that synth in the destination currency?
                      // Note: We're not using our effectiveValue function because we don't want to go get the
                      //       rate for the destination currency and check if it's stale repeatedly on every
                      //       iteration of the loop
                      uint synthValue = availableSynths[i].totalSupply()
                          .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey()))
                          .divideDecimalRound(currencyRate);
                      total = total.add(synthValue);
                  }
          
                  return total;
              }
          
              /**
               * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths
               */
              function availableSynthCount()
                  public
                  view
                  returns (uint)
              {
                  return availableSynths.length;
              }
          
              // ========== MUTATIVE FUNCTIONS ==========
          
              /**
               * @notice ERC20 transfer function.
               */
              function transfer(address to, uint value)
                  public
                  returns (bool)
              {
                  bytes memory empty;
                  return transfer(to, value, empty);
              }
          
              /**
               * @notice ERC223 transfer function. Does not conform with the ERC223 spec, as:
               *         - Transaction doesn't revert if the recipient doesn't implement tokenFallback()
               *         - Emits a standard ERC20 event without the bytes data parameter so as not to confuse
               *           tooling such as Etherscan.
               */
              function transfer(address to, uint value, bytes data)
                  public
                  optionalProxy
                  returns (bool)
              {
                  // Ensure they're not trying to exceed their locked amount
                  require(value <= transferableSynthetix(messageSender), "Insufficient balance");
          
                  // Perform the transfer: if there is a problem an exception will be thrown in this call.
                  _transfer_byProxy(messageSender, to, value, data);
          
                  return true;
              }
          
              /**
               * @notice ERC20 transferFrom function.
               */
              function transferFrom(address from, address to, uint value)
                  public
                  returns (bool)
              {
                  bytes memory empty;
                  return transferFrom(from, to, value, empty);
              }
          
              /**
               * @notice ERC223 transferFrom function. Does not conform with the ERC223 spec, as:
               *         - Transaction doesn't revert if the recipient doesn't implement tokenFallback()
               *         - Emits a standard ERC20 event without the bytes data parameter so as not to confuse
               *           tooling such as Etherscan.
               */
              function transferFrom(address from, address to, uint value, bytes data)
                  public
                  optionalProxy
                  returns (bool)
              {
                  // Ensure they're not trying to exceed their locked amount
                  require(value <= transferableSynthetix(from), "Insufficient balance");
          
                  // Perform the transfer: if there is a problem,
                  // an exception will be thrown in this call.
                  _transferFrom_byProxy(messageSender, from, to, value, data);
          
                  return true;
              }
          
              /**
               * @notice Function that allows you to exchange synths you hold in one flavour for another.
               * @param sourceCurrencyKey The source currency you wish to exchange from
               * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange
               * @param destinationCurrencyKey The destination currency you wish to obtain.
               * @param destinationAddress Where the result should go. If this is address(0) then it sends back to the message sender.
               * @return Boolean that indicates whether the transfer succeeded or failed.
               */
              function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)
                  external
                  optionalProxy
                  // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us.
                  returns (bool)
              {
                  require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths");
                  require(sourceAmount > 0, "Zero amount");
          
                  // Pass it along, defaulting to the sender as the recipient.
                  return _internalExchange(
                      messageSender,
                      sourceCurrencyKey,
                      sourceAmount,
                      destinationCurrencyKey,
                      destinationAddress == address(0) ? messageSender : destinationAddress,
                      true // Charge fee on the exchange
                  );
              }
          
              /**
               * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency
               * @dev Only the synth contract can call this function
               * @param from The address to exchange / burn synth from
               * @param sourceCurrencyKey The source currency you wish to exchange from
               * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange
               * @param destinationCurrencyKey The destination currency you wish to obtain.
               * @param destinationAddress Where the result should go.
               * @return Boolean that indicates whether the transfer succeeded or failed.
               */
              function synthInitiatedExchange(
                  address from,
                  bytes4 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes4 destinationCurrencyKey,
                  address destinationAddress
              )
                  external
                  onlySynth
                  returns (bool)
              {
                  require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
                  require(sourceAmount > 0, "Zero amount");
          
                  // Pass it along
                  return _internalExchange(
                      from,
                      sourceCurrencyKey,
                      sourceAmount,
                      destinationCurrencyKey,
                      destinationAddress,
                      false // Don't charge fee on the exchange, as they've already been charged a transfer fee in the synth contract
                  );
              }
          
              /**
               * @notice Function that allows synth contract to delegate sending fee to the fee Pool.
               * @dev Only the synth contract can call this function.
               * @param from The address fee is coming from.
               * @param sourceCurrencyKey source currency fee from.
               * @param sourceAmount The amount, specified in UNIT of source currency.
               * @return Boolean that indicates whether the transfer succeeded or failed.
               */
              function synthInitiatedFeePayment(
                  address from,
                  bytes4 sourceCurrencyKey,
                  uint sourceAmount
              )
                  external
                  onlySynth
                  returns (bool)
              {
                  require(sourceAmount > 0, "Source can't be 0");
          
                  // Pass it along, defaulting to the sender as the recipient.
                  bool result = _internalExchange(
                      from,
                      sourceCurrencyKey,
                      sourceAmount,
                      "XDR",
                      feePool.FEE_ADDRESS(),
                      false // Don't charge a fee on the exchange because this is already a fee
                  );
          
                  // Tell the fee pool about this.
                  feePool.feePaid(sourceCurrencyKey, sourceAmount);
          
                  return result;
              }
          
              /**
               * @notice Function that allows synth contract to delegate sending fee to the fee Pool.
               * @dev fee pool contract address is not allowed to call function
               * @param from The address to move synth from
               * @param sourceCurrencyKey source currency from.
               * @param sourceAmount The amount, specified in UNIT of source currency.
               * @param destinationCurrencyKey The destination currency to obtain.
               * @param destinationAddress Where the result should go.
               * @param chargeFee Boolean to charge a fee for transaction.
               * @return Boolean that indicates whether the transfer succeeded or failed.
               */
              function _internalExchange(
                  address from,
                  bytes4 sourceCurrencyKey,
                  uint sourceAmount,
                  bytes4 destinationCurrencyKey,
                  address destinationAddress,
                  bool chargeFee
              )
                  internal
                  notFeeAddress(from)
                  returns (bool)
              {
                  require(destinationAddress != address(0), "Zero destination");
                  require(destinationAddress != address(this), "Synthetix is invalid destination");
                  require(destinationAddress != address(proxy), "Proxy is invalid destination");
          
                  // 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
                  synths[sourceCurrencyKey].burn(from, sourceAmount);
          
                  // How much should they get in the destination currency?
                  uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
          
                  // What's the fee on that currency that we should deduct?
                  uint amountReceived = destinationAmount;
                  uint fee = 0;
          
                  if (chargeFee) {
                      amountReceived = feePool.amountReceivedFromExchange(destinationAmount);
                      fee = destinationAmount.sub(amountReceived);
                  }
          
                  // Issue their new synths
                  synths[destinationCurrencyKey].issue(destinationAddress, amountReceived);
          
                  // Remit the fee in XDRs
                  if (fee > 0) {
                      uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR");
                      synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount);
                  }
          
                  // Nothing changes as far as issuance data goes because the total value in the system hasn't changed.
          
                  // Call the ERC223 transfer callback if needed
                  synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived);
          
                  // Gas optimisation:
                  // No event emitted as it's assumed users will be able to track transfers to the zero address, followed
                  // by a transfer on another synth from the zero address and ascertain the info required here.
          
                  return true;
              }
          
              /**
               * @notice Function that registers new synth as they are isseud. Calculate delta to append to synthetixState.
               * @dev Only internal calls from synthetix address.
               * @param currencyKey The currency to register synths in, for example sUSD or sAUD
               * @param amount The amount of synths to register with a base of UNIT
               */
              function _addToDebtRegister(bytes4 currencyKey, uint amount)
                  internal
                  optionalProxy
              {
                  // What is the value of the requested debt in XDRs?
                  uint xdrValue = effectiveValue(currencyKey, amount, "XDR");
          
                  // What is the value of all issued synths of the system (priced in XDRs)?
                  uint totalDebtIssued = totalIssuedSynths("XDR");
          
                  // What will the new total be including the new value?
                  uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
          
                  // What is their percentage (as a high precision int) of the total debt?
                  uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
          
                  // And what effect does this percentage have on the global debt holding of other issuers?
                  // The delta specifically needs to not take into account any existing debt as it's already
                  // accounted for in the delta from when they issued previously.
                  // The delta is a high precision integer.
                  uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
          
                  // How much existing debt do they have?
                  uint existingDebt = debtBalanceOf(messageSender, "XDR");
          
                  // And what does their debt ownership look like including this previous stake?
                  if (existingDebt > 0) {
                      debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
                  }
          
                  // Are they a new issuer? If so, record them.
                  if (!synthetixState.hasIssued(messageSender)) {
                      synthetixState.incrementTotalIssuerCount();
                  }
          
                  // Save the debt entry parameters
                  synthetixState.setCurrentIssuanceData(messageSender, debtPercentage);
          
                  // And if we're the first, push 1 as there was no effect to any other holders, otherwise push
                  // the change for the rest of the debt holders. The debt ledger holds high precision integers.
                  if (synthetixState.debtLedgerLength() > 0) {
                      synthetixState.appendDebtLedgerValue(
                          synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
                      );
                  } else {
                      synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
                  }
              }
          
              /**
               * @notice Issue synths against the sender's SNX.
               * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0.
               * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD
               * @param amount The amount of synths you wish to issue with a base of UNIT
               */
              function issueSynths(bytes4 currencyKey, uint amount)
                  public
                  optionalProxy
                  nonZeroAmount(amount)
                  // No need to check if price is stale, as it is checked in issuableSynths.
              {
                  require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large");
          
                  // Keep track of the debt they're about to create
                  _addToDebtRegister(currencyKey, amount);
          
                  // Create their synths
                  synths[currencyKey].issue(messageSender, amount);
              }
          
              /**
               * @notice Issue the maximum amount of Synths possible against the sender's SNX.
               * @dev Issuance is only allowed if the synthetix price isn't stale.
               * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD
               */
              function issueMaxSynths(bytes4 currencyKey)
                  external
                  optionalProxy
              {
                  // Figure out the maximum we can issue in that currency
                  uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);
          
                  // And issue them
                  issueSynths(currencyKey, maxIssuable);
              }
          
              /**
               * @notice Burn synths to clear issued synths/free SNX.
               * @param currencyKey The currency you're specifying to burn
               * @param amount The amount (in UNIT base) you wish to burn
               */
              function burnSynths(bytes4 currencyKey, uint amount)
                  external
                  optionalProxy
                  // No need to check for stale rates as _removeFromDebtRegister calls effectiveValue
                  // which does this for us
              {
                  // How much debt do they have?
                  uint debt = debtBalanceOf(messageSender, currencyKey);
          
                  require(debt > 0, "No debt to forgive");
          
                  // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just
                  // clear their debt and leave them be.
                  uint amountToBurn = debt < amount ? debt : amount;
          
                  // Remove their debt from the ledger
                  _removeFromDebtRegister(currencyKey, amountToBurn);
          
                  // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths).
                  synths[currencyKey].burn(messageSender, amountToBurn);
              }
          
              /**
               * @notice Remove a debt position from the register
               * @param currencyKey The currency the user is presenting to forgive their debt
               * @param amount The amount (in UNIT base) being presented
               */
              function _removeFromDebtRegister(bytes4 currencyKey, uint amount)
                  internal
              {
                  // How much debt are they trying to remove in XDRs?
                  uint debtToRemove = effectiveValue(currencyKey, amount, "XDR");
          
                  // How much debt do they have?
                  uint existingDebt = debtBalanceOf(messageSender, "XDR");
          
                  // What percentage of the total debt are they trying to remove?
                  uint totalDebtIssued = totalIssuedSynths("XDR");
                  uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(totalDebtIssued);
          
                  // And what effect does this percentage have on the global debt holding of other issuers?
                  // The delta specifically needs to not take into account any existing debt as it's already
                  // accounted for in the delta from when they issued previously.
                  uint delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
          
                  // Are they exiting the system, or are they just decreasing their debt position?
                  if (debtToRemove == existingDebt) {
                      synthetixState.clearIssuanceData(messageSender);
                      synthetixState.decrementTotalIssuerCount();
                  } else {
                      // What percentage of the debt will they be left with?
                      uint newDebt = existingDebt.sub(debtToRemove);
                      uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
                      uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
          
                      // Store the debt percentage and debt ledger as high precision integers
                      synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage);
                  }
          
                  // Update our cumulative ledger. This is also a high precision integer.
                  synthetixState.appendDebtLedgerValue(
                      synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
                  );
              }
          
              // ========== Issuance/Burning ==========
          
              /**
               * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs.
               * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue.
               */
              function maxIssuableSynths(address issuer, bytes4 currencyKey)
                  public
                  view
                  // We don't need to check stale rates here as effectiveValue will do it for us.
                  returns (uint)
              {
                  // What is the value of their SNX balance in the destination currency?
                  uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey);
          
                  // They're allowed to issue up to issuanceRatio of that value
                  return destinationValue.multiplyDecimal(synthetixState.issuanceRatio());
              }
          
              /**
               * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time
               * as the value of the underlying Synthetix asset changes, e.g. if a user issues their maximum available
               * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value
               * of Synthetix changes, the ratio returned by this function will adjust accordlingly. Users are
               * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by
               * altering the amount of fees they're able to claim from the system.
               */
              function collateralisationRatio(address issuer)
                  public
                  view
                  returns (uint)
              {
                  uint totalOwnedSynthetix = collateral(issuer);
                  if (totalOwnedSynthetix == 0) return 0;
          
                  uint debtBalance = debtBalanceOf(issuer, "SNX");
                  return debtBalance.divideDecimalRound(totalOwnedSynthetix);
              }
          
          /**
               * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function
               * will tell you how many synths a user has to give back to the system in order to unlock their original
               * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price
               * the debt in sUSD, XDR, or any other synth you wish.
               */
              function debtBalanceOf(address issuer, bytes4 currencyKey)
                  public
                  view
                  // Don't need to check for stale rates here because totalIssuedSynths will do it for us
                  returns (uint)
              {
                  // What was their initial debt ownership?
                  uint initialDebtOwnership;
                  uint debtEntryIndex;
                  (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer);
          
                  // If it's zero, they haven't issued, and they have no debt.
                  if (initialDebtOwnership == 0) return 0;
          
                  // Figure out the global debt percentage delta from when they entered the system.
                  // This is a high precision integer.
                  uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry()
                      .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex))
                      .multiplyDecimalRoundPrecise(initialDebtOwnership);
          
                  // What's the total value of the system in their requested currency?
                  uint totalSystemValue = totalIssuedSynths(currencyKey);
          
                  // Their debt balance is their portion of the total system value.
                  uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal()
                      .multiplyDecimalRoundPrecise(currentDebtOwnership);
          
                  return highPrecisionBalance.preciseDecimalToDecimal();
              }
          
              /**
               * @notice The remaining synths an issuer can issue against their total synthetix balance.
               * @param issuer The account that intends to issue
               * @param currencyKey The currency to price issuable value in
               */
              function remainingIssuableSynths(address issuer, bytes4 currencyKey)
                  public
                  view
                  // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us.
                  returns (uint)
              {
                  uint alreadyIssued = debtBalanceOf(issuer, currencyKey);
                  uint max = maxIssuableSynths(issuer, currencyKey);
          
                  if (alreadyIssued >= max) {
                      return 0;
                  } else {
                      return max.sub(alreadyIssued);
                  }
              }
          
              /**
               * @notice The total SNX owned by this account, both escrowed and unescrowed,
               * against which synths can be issued.
               * This includes those already being used as collateral (locked), and those
               * available for further issuance (unlocked).
               */
              function collateral(address account)
                  public
                  view
                  returns (uint)
              {
                  uint balance = tokenState.balanceOf(account);
          
                  if (escrow != address(0)) {
                      balance = balance.add(escrow.balanceOf(account));
                  }
          
                  return balance;
              }
          
              /**
               * @notice The number of SNX that are free to be transferred by an account.
               * @dev When issuing, escrowed SNX are locked first, then non-escrowed
               * SNX are locked last, but escrowed SNX are not transferable, so they are not included
               * in this calculation.
               */
              function transferableSynthetix(address account)
                  public
                  view
                  rateNotStale("SNX")
                  returns (uint)
              {
                  // How many SNX do they have, excluding escrow?
                  // Note: We're excluding escrow here because we're interested in their transferable amount
                  // and escrowed SNX are not transferable.
                  uint balance = tokenState.balanceOf(account);
          
                  // How many of those will be locked by the amount they've issued?
                  // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require
                  // 100 SNX to be locked in their wallet to maintain their collateralisation ratio
                  // The locked synthetix value can exceed their balance.
                  uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio());
          
                  // If we exceed the balance, no SNX are transferable, otherwise the difference is.
                  if (lockedSynthetixValue >= balance) {
                      return 0;
                  } else {
                      return balance.sub(lockedSynthetixValue);
                  }
              }
          
              // ========== MODIFIERS ==========
          
              modifier rateNotStale(bytes4 currencyKey) {
                  require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency");
                  _;
              }
          
              modifier notFeeAddress(address account) {
                  require(account != feePool.FEE_ADDRESS(), "Fee address not allowed");
                  _;
              }
          
              modifier onlySynth() {
                  bool isSynth = false;
          
                  // No need to repeatedly call this function either
                  for (uint8 i = 0; i < availableSynths.length; i++) {
                      if (availableSynths[i] == msg.sender) {
                          isSynth = true;
                          break;
                      }
                  }
          
                  require(isSynth, "Only synth allowed");
                  _;
              }
          
              modifier nonZeroAmount(uint _amount) {
                  require(_amount > 0, "Amount needs to be larger than 0");
                  _;
              }
          
              // ========== EVENTS ==========
          
              event PreferredCurrencyChanged(address indexed account, bytes4 newPreferredCurrency);
              bytes32 constant PREFERREDCURRENCYCHANGED_SIG = keccak256("PreferredCurrencyChanged(address,bytes4)");
              function emitPreferredCurrencyChanged(address account, bytes4 newPreferredCurrency) internal {
                  proxy._emit(abi.encode(newPreferredCurrency), 2, PREFERREDCURRENCYCHANGED_SIG, bytes32(account), 0, 0);
              }
          
              event StateContractChanged(address stateContract);
              bytes32 constant STATECONTRACTCHANGED_SIG = keccak256("StateContractChanged(address)");
              function emitStateContractChanged(address stateContract) internal {
                  proxy._emit(abi.encode(stateContract), 1, STATECONTRACTCHANGED_SIG, 0, 0, 0);
              }
          
              event SynthAdded(bytes4 currencyKey, address newSynth);
              bytes32 constant SYNTHADDED_SIG = keccak256("SynthAdded(bytes4,address)");
              function emitSynthAdded(bytes4 currencyKey, address newSynth) internal {
                  proxy._emit(abi.encode(currencyKey, newSynth), 1, SYNTHADDED_SIG, 0, 0, 0);
              }
          
              event SynthRemoved(bytes4 currencyKey, address removedSynth);
              bytes32 constant SYNTHREMOVED_SIG = keccak256("SynthRemoved(bytes4,address)");
              function emitSynthRemoved(bytes4 currencyKey, address removedSynth) internal {
                  proxy._emit(abi.encode(currencyKey, removedSynth), 1, SYNTHREMOVED_SIG, 0, 0, 0);
              }
          }
          
          
          /*
          -----------------------------------------------------------------
          FILE INFORMATION
          -----------------------------------------------------------------
          
          file:       SynthetixState.sol
          version:    1.0
          author:     Kevin Brown
          date:       2018-10-19
          
          -----------------------------------------------------------------
          MODULE DESCRIPTION
          -----------------------------------------------------------------
          
          A contract that holds issuance state and preferred currency of
          users in the Synthetix system.
          
          This contract is used side by side with the Synthetix contract
          to make it easier to upgrade the contract logic while maintaining
          issuance state.
          
          The Synthetix contract is also quite large and on the edge of
          being beyond the contract size limit without moving this information
          out to another contract.
          
          The first deployed contract would create this state contract,
          using it as its store of issuance data.
          
          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 Synthetix State
           * @notice Stores issuance information and preferred currency information of the Synthetix contract.
           */
          contract SynthetixState is State, LimitedSetup {
              using SafeMath for uint;
              using SafeDecimalMath for uint;
          
              // 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;
              }
          
              // Issued synth balances for individual fee entitlements and exit price calculations
              mapping(address => IssuanceData) public issuanceData;
          
              // The total count of people that have outstanding issued synths in any flavour
              uint public totalIssuerCount;
          
              // Global debt pool tracking
              uint[] public debtLedger;
          
              // Import state
              uint public importedXDRAmount;
          
              // A quantity of synths greater than this ratio
              // may not be issued against a given value of SNX.
              uint public issuanceRatio = SafeDecimalMath.unit() / 5;
              // No more synths may be issued than the value of SNX backing them.
              uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit();
          
              // Users can specify their preferred currency, in which case all synths they receive
              // will automatically exchange to that preferred currency upon receipt in their wallet
              mapping(address => bytes4) public preferredCurrency;
          
              /**
               * @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)
                  LimitedSetup(1 weeks)
                  public
              {}
          
              /* ========== SETTERS ========== */
          
              /**
               * @notice Set issuance data for an address
               * @dev Only the associated contract may call this.
               * @param account The address to set the data for.
               * @param initialDebtOwnership The initial debt ownership for this address.
               */
              function setCurrentIssuanceData(address account, uint initialDebtOwnership)
                  external
                  onlyAssociatedContract
              {
                  issuanceData[account].initialDebtOwnership = initialDebtOwnership;
                  issuanceData[account].debtEntryIndex = debtLedger.length;
              }
          
              /**
               * @notice Clear issuance data for an address
               * @dev Only the associated contract may call this.
               * @param account The address to clear the data for.
               */
              function clearIssuanceData(address account)
                  external
                  onlyAssociatedContract
              {
                  delete issuanceData[account];
              }
          
              /**
               * @notice Increment the total issuer count
               * @dev Only the associated contract may call this.
               */
              function incrementTotalIssuerCount()
                  external
                  onlyAssociatedContract
              {
                  totalIssuerCount = totalIssuerCount.add(1);
              }
          
              /**
               * @notice Decrement the total issuer count
               * @dev Only the associated contract may call this.
               */
              function decrementTotalIssuerCount()
                  external
                  onlyAssociatedContract
              {
                  totalIssuerCount = totalIssuerCount.sub(1);
              }
          
              /**
               * @notice Append a value to the debt ledger
               * @dev Only the associated contract may call this.
               * @param value The new value to be added to the debt ledger.
               */
              function appendDebtLedgerValue(uint value)
                  external
                  onlyAssociatedContract
              {
                  debtLedger.push(value);
              }
          
              /**
               * @notice Set preferred currency for a user
               * @dev Only the associated contract may call this.
               * @param account The account to set the preferred currency for
               * @param currencyKey The new preferred currency
               */
              function setPreferredCurrency(address account, bytes4 currencyKey)
                  external
                  onlyAssociatedContract
              {
                  preferredCurrency[account] = currencyKey;
              }
          
              /**
               * @notice Set the issuanceRatio for issuance calculations.
               * @dev Only callable by the contract owner.
               */
              function setIssuanceRatio(uint _issuanceRatio)
                  external
                  onlyOwner
              {
                  require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
                  issuanceRatio = _issuanceRatio;
                  emit IssuanceRatioUpdated(_issuanceRatio);
              }
          
              /**
               * @notice Import issuer data from the old Synthetix contract before multicurrency
               * @dev Only callable by the contract owner, and only for 1 week after deployment.
               */
              function importIssuerData(address[] accounts, uint[] sUSDAmounts)
                  external
                  onlyOwner
                  onlyDuringSetup
              {
                  require(accounts.length == sUSDAmounts.length, "Length mismatch");
          
                  for (uint8 i = 0; i < accounts.length; i++) {
                      _addToDebtRegister(accounts[i], sUSDAmounts[i]);
                  }
              }
          
              /**
               * @notice Import issuer data from the old Synthetix contract before multicurrency
               * @dev Only used from importIssuerData above, meant to be disposable
               */
              function _addToDebtRegister(address account, uint amount)
                  internal
              {
                  // This code is duplicated from Synthetix so that we can call it directly here
                  // during setup only.
                  Synthetix synthetix = Synthetix(associatedContract);
          
                  // What is the value of the requested debt in XDRs?
                  uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR");
          
                  // What is the value that we've previously imported?
                  uint totalDebtIssued = importedXDRAmount;
          
                  // What will the new total be including the new value?
                  uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
          
                  // Save that for the next import.
                  importedXDRAmount = newTotalDebtIssued;
          
                  // What is their percentage (as a high precision int) of the total debt?
                  uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
          
                  // And what effect does this percentage have on the global debt holding of other issuers?
                  // The delta specifically needs to not take into account any existing debt as it's already
                  // accounted for in the delta from when they issued previously.
                  // The delta is a high precision integer.
                  uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
          
                  uint existingDebt = synthetix.debtBalanceOf(account, "XDR");
          
                  // And what does their debt ownership look like including this previous stake?
                  if (existingDebt > 0) {
                      debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
                  }
          
                  // Are they a new issuer? If so, record them.
                  if (issuanceData[account].initialDebtOwnership == 0) {
                      totalIssuerCount = totalIssuerCount.add(1);
                  }
          
                  // Save the debt entry parameters
                  issuanceData[account].initialDebtOwnership = debtPercentage;
                  issuanceData[account].debtEntryIndex = debtLedger.length;
          
                  // And if we're the first, push 1 as there was no effect to any other holders, otherwise push
                  // the change for the rest of the debt holders. The debt ledger holds high precision integers.
                  if (debtLedger.length > 0) {
                      debtLedger.push(
                          debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)
                      );
                  } else {
                      debtLedger.push(SafeDecimalMath.preciseUnit());
                  }
              }
          
              /* ========== VIEWS ========== */
          
              /**
               * @notice Retrieve the length of the debt ledger array
               */
              function debtLedgerLength()
                  external
                  view
                  returns (uint)
              {
                  return debtLedger.length;
              }
          
              /**
               * @notice Retrieve the most recent entry from the debt ledger
               */
              function lastDebtLedgerEntry()
                  external
                  view
                  returns (uint)
              {
                  return debtLedger[debtLedger.length - 1];
              }
          
              /**
               * @notice Query whether an account has issued and has an outstanding debt balance
               * @param account The address to query for
               */
              function hasIssued(address account)
                  external
                  view
                  returns (bool)
              {
                  return issuanceData[account].initialDebtOwnership > 0;
              }
          
              event IssuanceRatioUpdated(uint newRatio);
          }
          
          

          File 7 of 8: TokenState
          /*
          -----------------------------------------------------------------
          FILE HEADER
          -----------------------------------------------------------------
          
          file:       TokenState.sol
          version:    1.0
          author:     Dominic Romanowski
                      Anton Jurisevic
          
          date:       2018-2-24
          checked:    Anton Jurisevic
          approved:   Samuel Brooks
          
          repo:       https://github.com/Havven/havven
          commit:     34e66009b98aa18976226c139270970d105045e3
          
          -----------------------------------------------------------------
          CONTRACT 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.20;
          
          contract Owned {
              address public owner;
              address public nominatedOwner;
          
              function Owned(address _owner)
                  public
              {
                  owner = _owner;
              }
          
              function nominateOwner(address _owner)
                  external
                  onlyOwner
              {
                  nominatedOwner = _owner;
                  emit OwnerNominated(_owner);
              }
          
              function acceptOwnership()
                  external
              {
                  require(msg.sender == nominatedOwner);
                  emit OwnerChanged(owner, nominatedOwner);
                  owner = nominatedOwner;
                  nominatedOwner = address(0);
              }
          
              modifier onlyOwner
              {
                  require(msg.sender == owner);
                  _;
              }
          
              event OwnerNominated(address newOwner);
              event OwnerChanged(address oldOwner, address newOwner);
          }
          
          /*
          -----------------------------------------------------------------
          CONTRACT 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 Havven and EtherNomin.
          It provides an easy way to upgrade contract logic while
          maintaining all user balances and allowances. This is designed
          to 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 TokenState is Owned {
          
              // the address of the contract that can modify balances and allowances
              // this can only be changed by the owner of this contract
              address public associatedContract;
          
              // ERC20 fields.
              mapping(address => uint) public balanceOf;
              mapping(address => mapping(address => uint256)) public allowance;
          
              function TokenState(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);
              }
          
              function setAllowance(address tokenOwner, address spender, uint value)
                  external
                  onlyAssociatedContract
              {
                  allowance[tokenOwner][spender] = value;
              }
          
              function setBalanceOf(address account, uint value)
                  external
                  onlyAssociatedContract
              {
                  balanceOf[account] = value;
              }
          
          
              /* ========== MODIFIERS ========== */
          
              modifier onlyAssociatedContract
              {
                  require(msg.sender == associatedContract);
                  _;
              }
          
              /* ========== EVENTS ========== */
          
              event AssociatedContractUpdated(address _associatedContract);
          }
          
          /*
          MIT License
          
          Copyright (c) 2018 Havven
          
          Permission is hereby granted, free of charge, to any person obtaining a copy
          of this software and associated documentation files (the "Software"), to deal
          in the Software without restriction, including without limitation the rights
          to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          copies of the Software, and to permit persons to whom the Software is
          furnished to do so, subject to the following conditions:
          
          The above copyright notice and this permission notice shall be included in all
          copies or substantial portions of the Software.
          
          THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          SOFTWARE.
          */

          File 8 of 8: YAMDelegate
          pragma solidity 0.5.17;
          
          
          library SafeMath {
              /**
               * @dev Returns the addition of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `+` operator.
               *
               * Requirements:
               *
               * - Addition cannot overflow.
               */
              function add(uint256 a, uint256 b) internal pure returns (uint256) {
                  uint256 c = a + b;
                  require(c >= a, "SafeMath: addition overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               *
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                  return sub(a, b, "SafeMath: subtraction overflow");
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               *
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b <= a, errorMessage);
                  uint256 c = a - b;
          
                  return c;
              }
          
              /**
               * @dev Returns the multiplication of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `*` operator.
               *
               * Requirements:
               *
               * - Multiplication cannot overflow.
               */
              function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                  // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                  if (a == 0) {
                      return 0;
                  }
          
                  uint256 c = a * b;
                  require(c / a == b, "SafeMath: multiplication overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b) internal pure returns (uint256) {
                  return div(a, b, "SafeMath: division by zero");
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b > 0, errorMessage);
                  uint256 c = a / b;
                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
          
                  return c;
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                  return mod(a, b, "SafeMath: modulo by zero");
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts with custom message when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b != 0, errorMessage);
                  return a % b;
              }
          }
          
          
          contract YAMTokenStorage {
          
              using SafeMath for uint256;
          
              /**
               * @dev Guard variable for re-entrancy checks. Not currently used
               */
              bool internal _notEntered;
          
              /**
               * @notice EIP-20 token name for this token
               */
              string public name;
          
              /**
               * @notice EIP-20 token symbol for this token
               */
              string public symbol;
          
              /**
               * @notice EIP-20 token decimals for this token
               */
              uint8 public decimals;
          
              /**
               * @notice Governor for this contract
               */
              address public gov;
          
              /**
               * @notice Pending governance for this contract
               */
              address public pendingGov;
          
              /**
               * @notice Approved rebaser for this contract
               */
              address public rebaser;
          
              /**
               * @notice Reserve address of YAM protocol
               */
              address public incentivizer;
          
              /**
               * @notice Total supply of YAMs
               */
              uint256 public totalSupply;
          
              /**
               * @notice Internal decimals used to handle scaling factor
               */
              uint256 public constant internalDecimals = 10**24;
          
              /**
               * @notice Used for percentage maths
               */
              uint256 public constant BASE = 10**18;
          
              /**
               * @notice Scaling factor that adjusts everyone's balances
               */
              uint256 public yamsScalingFactor;
          
              mapping (address => uint256) internal _yamBalances;
          
              mapping (address => mapping (address => uint256)) internal _allowedFragments;
          
              uint256 public initSupply;
          
          }
          
          
          contract YAMGovernanceStorage {
              /// @notice A record of each accounts delegate
              mapping (address => address) internal _delegates;
          
              /// @notice A checkpoint for marking number of votes from a given block
              struct Checkpoint {
                  uint32 fromBlock;
                  uint256 votes;
              }
          
              /// @notice A record of votes checkpoints for each account, by index
              mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
          
              /// @notice The number of checkpoints for each account
              mapping (address => uint32) public numCheckpoints;
          
              /// @notice The EIP-712 typehash for the contract's domain
              bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
          
              /// @notice The EIP-712 typehash for the delegation struct used by the contract
              bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
          
              /// @notice A record of states for signing / validating signatures
              mapping (address => uint) public nonces;
          }
          
          
          contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
          
              /// @notice An event thats emitted when an account changes its delegate
              event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
          
              /// @notice An event thats emitted when a delegate account's vote balance changes
              event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
          
              /**
               * @notice Event emitted when tokens are rebased
               */
              event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
          
              /*** Gov Events ***/
          
              /**
               * @notice Event emitted when pendingGov is changed
               */
              event NewPendingGov(address oldPendingGov, address newPendingGov);
          
              /**
               * @notice Event emitted when gov is changed
               */
              event NewGov(address oldGov, address newGov);
          
              /**
               * @notice Sets the rebaser contract
               */
              event NewRebaser(address oldRebaser, address newRebaser);
          
              /**
               * @notice Sets the incentivizer contract
               */
              event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
          
              /* - ERC20 Events - */
          
              /**
               * @notice EIP20 Transfer event
               */
              event Transfer(address indexed from, address indexed to, uint amount);
          
              /**
               * @notice EIP20 Approval event
               */
              event Approval(address indexed owner, address indexed spender, uint amount);
          
              /* - Extra Events - */
              /**
               * @notice Tokens minted event
               */
              event Mint(address to, uint256 amount);
          
              // Public functions
              function transfer(address to, uint256 value) external returns(bool);
              function transferFrom(address from, address to, uint256 value) external returns(bool);
              function balanceOf(address who) external view returns(uint256);
              function balanceOfUnderlying(address who) external view returns(uint256);
              function allowance(address owner_, address spender) external view returns(uint256);
              function approve(address spender, uint256 value) external returns (bool);
              function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
              function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
              function maxScalingFactor() external view returns (uint256);
          
              /* - Governance Functions - */
              function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
              function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
              function delegate(address delegatee) external;
              function delegates(address delegator) external view returns (address);
              function getCurrentVotes(address account) external view returns (uint256);
          
              /* - Permissioned/Governance functions - */
              function mint(address to, uint256 amount) external returns (bool);
              function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
              function _setRebaser(address rebaser_) external;
              function _setIncentivizer(address incentivizer_) external;
              function _setPendingGov(address pendingGov_) external;
              function _acceptGov() external;
          }
          
          
          contract YAMGovernanceToken is YAMTokenInterface {
          
                /// @notice An event thats emitted when an account changes its delegate
              event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
          
              /// @notice An event thats emitted when a delegate account's vote balance changes
              event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
          
              /**
               * @notice Delegate votes from `msg.sender` to `delegatee`
               * @param delegator The address to get delegatee for
               */
              function delegates(address delegator)
                  external
                  view
                  returns (address)
              {
                  return _delegates[delegator];
              }
          
             /**
              * @notice Delegate votes from `msg.sender` to `delegatee`
              * @param delegatee The address to delegate votes to
              */
              function delegate(address delegatee) external {
                  return _delegate(msg.sender, delegatee);
              }
          
              /**
               * @notice Delegates votes from signatory to `delegatee`
               * @param delegatee The address to delegate votes to
               * @param nonce The contract state required to match the signature
               * @param expiry The time at which to expire the signature
               * @param v The recovery byte of the signature
               * @param r Half of the ECDSA signature pair
               * @param s Half of the ECDSA signature pair
               */
              function delegateBySig(
                  address delegatee,
                  uint nonce,
                  uint expiry,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              )
                  external
              {
                  bytes32 domainSeparator = keccak256(
                      abi.encode(
                          DOMAIN_TYPEHASH,
                          keccak256(bytes(name)),
                          getChainId(),
                          address(this)
                      )
                  );
          
                  bytes32 structHash = keccak256(
                      abi.encode(
                          DELEGATION_TYPEHASH,
                          delegatee,
                          nonce,
                          expiry
                      )
                  );
          
                  bytes32 digest = keccak256(
                      abi.encodePacked(
                          "\x19\x01",
                          domainSeparator,
                          structHash
                      )
                  );
          
                  address signatory = ecrecover(digest, v, r, s);
                  require(signatory != address(0), "YAM::delegateBySig: invalid signature");
                  require(nonce == nonces[signatory]++, "YAM::delegateBySig: invalid nonce");
                  require(now <= expiry, "YAM::delegateBySig: signature expired");
                  return _delegate(signatory, delegatee);
              }
          
              /**
               * @notice Gets the current votes balance for `account`
               * @param account The address to get votes balance
               * @return The number of current votes for `account`
               */
              function getCurrentVotes(address account)
                  external
                  view
                  returns (uint256)
              {
                  uint32 nCheckpoints = numCheckpoints[account];
                  return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
              }
          
              /**
               * @notice Determine the prior number of votes for an account as of a block number
               * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
               * @param account The address of the account to check
               * @param blockNumber The block number to get the vote balance at
               * @return The number of votes the account had as of the given block
               */
              function getPriorVotes(address account, uint blockNumber)
                  external
                  view
                  returns (uint256)
              {
                  require(blockNumber < block.number, "YAM::getPriorVotes: not yet determined");
          
                  uint32 nCheckpoints = numCheckpoints[account];
                  if (nCheckpoints == 0) {
                      return 0;
                  }
          
                  // First check most recent balance
                  if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
                      return checkpoints[account][nCheckpoints - 1].votes;
                  }
          
                  // Next check implicit zero balance
                  if (checkpoints[account][0].fromBlock > blockNumber) {
                      return 0;
                  }
          
                  uint32 lower = 0;
                  uint32 upper = nCheckpoints - 1;
                  while (upper > lower) {
                      uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
                      Checkpoint memory cp = checkpoints[account][center];
                      if (cp.fromBlock == blockNumber) {
                          return cp.votes;
                      } else if (cp.fromBlock < blockNumber) {
                          lower = center;
                      } else {
                          upper = center - 1;
                      }
                  }
                  return checkpoints[account][lower].votes;
              }
          
              function _delegate(address delegator, address delegatee)
                  internal
              {
                  address currentDelegate = _delegates[delegator];
                  uint256 delegatorBalance = _yamBalances[delegator]; // balance of underlying YAMs (not scaled);
                  _delegates[delegator] = delegatee;
          
                  emit DelegateChanged(delegator, currentDelegate, delegatee);
          
                  _moveDelegates(currentDelegate, delegatee, delegatorBalance);
              }
          
              function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
                  if (srcRep != dstRep && amount > 0) {
                      if (srcRep != address(0)) {
                          // decrease old representative
                          uint32 srcRepNum = numCheckpoints[srcRep];
                          uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                          uint256 srcRepNew = srcRepOld.sub(amount);
                          _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
                      }
          
                      if (dstRep != address(0)) {
                          // increase new representative
                          uint32 dstRepNum = numCheckpoints[dstRep];
                          uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                          uint256 dstRepNew = dstRepOld.add(amount);
                          _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
                      }
                  }
              }
          
              function _writeCheckpoint(
                  address delegatee,
                  uint32 nCheckpoints,
                  uint256 oldVotes,
                  uint256 newVotes
              )
                  internal
              {
                  uint32 blockNumber = safe32(block.number, "YAM::_writeCheckpoint: block number exceeds 32 bits");
          
                  if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
                      checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
                  } else {
                      checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
                      numCheckpoints[delegatee] = nCheckpoints + 1;
                  }
          
                  emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
              }
          
              function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
                  require(n < 2**32, errorMessage);
                  return uint32(n);
              }
          
              function getChainId() internal pure returns (uint) {
                  uint256 chainId;
                  assembly { chainId := chainid() }
                  return chainId;
              }
          }
          
          contract YAMToken is YAMGovernanceToken {
              // Modifiers
              modifier onlyGov() {
                  require(msg.sender == gov);
                  _;
              }
          
              modifier onlyRebaser() {
                  require(msg.sender == rebaser);
                  _;
              }
          
              modifier onlyMinter() {
                  require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
                  _;
              }
          
              modifier validRecipient(address to) {
                  require(to != address(0x0));
                  require(to != address(this));
                  _;
              }
          
              function initialize(
                  string memory name_,
                  string memory symbol_,
                  uint8 decimals_
              )
                  public
              {
                  require(yamsScalingFactor == 0, "already initialized");
                  name = name_;
                  symbol = symbol_;
                  decimals = decimals_;
              }
          
          
              /**
              * @notice Computes the current max scaling factor
              */
              function maxScalingFactor()
                  external
                  view
                  returns (uint256)
              {
                  return _maxScalingFactor();
              }
          
              function _maxScalingFactor()
                  internal
                  view
                  returns (uint256)
              {
                  // scaling factor can only go up to 2**256-1 = initSupply * yamsScalingFactor
                  // this is used to check if yamsScalingFactor will be too high to compute balances when rebasing.
                  return uint256(-1) / initSupply;
              }
          
              /**
              * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
              * @dev Limited to onlyMinter modifier
              */
              function mint(address to, uint256 amount)
                  external
                  onlyMinter
                  returns (bool)
              {
                  _mint(to, amount);
                  return true;
              }
          
              function _mint(address to, uint256 amount)
                  internal
              {
                // increase totalSupply
                totalSupply = totalSupply.add(amount);
          
                // get underlying value
                uint256 yamValue = amount.mul(internalDecimals).div(yamsScalingFactor);
          
                // increase initSupply
                initSupply = initSupply.add(yamValue);
          
                // make sure the mint didnt push maxScalingFactor too low
                require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
          
                // add balance
                _yamBalances[to] = _yamBalances[to].add(yamValue);
          
                // add delegates to the minter
                _moveDelegates(address(0), _delegates[to], yamValue);
                emit Mint(to, amount);
              }
          
              /* - ERC20 functionality - */
          
              /**
              * @dev Transfer tokens to a specified address.
              * @param to The address to transfer to.
              * @param value The amount to be transferred.
              * @return True on success, false otherwise.
              */
              function transfer(address to, uint256 value)
                  external
                  validRecipient(to)
                  returns (bool)
              {
                  // underlying balance is stored in yams, so divide by current scaling factor
          
                  // note, this means as scaling factor grows, dust will be untransferrable.
                  // minimum transfer value == yamsScalingFactor / 1e24;
          
                  // get amount in underlying
                  uint256 yamValue = value.mul(internalDecimals).div(yamsScalingFactor);
          
                  // sub from balance of sender
                  _yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
          
                  // add to balance of receiver
                  _yamBalances[to] = _yamBalances[to].add(yamValue);
                  emit Transfer(msg.sender, to, value);
          
                  _moveDelegates(_delegates[msg.sender], _delegates[to], yamValue);
                  return true;
              }
          
              /**
              * @dev Transfer tokens from one address to another.
              * @param from The address you want to send tokens from.
              * @param to The address you want to transfer to.
              * @param value The amount of tokens to be transferred.
              */
              function transferFrom(address from, address to, uint256 value)
                  external
                  validRecipient(to)
                  returns (bool)
              {
                  // decrease allowance
                  _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
          
                  // get value in yams
                  uint256 yamValue = value.mul(internalDecimals).div(yamsScalingFactor);
          
                  // sub from from
                  _yamBalances[from] = _yamBalances[from].sub(yamValue);
                  _yamBalances[to] = _yamBalances[to].add(yamValue);
                  emit Transfer(from, to, value);
          
                  _moveDelegates(_delegates[from], _delegates[to], yamValue);
                  return true;
              }
          
              /**
              * @param who The address to query.
              * @return The balance of the specified address.
              */
              function balanceOf(address who)
                external
                view
                returns (uint256)
              {
                return _yamBalances[who].mul(yamsScalingFactor).div(internalDecimals);
              }
          
              /** @notice Currently returns the internal storage amount
              * @param who The address to query.
              * @return The underlying balance of the specified address.
              */
              function balanceOfUnderlying(address who)
                external
                view
                returns (uint256)
              {
                return _yamBalances[who];
              }
          
              /**
               * @dev Function to check the amount of tokens that an owner has allowed to a spender.
               * @param owner_ The address which owns the funds.
               * @param spender The address which will spend the funds.
               * @return The number of tokens still available for the spender.
               */
              function allowance(address owner_, address spender)
                  external
                  view
                  returns (uint256)
              {
                  return _allowedFragments[owner_][spender];
              }
          
              /**
               * @dev Approve the passed address to spend the specified amount of tokens on behalf of
               * msg.sender. This method is included for ERC20 compatibility.
               * increaseAllowance and decreaseAllowance should be used instead.
               * Changing an allowance with this method brings the risk that someone may transfer both
               * the old and the new allowance - if they are both greater than zero - if a transfer
               * transaction is mined before the later approve() call is mined.
               *
               * @param spender The address which will spend the funds.
               * @param value The amount of tokens to be spent.
               */
              function approve(address spender, uint256 value)
                  external
                  returns (bool)
              {
                  _allowedFragments[msg.sender][spender] = value;
                  emit Approval(msg.sender, spender, value);
                  return true;
              }
          
              /**
               * @dev Increase the amount of tokens that an owner has allowed to a spender.
               * This method should be used instead of approve() to avoid the double approval vulnerability
               * described above.
               * @param spender The address which will spend the funds.
               * @param addedValue The amount of tokens to increase the allowance by.
               */
              function increaseAllowance(address spender, uint256 addedValue)
                  external
                  returns (bool)
              {
                  _allowedFragments[msg.sender][spender] =
                      _allowedFragments[msg.sender][spender].add(addedValue);
                  emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
                  return true;
              }
          
              /**
               * @dev Decrease the amount of tokens that an owner has allowed to a spender.
               *
               * @param spender The address which will spend the funds.
               * @param subtractedValue The amount of tokens to decrease the allowance by.
               */
              function decreaseAllowance(address spender, uint256 subtractedValue)
                  external
                  returns (bool)
              {
                  uint256 oldValue = _allowedFragments[msg.sender][spender];
                  if (subtractedValue >= oldValue) {
                      _allowedFragments[msg.sender][spender] = 0;
                  } else {
                      _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
                  }
                  emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
                  return true;
              }
          
              /* - Governance Functions - */
          
              /** @notice sets the rebaser
               * @param rebaser_ The address of the rebaser contract to use for authentication.
               */
              function _setRebaser(address rebaser_)
                  external
                  onlyGov
              {
                  address oldRebaser = rebaser;
                  rebaser = rebaser_;
                  emit NewRebaser(oldRebaser, rebaser_);
              }
          
              /** @notice sets the incentivizer
               * @param incentivizer_ The address of the rebaser contract to use for authentication.
               */
              function _setIncentivizer(address incentivizer_)
                  external
                  onlyGov
              {
                  address oldIncentivizer = incentivizer;
                  incentivizer = incentivizer_;
                  emit NewIncentivizer(oldIncentivizer, incentivizer_);
              }
          
              /** @notice sets the pendingGov
               * @param pendingGov_ The address of the rebaser contract to use for authentication.
               */
              function _setPendingGov(address pendingGov_)
                  external
                  onlyGov
              {
                  address oldPendingGov = pendingGov;
                  pendingGov = pendingGov_;
                  emit NewPendingGov(oldPendingGov, pendingGov_);
              }
          
              /** @notice lets msg.sender accept governance
               *
               */
              function _acceptGov()
                  external
              {
                  require(msg.sender == pendingGov, "!pending");
                  address oldGov = gov;
                  gov = pendingGov;
                  pendingGov = address(0);
                  emit NewGov(oldGov, gov);
              }
          
              /* - Extras - */
          
              /**
              * @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
              *
              * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
              *      Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
              *      and targetRate is CpiOracleRate / baseCpi
              */
              function rebase(
                  uint256 epoch,
                  uint256 indexDelta,
                  bool positive
              )
                  external
                  onlyRebaser
                  returns (uint256)
              {
                  if (indexDelta == 0) {
                    emit Rebase(epoch, yamsScalingFactor, yamsScalingFactor);
                    return totalSupply;
                  }
          
                  uint256 prevYamsScalingFactor = yamsScalingFactor;
          
                  if (!positive) {
                     yamsScalingFactor = yamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
                  } else {
                      uint256 newScalingFactor = yamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
                      if (newScalingFactor < _maxScalingFactor()) {
                          yamsScalingFactor = newScalingFactor;
                      } else {
                        yamsScalingFactor = _maxScalingFactor();
                      }
                  }
          
                  totalSupply = initSupply.mul(yamsScalingFactor);
                  emit Rebase(epoch, prevYamsScalingFactor, yamsScalingFactor);
                  return totalSupply;
              }
          }
          
          contract YAM is YAMToken {
              /**
               * @notice Initialize the new money market
               * @param name_ ERC-20 name of this token
               * @param symbol_ ERC-20 symbol of this token
               * @param decimals_ ERC-20 decimal precision of this token
               */
              function initialize(
                  string memory name_,
                  string memory symbol_,
                  uint8 decimals_,
                  address initial_owner,
                  uint256 initSupply_
              )
                  public
              {
                  require(initSupply_ > 0, "0 init supply");
          
                  super.initialize(name_, symbol_, decimals_);
          
                  initSupply = initSupply_.mul(10**24/ (BASE));
                  totalSupply = initSupply_;
                  yamsScalingFactor = BASE;
                  _yamBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));
          
                  // owner renounces ownership after deployment as they need to set
                  // rebaser and incentivizer
                  // gov = gov_;
              }
          }
          
          contract YAMDelegationStorage {
              /**
               * @notice Implementation address for this contract
               */
              address public implementation;
          }
          
          contract YAMDelegateInterface is YAMDelegationStorage {
              /**
               * @notice Called by the delegator on a delegate to initialize it for duty
               * @dev Should revert if any issues arise which make it unfit for delegation
               * @param data The encoded bytes data for any initialization
               */
              function _becomeImplementation(bytes memory data) public;
          
              /**
               * @notice Called by the delegator on a delegate to forfeit its responsibility
               */
              function _resignImplementation() public;
          }
          
          contract YAMDelegate is YAM, YAMDelegateInterface {
              /**
               * @notice Construct an empty delegate
               */
              constructor() public {}
          
              /**
               * @notice Called by the delegator on a delegate to initialize it for duty
               * @param data The encoded bytes data for any initialization
               */
              function _becomeImplementation(bytes memory data) public {
                  // Shh -- currently unused
                  data;
          
                  // Shh -- we don't ever want this hook to be marked pure
                  if (false) {
                      implementation = address(0);
                  }
          
                  require(msg.sender == gov, "only the gov may call _becomeImplementation");
              }
          
              /**
               * @notice Called by the delegator on a delegate to forfeit its responsibility
               */
              function _resignImplementation() public {
                  // Shh -- we don't ever want this hook to be marked pure
                  if (false) {
                      implementation = address(0);
                  }
          
                  require(msg.sender == gov, "only the gov may call _resignImplementation");
              }
          }