ETH Price: $2,554.05 (-4.30%)

Transaction Decoder

Block:
10260313 at Jun-13-2020 11:25:16 PM +UTC
Transaction Fee:
0.0016887006 ETH $4.31
Gas Used:
119,766 Gas / 14.1 Gwei

Emitted Events:

81 WETH9.Transfer( src=[Receiver] StakingProxy, dst=[Sender] 0xd1898665a01a91ac10bd2c6cb1899336df34ac33, wad=119980513098491 )
82 StakingProxy.0x7d3ad1dcf03b9027064d1d9a474a69e0cecc31324c541d3eb9b5e6fa2f106c8d( 0x7d3ad1dcf03b9027064d1d9a474a69e0cecc31324c541d3eb9b5e6fa2f106c8d, 0x000000000000000000000000d1898665a01a91ac10bd2c6cb1899336df34ac33, 0x0000000000000000000000000000000000000000000000000000000000000010, 0x0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000026acf80c086ab0000, 0000000000000000000000000000000000000000000000000000000000000001, 0000000000000000000000000000000000000000000000000000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
0xa26e80e7...E6CFfA777
(0x: Staking Proxy V3)
0xC02aaA39...83C756Cc2
0xD1898665...6df34AC33
0.602239021557694365 Eth
Nonce: 255
0.600550320957694365 Eth
Nonce: 256
0.0016887006
(Ethermine)
789.410757668183340497 Eth789.412446368783340497 Eth0.0016887006

Execution Trace

StakingProxy.batchExecute( data=[WPbH4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACas+AwIarAAA=] ) => ( batchReturnData=[] )
  • Staking.moveStake( from=[{name:status, type:uint8, order:1, indexed:false, value:1, valueString:1}, {name:poolId, type:bytes32, order:2, indexed:false, value:0000000000000000000000000000000000000000000000000000000000000010, valueString:0000000000000000000000000000000000000000000000000000000000000010}], to=[{name:status, type:uint8, order:1, indexed:false, value:0, valueString:0}, {name:poolId, type:bytes32, order:2, indexed:false, value:0000000000000000000000000000000000000000000000000000000000000000, valueString:0000000000000000000000000000000000000000000000000000000000000000}], amount=44590000000000000000 )
    • WETH9.transfer( dst=0xD1898665a01A91AC10bD2C6cb1899336df34AC33, wad=119980513098491 ) => ( True )
      batchExecute[StakingProxy (ln:4477)]
      File 1 of 3: StakingProxy
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./interfaces/IStaking.sol";
      import "./sys/MixinParams.sol";
      import "./stake/MixinStake.sol";
      import "./fees/MixinExchangeFees.sol";
      contract Staking is
          IStaking,
          MixinParams,
          MixinStake,
          MixinExchangeFees
      {
          /// @dev Initialize storage owned by this contract.
          ///      This function should not be called directly.
          ///      The StakingProxy contract will call it in `attachStakingContract()`.
          function init()
              public
              onlyAuthorized
          {
              // DANGER! When performing upgrades, take care to modify this logic
              // to prevent accidentally clearing prior state.
              _initMixinScheduler();
              _initMixinParams();
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
      import "./IStructs.sol";
      import "./IZrxVault.sol";
      interface IStaking {
          /// @dev Adds a new exchange address
          /// @param addr Address of exchange contract to add
          function addExchangeAddress(address addr)
              external;
          /// @dev Create a new staking pool. The sender will be the operator of this pool.
          /// Note that an operator must be payable.
          /// @param operatorShare Portion of rewards owned by the operator, in ppm.
          /// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true.
          /// @return poolId The unique pool id generated for this pool.
          function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker)
              external
              returns (bytes32 poolId);
          /// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
          /// @param poolId Unique Id of pool.
          /// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
          function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
              external;
          /// @dev Begins a new epoch, preparing the prior one for finalization.
          ///      Throws if not enough time has passed between epochs or if the
          ///      previous epoch was not fully finalized.
          /// @return numPoolsToFinalize The number of unfinalized pools.
          function endEpoch()
              external
              returns (uint256);
          /// @dev Instantly finalizes a single pool that earned rewards in the previous
          ///      epoch, crediting it rewards for members and withdrawing operator's
          ///      rewards as WETH. This can be called by internal functions that need
          ///      to finalize a pool immediately. Does nothing if the pool is already
          ///      finalized or did not earn rewards in the previous epoch.
          /// @param poolId The pool ID to finalize.
          function finalizePool(bytes32 poolId)
              external;
          /// @dev Initialize storage owned by this contract.
          ///      This function should not be called directly.
          ///      The StakingProxy contract will call it in `attachStakingContract()`.
          function init()
              external;
          /// @dev Allows caller to join a staking pool as a maker.
          /// @param poolId Unique id of pool.
          function joinStakingPoolAsMaker(bytes32 poolId)
              external;
          /// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
          ///      Delegated stake can also be moved between pools.
          ///      This change comes into effect next epoch.
          /// @param from status to move stake out of.
          /// @param to status to move stake into.
          /// @param amount of stake to move.
          function moveStake(
              IStructs.StakeInfo calldata from,
              IStructs.StakeInfo calldata to,
              uint256 amount
          )
              external;
          /// @dev Pays a protocol fee in ETH.
          /// @param makerAddress The address of the order's maker.
          /// @param payerAddress The address that is responsible for paying the protocol fee.
          /// @param protocolFee The amount of protocol fees that should be paid.
          function payProtocolFee(
              address makerAddress,
              address payerAddress,
              uint256 protocolFee
          )
              external
              payable;
          /// @dev Removes an existing exchange address
          /// @param addr Address of exchange contract to remove
          function removeExchangeAddress(address addr)
              external;
          /// @dev Set all configurable parameters at once.
          /// @param _epochDurationInSeconds Minimum seconds between epochs.
          /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function setParams(
              uint256 _epochDurationInSeconds,
              uint32 _rewardDelegatedStakeWeight,
              uint256 _minimumPoolStake,
              uint32 _cobbDouglasAlphaNumerator,
              uint32 _cobbDouglasAlphaDenominator
          )
              external;
          /// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
          ///      Unstake to retrieve the ZRX. Stake is in the 'Active' status.
          /// @param amount of ZRX to stake.
          function stake(uint256 amount)
              external;
          /// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
          ///      the staker. Stake must be in the 'undelegated' status in both the
          ///      current and next epoch in order to be unstaked.
          /// @param amount of ZRX to unstake.
          function unstake(uint256 amount)
              external;
          /// @dev Withdraws the caller's WETH rewards that have accumulated
          ///      until the last epoch.
          /// @param poolId Unique id of pool.
          function withdrawDelegatorRewards(bytes32 poolId)
              external;
          /// @dev Computes the reward balance in ETH of a specific member of a pool.
          /// @param poolId Unique id of pool.
          /// @param member The member of the pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfDelegator(bytes32 poolId, address member)
              external
              view
              returns (uint256 reward);
          /// @dev Computes the reward balance in ETH of the operator of a pool.
          /// @param poolId Unique id of pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfOperator(bytes32 poolId)
              external
              view
              returns (uint256 reward);
          /// @dev Returns the earliest end time in seconds of this epoch.
          ///      The next epoch can begin once this time is reached.
          ///      Epoch period = [startTimeInSeconds..endTimeInSeconds)
          /// @return Time in seconds.
          function getCurrentEpochEarliestEndTimeInSeconds()
              external
              view
              returns (uint256);
          /// @dev Gets global stake for a given status.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Global stake for given status.
          function getGlobalStakeByStatus(IStructs.StakeStatus stakeStatus)
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev Gets an owner's stake balances by status.
          /// @param staker Owner of stake.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Owner's stake balances for given status.
          function getOwnerStakeByStatus(
              address staker,
              IStructs.StakeStatus stakeStatus
          )
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev Retrieves all configurable parameter values.
          /// @return _epochDurationInSeconds Minimum seconds between epochs.
          /// @return _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @return _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @return _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @return _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function getParams()
              external
              view
              returns (
                  uint256 _epochDurationInSeconds,
                  uint32 _rewardDelegatedStakeWeight,
                  uint256 _minimumPoolStake,
                  uint32 _cobbDouglasAlphaNumerator,
                  uint32 _cobbDouglasAlphaDenominator
              );
          /// @param staker of stake.
          /// @param poolId Unique Id of pool.
          /// @return Stake delegated to pool by staker.
          function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId)
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev Returns a staking pool
          /// @param poolId Unique id of pool.
          function getStakingPool(bytes32 poolId)
              external
              view
              returns (IStructs.Pool memory);
          /// @dev Get stats on a staking pool in this epoch.
          /// @param poolId Pool Id to query.
          /// @return PoolStats struct for pool id.
          function getStakingPoolStatsThisEpoch(bytes32 poolId)
              external
              view
              returns (IStructs.PoolStats memory);
          /// @dev Returns the total stake delegated to a specific staking pool,
          ///      across all members.
          /// @param poolId Unique Id of pool.
          /// @return Total stake delegated to pool.
          function getTotalStakeDelegatedToPool(bytes32 poolId)
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev An overridable way to access the deployed WETH contract.
          ///      Must be view to allow overrides to access state.
          /// @return wethContract The WETH contract instance.
          function getWethContract()
              external
              view
              returns (IEtherToken wethContract);
          /// @dev An overridable way to access the deployed zrxVault.
          ///      Must be view to allow overrides to access state.
          /// @return zrxVault The zrxVault contract.
          function getZrxVault()
              external
              view
              returns (IZrxVault zrxVault);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./IERC20Token.sol";
      contract IEtherToken is
          IERC20Token
      {
          function deposit()
              public
              payable;
          
          function withdraw(uint256 amount)
              public;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract IERC20Token {
          // solhint-disable no-simple-event-func-name
          event Transfer(
              address indexed _from,
              address indexed _to,
              uint256 _value
          );
          event Approval(
              address indexed _owner,
              address indexed _spender,
              uint256 _value
          );
          /// @dev send `value` token to `to` from `msg.sender`
          /// @param _to The address of the recipient
          /// @param _value The amount of token to be transferred
          /// @return True if transfer was successful
          function transfer(address _to, uint256 _value)
              external
              returns (bool);
          /// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
          /// @param _from The address of the sender
          /// @param _to The address of the recipient
          /// @param _value The amount of token to be transferred
          /// @return True if transfer was successful
          function transferFrom(
              address _from,
              address _to,
              uint256 _value
          )
              external
              returns (bool);
          /// @dev `msg.sender` approves `_spender` to spend `_value` tokens
          /// @param _spender The address of the account able to transfer the tokens
          /// @param _value The amount of wei to be approved for transfer
          /// @return Always true if the call has enough gas to complete execution
          function approve(address _spender, uint256 _value)
              external
              returns (bool);
          /// @dev Query total supply of token
          /// @return Total supply of token
          function totalSupply()
              external
              view
              returns (uint256);
          /// @param _owner The address from which the balance will be retrieved
          /// @return Balance of owner
          function balanceOf(address _owner)
              external
              view
              returns (uint256);
          /// @param _owner The address of the account owning tokens
          /// @param _spender The address of the account able to transfer the tokens
          /// @return Amount of remaining tokens allowed to spent
          function allowance(address _owner, address _spender)
              external
              view
              returns (uint256);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      interface IStructs {
          /// @dev Stats for a pool that earned rewards.
          /// @param feesCollected Fees collected in ETH by this pool.
          /// @param weightedStake Amount of weighted stake in the pool.
          /// @param membersStake Amount of non-operator stake in the pool.
          struct PoolStats {
              uint256 feesCollected;
              uint256 weightedStake;
              uint256 membersStake;
          }
          /// @dev Holds stats aggregated across a set of pools.
          /// @param rewardsAvailable Rewards (ETH) available to the epoch
          ///        being finalized (the previous epoch). This is simply the balance
          ///        of the contract at the end of the epoch.
          /// @param numPoolsToFinalize The number of pools that have yet to be finalized through `finalizePools()`.
          /// @param totalFeesCollected The total fees collected for the epoch being finalized.
          /// @param totalWeightedStake The total fees collected for the epoch being finalized.
          /// @param totalRewardsFinalized Amount of rewards that have been paid during finalization.
          struct AggregatedStats {
              uint256 rewardsAvailable;
              uint256 numPoolsToFinalize;
              uint256 totalFeesCollected;
              uint256 totalWeightedStake;
              uint256 totalRewardsFinalized;
          }
          /// @dev Encapsulates a balance for the current and next epochs.
          /// Note that these balances may be stale if the current epoch
          /// is greater than `currentEpoch`.
          /// @param currentEpoch the current epoch
          /// @param currentEpochBalance balance in the current epoch.
          /// @param nextEpochBalance balance in `currentEpoch+1`.
          struct StoredBalance {
              uint64 currentEpoch;
              uint96 currentEpochBalance;
              uint96 nextEpochBalance;
          }
          /// @dev Statuses that stake can exist in.
          ///      Any stake can be (re)delegated effective at the next epoch
          ///      Undelegated stake can be withdrawn if it is available in both the current and next epoch
          enum StakeStatus {
              UNDELEGATED,
              DELEGATED
          }
          /// @dev Info used to describe a status.
          /// @param status of the stake.
          /// @param poolId Unique Id of pool. This is set when status=DELEGATED.
          struct StakeInfo {
              StakeStatus status;
              bytes32 poolId;
          }
          /// @dev Struct to represent a fraction.
          /// @param numerator of fraction.
          /// @param denominator of fraction.
          struct Fraction {
              uint256 numerator;
              uint256 denominator;
          }
          /// @dev Holds the metadata for a staking pool.
          /// @param operator of the pool.
          /// @param operatorShare Fraction of the total balance owned by the operator, in ppm.
          struct Pool {
              address operator;
              uint32 operatorShare;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      interface IZrxVault {
          /// @dev Emmitted whenever a StakingProxy is set in a vault.
          event StakingProxySet(address stakingProxyAddress);
          /// @dev Emitted when the Staking contract is put into Catastrophic Failure Mode
          /// @param sender Address of sender (`msg.sender`)
          event InCatastrophicFailureMode(address sender);
          /// @dev Emitted when Zrx Tokens are deposited into the vault.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens deposited.
          event Deposit(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted when Zrx Tokens are withdrawn from the vault.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens withdrawn.
          event Withdraw(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted whenever the ZRX AssetProxy is set.
          event ZrxProxySet(address zrxProxyAddress);
          /// @dev Sets the address of the StakingProxy contract.
          /// Note that only the contract staker can call this function.
          /// @param _stakingProxyAddress Address of Staking proxy contract.
          function setStakingProxy(address _stakingProxyAddress)
              external;
          /// @dev Vault enters into Catastrophic Failure Mode.
          /// *** WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! ***
          /// Note that only the contract staker can call this function.
          function enterCatastrophicFailure()
              external;
          /// @dev Sets the Zrx proxy.
          /// Note that only the contract staker can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param zrxProxyAddress Address of the 0x Zrx Proxy.
          function setZrxProxy(address zrxProxyAddress)
              external;
          /// @dev Deposit an `amount` of Zrx Tokens from `staker` into the vault.
          /// Note that only the Staking contract can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to deposit.
          function depositFrom(address staker, uint256 amount)
              external;
          /// @dev Withdraw an `amount` of Zrx Tokens to `staker` from the vault.
          /// Note that only the Staking contract can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to withdraw.
          function withdrawFrom(address staker, uint256 amount)
              external;
          /// @dev Withdraw ALL Zrx Tokens to `staker` from the vault.
          /// Note that this can only be called when *in* Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          function withdrawAllFrom(address staker)
              external
              returns (uint256);
          /// @dev Returns the balance in Zrx Tokens of the `staker`
          /// @return Balance in Zrx.
          function balanceOf(address staker)
              external
              view
              returns (uint256);
          /// @dev Returns the entire balance of Zrx tokens in the vault.
          function balanceOfZrxVault()
              external
              view
              returns (uint256);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "../immutable/MixinStorage.sol";
      import "../immutable/MixinConstants.sol";
      import "../interfaces/IStakingEvents.sol";
      import "../interfaces/IStakingProxy.sol";
      import "../libs/LibStakingRichErrors.sol";
      contract MixinParams is
          IStakingEvents,
          MixinStorage,
          MixinConstants
      {
          /// @dev Set all configurable parameters at once.
          /// @param _epochDurationInSeconds Minimum seconds between epochs.
          /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function setParams(
              uint256 _epochDurationInSeconds,
              uint32 _rewardDelegatedStakeWeight,
              uint256 _minimumPoolStake,
              uint32 _cobbDouglasAlphaNumerator,
              uint32 _cobbDouglasAlphaDenominator
          )
              external
              onlyAuthorized
          {
              _setParams(
                  _epochDurationInSeconds,
                  _rewardDelegatedStakeWeight,
                  _minimumPoolStake,
                  _cobbDouglasAlphaNumerator,
                  _cobbDouglasAlphaDenominator
              );
              // Let the staking proxy enforce that these parameters are within
              // acceptable ranges.
              IStakingProxy(address(this)).assertValidStorageParams();
          }
          /// @dev Retrieves all configurable parameter values.
          /// @return _epochDurationInSeconds Minimum seconds between epochs.
          /// @return _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @return _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @return _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @return _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function getParams()
              external
              view
              returns (
                  uint256 _epochDurationInSeconds,
                  uint32 _rewardDelegatedStakeWeight,
                  uint256 _minimumPoolStake,
                  uint32 _cobbDouglasAlphaNumerator,
                  uint32 _cobbDouglasAlphaDenominator
              )
          {
              _epochDurationInSeconds = epochDurationInSeconds;
              _rewardDelegatedStakeWeight = rewardDelegatedStakeWeight;
              _minimumPoolStake = minimumPoolStake;
              _cobbDouglasAlphaNumerator = cobbDouglasAlphaNumerator;
              _cobbDouglasAlphaDenominator = cobbDouglasAlphaDenominator;
          }
          /// @dev Initialize storage belonging to this mixin.
          function _initMixinParams()
              internal
          {
              // Ensure state is uninitialized.
              _assertParamsNotInitialized();
              // Set up defaults.
              uint256 _epochDurationInSeconds = 10 days;
              uint32 _rewardDelegatedStakeWeight = (90 * PPM_DENOMINATOR) / 100;
              uint256 _minimumPoolStake = 100 * MIN_TOKEN_VALUE;
              uint32 _cobbDouglasAlphaNumerator = 2;
              uint32 _cobbDouglasAlphaDenominator = 3;
              _setParams(
                  _epochDurationInSeconds,
                  _rewardDelegatedStakeWeight,
                  _minimumPoolStake,
                  _cobbDouglasAlphaNumerator,
                  _cobbDouglasAlphaDenominator
              );
          }
          /// @dev Asserts that upgradable storage has not yet been initialized.
          function _assertParamsNotInitialized()
              internal
              view
          {
              if (epochDurationInSeconds != 0 &&
                  rewardDelegatedStakeWeight != 0 &&
                  minimumPoolStake != 0 &&
                  cobbDouglasAlphaNumerator != 0 &&
                  cobbDouglasAlphaDenominator != 0
              ) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InitializationError(
                          LibStakingRichErrors.InitializationErrorCodes.MixinParamsAlreadyInitialized
                      )
                  );
              }
          }
          /// @dev Set all configurable parameters at once.
          /// @param _epochDurationInSeconds Minimum seconds between epochs.
          /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function _setParams(
              uint256 _epochDurationInSeconds,
              uint32 _rewardDelegatedStakeWeight,
              uint256 _minimumPoolStake,
              uint32 _cobbDouglasAlphaNumerator,
              uint32 _cobbDouglasAlphaDenominator
          )
              private
          {
              epochDurationInSeconds = _epochDurationInSeconds;
              rewardDelegatedStakeWeight = _rewardDelegatedStakeWeight;
              minimumPoolStake = _minimumPoolStake;
              cobbDouglasAlphaNumerator = _cobbDouglasAlphaNumerator;
              cobbDouglasAlphaDenominator = _cobbDouglasAlphaDenominator;
              emit ParamsSet(
                  _epochDurationInSeconds,
                  _rewardDelegatedStakeWeight,
                  _minimumPoolStake,
                  _cobbDouglasAlphaNumerator,
                  _cobbDouglasAlphaDenominator
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      library LibRichErrors {
          // bytes4(keccak256("Error(string)"))
          bytes4 internal constant STANDARD_ERROR_SELECTOR =
              0x08c379a0;
          // solhint-disable func-name-mixedcase
          /// @dev ABI encode a standard, string revert error payload.
          ///      This is the same payload that would be included by a `revert(string)`
          ///      solidity statement. It has the function signature `Error(string)`.
          /// @param message The error string.
          /// @return The ABI encoded error.
          function StandardError(
              string memory message
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  STANDARD_ERROR_SELECTOR,
                  bytes(message)
              );
          }
          // solhint-enable func-name-mixedcase
          /// @dev Reverts an encoded rich revert reason `errorData`.
          /// @param errorData ABI encoded error data.
          function rrevert(bytes memory errorData)
              internal
              pure
          {
              assembly {
                  revert(add(errorData, 0x20), mload(errorData))
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/Authorizable.sol";
      import "./MixinConstants.sol";
      import "../interfaces/IZrxVault.sol";
      import "../interfaces/IStructs.sol";
      import "../libs/LibStakingRichErrors.sol";
      // solhint-disable max-states-count, no-empty-blocks
      contract MixinStorage is
          Authorizable
      {
          // address of staking contract
          address public stakingContract;
          // mapping from StakeStatus to global stored balance
          // NOTE: only Status.DELEGATED is used to access this mapping, but this format
          // is used for extensibility
          mapping (uint8 => IStructs.StoredBalance) internal _globalStakeByStatus;
          // mapping from StakeStatus to address of staker to stored balance
          mapping (uint8 => mapping (address => IStructs.StoredBalance)) internal _ownerStakeByStatus;
          // Mapping from Owner to Pool Id to Amount Delegated
          mapping (address => mapping (bytes32 => IStructs.StoredBalance)) internal _delegatedStakeToPoolByOwner;
          // Mapping from Pool Id to Amount Delegated
          mapping (bytes32 => IStructs.StoredBalance) internal _delegatedStakeByPoolId;
          // tracking Pool Id, a unique identifier for each staking pool.
          bytes32 public lastPoolId;
          // mapping from Maker Address to Pool Id of maker
          mapping (address => bytes32) public poolIdByMaker;
          // mapping from Pool Id to Pool
          mapping (bytes32 => IStructs.Pool) internal _poolById;
          // mapping from PoolId to balance of members
          mapping (bytes32 => uint256) public rewardsByPoolId;
          // current epoch
          uint256 public currentEpoch;
          // current epoch start time
          uint256 public currentEpochStartTimeInSeconds;
          // mapping from Pool Id to Epoch to Reward Ratio
          mapping (bytes32 => mapping (uint256 => IStructs.Fraction)) internal _cumulativeRewardsByPool;
          // mapping from Pool Id to Epoch
          mapping (bytes32 => uint256) internal _cumulativeRewardsByPoolLastStored;
          // registered 0x Exchange contracts
          mapping (address => bool) public validExchanges;
          /* Tweakable parameters */
          // Minimum seconds between epochs.
          uint256 public epochDurationInSeconds;
          // How much delegated stake is weighted vs operator stake, in ppm.
          uint32 public rewardDelegatedStakeWeight;
          // Minimum amount of stake required in a pool to collect rewards.
          uint256 public minimumPoolStake;
          // Numerator for cobb douglas alpha factor.
          uint32 public cobbDouglasAlphaNumerator;
          // Denominator for cobb douglas alpha factor.
          uint32 public cobbDouglasAlphaDenominator;
          /* State for finalization */
          /// @dev Stats for each pool that generated fees with sufficient stake to earn rewards.
          ///      See `_minimumPoolStake` in MixinParams.
          mapping (bytes32 => mapping (uint256 => IStructs.PoolStats)) public poolStatsByEpoch;
          /// @dev Aggregated stats across all pools that generated fees with sufficient stake to earn rewards.
          ///      See `_minimumPoolStake` in MixinParams.
          mapping (uint256 => IStructs.AggregatedStats) public aggregatedStatsByEpoch;
          /// @dev The WETH balance of this contract that is reserved for pool reward payouts.
          uint256 public wethReservedForPoolRewards;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./interfaces/IAuthorizable.sol";
      import "./LibAuthorizableRichErrors.sol";
      import "./LibRichErrors.sol";
      import "./Ownable.sol";
      // solhint-disable no-empty-blocks
      contract Authorizable is
          Ownable,
          IAuthorizable
      {
          /// @dev Only authorized addresses can invoke functions with this modifier.
          modifier onlyAuthorized {
              _assertSenderIsAuthorized();
              _;
          }
          mapping (address => bool) public authorized;
          address[] public authorities;
          /// @dev Initializes the `owner` address.
          constructor()
              public
              Ownable()
          {}
          /// @dev Authorizes an address.
          /// @param target Address to authorize.
          function addAuthorizedAddress(address target)
              external
              onlyOwner
          {
              _addAuthorizedAddress(target);
          }
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          function removeAuthorizedAddress(address target)
              external
              onlyOwner
          {
              if (!authorized[target]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetNotAuthorizedError(target));
              }
              for (uint256 i = 0; i < authorities.length; i++) {
                  if (authorities[i] == target) {
                      _removeAuthorizedAddressAtIndex(target, i);
                      break;
                  }
              }
          }
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          /// @param index Index of target in authorities array.
          function removeAuthorizedAddressAtIndex(
              address target,
              uint256 index
          )
              external
              onlyOwner
          {
              _removeAuthorizedAddressAtIndex(target, index);
          }
          /// @dev Gets all authorized addresses.
          /// @return Array of authorized addresses.
          function getAuthorizedAddresses()
              external
              view
              returns (address[] memory)
          {
              return authorities;
          }
          /// @dev Reverts if msg.sender is not authorized.
          function _assertSenderIsAuthorized()
              internal
              view
          {
              if (!authorized[msg.sender]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.SenderNotAuthorizedError(msg.sender));
              }
          }
          /// @dev Authorizes an address.
          /// @param target Address to authorize.
          function _addAuthorizedAddress(address target)
              internal
          {
              // Ensure that the target is not the zero address.
              if (target == address(0)) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.ZeroCantBeAuthorizedError());
              }
              // Ensure that the target is not already authorized.
              if (authorized[target]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetAlreadyAuthorizedError(target));
              }
              authorized[target] = true;
              authorities.push(target);
              emit AuthorizedAddressAdded(target, msg.sender);
          }
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          /// @param index Index of target in authorities array.
          function _removeAuthorizedAddressAtIndex(
              address target,
              uint256 index
          )
              internal
          {
              if (!authorized[target]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetNotAuthorizedError(target));
              }
              if (index >= authorities.length) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.IndexOutOfBoundsError(
                      index,
                      authorities.length
                  ));
              }
              if (authorities[index] != target) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.AuthorizedAddressMismatchError(
                      authorities[index],
                      target
                  ));
              }
              delete authorized[target];
              authorities[index] = authorities[authorities.length - 1];
              authorities.length -= 1;
              emit AuthorizedAddressRemoved(target, msg.sender);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./IOwnable.sol";
      contract IAuthorizable is
          IOwnable
      {
          // Event logged when a new address is authorized.
          event AuthorizedAddressAdded(
              address indexed target,
              address indexed caller
          );
          // Event logged when a currently authorized address is unauthorized.
          event AuthorizedAddressRemoved(
              address indexed target,
              address indexed caller
          );
          /// @dev Authorizes an address.
          /// @param target Address to authorize.
          function addAuthorizedAddress(address target)
              external;
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          function removeAuthorizedAddress(address target)
              external;
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          /// @param index Index of target in authorities array.
          function removeAuthorizedAddressAtIndex(
              address target,
              uint256 index
          )
              external;
          /// @dev Gets all authorized addresses.
          /// @return Array of authorized addresses.
          function getAuthorizedAddresses()
              external
              view
              returns (address[] memory);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract IOwnable {
          /// @dev Emitted by Ownable when ownership is transferred.
          /// @param previousOwner The previous owner of the contract.
          /// @param newOwner The new owner of the contract.
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /// @dev Transfers ownership of the contract to a new address.
          /// @param newOwner The address that will become the owner.
          function transferOwnership(address newOwner)
              public;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      library LibAuthorizableRichErrors {
          // bytes4(keccak256("AuthorizedAddressMismatchError(address,address)"))
          bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR =
              0x140a84db;
          // bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)"))
          bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR =
              0xe9f83771;
          // bytes4(keccak256("SenderNotAuthorizedError(address)"))
          bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR =
              0xb65a25b9;
          // bytes4(keccak256("TargetAlreadyAuthorizedError(address)"))
          bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR =
              0xde16f1a0;
          // bytes4(keccak256("TargetNotAuthorizedError(address)"))
          bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR =
              0xeb5108a2;
          // bytes4(keccak256("ZeroCantBeAuthorizedError()"))
          bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES =
              hex"57654fe4";
          // solhint-disable func-name-mixedcase
          function AuthorizedAddressMismatchError(
              address authorized,
              address target
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR,
                  authorized,
                  target
              );
          }
          function IndexOutOfBoundsError(
              uint256 index,
              uint256 length
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR,
                  index,
                  length
              );
          }
          function SenderNotAuthorizedError(address sender)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  SENDER_NOT_AUTHORIZED_ERROR_SELECTOR,
                  sender
              );
          }
          function TargetAlreadyAuthorizedError(address target)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR,
                  target
              );
          }
          function TargetNotAuthorizedError(address target)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  TARGET_NOT_AUTHORIZED_ERROR_SELECTOR,
                  target
              );
          }
          function ZeroCantBeAuthorizedError()
              internal
              pure
              returns (bytes memory)
          {
              return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./interfaces/IOwnable.sol";
      import "./LibOwnableRichErrors.sol";
      import "./LibRichErrors.sol";
      contract Ownable is
          IOwnable
      {
          address public owner;
          constructor ()
              public
          {
              owner = msg.sender;
          }
          modifier onlyOwner() {
              _assertSenderIsOwner();
              _;
          }
          function transferOwnership(address newOwner)
              public
              onlyOwner
          {
              if (newOwner == address(0)) {
                  LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError());
              } else {
                  owner = newOwner;
                  emit OwnershipTransferred(msg.sender, newOwner);
              }
          }
          function _assertSenderIsOwner()
              internal
              view
          {
              if (msg.sender != owner) {
                  LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError(
                      msg.sender,
                      owner
                  ));
              }
          }
      }
      pragma solidity ^0.5.9;
      library LibOwnableRichErrors {
          // bytes4(keccak256("OnlyOwnerError(address,address)"))
          bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
              0x1de45ad1;
          // bytes4(keccak256("TransferOwnerToZeroError()"))
          bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
              hex"e69edc3e";
          // solhint-disable func-name-mixedcase
          function OnlyOwnerError(
              address sender,
              address owner
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_OWNER_ERROR_SELECTOR,
                  sender,
                  owner
              );
          }
          function TransferOwnerToZeroError()
              internal
              pure
              returns (bytes memory)
          {
              return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract MixinConstants {
          // 100% in parts-per-million.
          uint32 constant internal PPM_DENOMINATOR = 10**6;
          bytes32 constant internal NIL_POOL_ID = 0x0000000000000000000000000000000000000000000000000000000000000000;
          address constant internal NIL_ADDRESS = 0x0000000000000000000000000000000000000000;
          uint256 constant internal MIN_TOKEN_VALUE = 10**18;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "../interfaces/IStructs.sol";
      library LibStakingRichErrors {
          enum OperatorShareErrorCodes {
              OperatorShareTooLarge,
              CanOnlyDecreaseOperatorShare
          }
          enum InitializationErrorCodes {
              MixinSchedulerAlreadyInitialized,
              MixinParamsAlreadyInitialized
          }
          enum InvalidParamValueErrorCodes {
              InvalidCobbDouglasAlpha,
              InvalidRewardDelegatedStakeWeight,
              InvalidMaximumMakersInPool,
              InvalidMinimumPoolStake,
              InvalidEpochDuration
          }
          enum ExchangeManagerErrorCodes {
              ExchangeAlreadyRegistered,
              ExchangeNotRegistered
          }
          // bytes4(keccak256("OnlyCallableByExchangeError(address)"))
          bytes4 internal constant ONLY_CALLABLE_BY_EXCHANGE_ERROR_SELECTOR =
              0xb56d2df0;
          // bytes4(keccak256("ExchangeManagerError(uint8,address)"))
          bytes4 internal constant EXCHANGE_MANAGER_ERROR_SELECTOR =
              0xb9588e43;
          // bytes4(keccak256("InsufficientBalanceError(uint256,uint256)"))
          bytes4 internal constant INSUFFICIENT_BALANCE_ERROR_SELECTOR =
              0x84c8b7c9;
          // bytes4(keccak256("OnlyCallableByPoolOperatorError(address,bytes32)"))
          bytes4 internal constant ONLY_CALLABLE_BY_POOL_OPERATOR_ERROR_SELECTOR =
              0x82ded785;
          // bytes4(keccak256("BlockTimestampTooLowError(uint256,uint256)"))
          bytes4 internal constant BLOCK_TIMESTAMP_TOO_LOW_ERROR_SELECTOR =
              0xa6bcde47;
          // bytes4(keccak256("OnlyCallableByStakingContractError(address)"))
          bytes4 internal constant ONLY_CALLABLE_BY_STAKING_CONTRACT_ERROR_SELECTOR =
              0xca1d07a2;
          // bytes4(keccak256("OnlyCallableIfInCatastrophicFailureError()"))
          bytes internal constant ONLY_CALLABLE_IF_IN_CATASTROPHIC_FAILURE_ERROR =
              hex"3ef081cc";
          // bytes4(keccak256("OnlyCallableIfNotInCatastrophicFailureError()"))
          bytes internal constant ONLY_CALLABLE_IF_NOT_IN_CATASTROPHIC_FAILURE_ERROR =
              hex"7dd020ce";
          // bytes4(keccak256("OperatorShareError(uint8,bytes32,uint32)"))
          bytes4 internal constant OPERATOR_SHARE_ERROR_SELECTOR =
              0x22df9597;
          // bytes4(keccak256("PoolExistenceError(bytes32,bool)"))
          bytes4 internal constant POOL_EXISTENCE_ERROR_SELECTOR =
              0x9ae94f01;
          // bytes4(keccak256("ProxyDestinationCannotBeNilError()"))
          bytes internal constant PROXY_DESTINATION_CANNOT_BE_NIL_ERROR =
              hex"6eff8285";
          // bytes4(keccak256("InitializationError(uint8)"))
          bytes4 internal constant INITIALIZATION_ERROR_SELECTOR =
              0x0b02d773;
          // bytes4(keccak256("InvalidParamValueError(uint8)"))
          bytes4 internal constant INVALID_PARAM_VALUE_ERROR_SELECTOR =
              0xfc45bd11;
          // bytes4(keccak256("InvalidProtocolFeePaymentError(uint256,uint256)"))
          bytes4 internal constant INVALID_PROTOCOL_FEE_PAYMENT_ERROR_SELECTOR =
              0x31d7a505;
          // bytes4(keccak256("PreviousEpochNotFinalizedError(uint256,uint256)"))
          bytes4 internal constant PREVIOUS_EPOCH_NOT_FINALIZED_ERROR_SELECTOR =
              0x614b800a;
          // bytes4(keccak256("PoolNotFinalizedError(bytes32,uint256)"))
          bytes4 internal constant POOL_NOT_FINALIZED_ERROR_SELECTOR =
              0x5caa0b05;
          // solhint-disable func-name-mixedcase
          function OnlyCallableByExchangeError(
              address senderAddress
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_CALLABLE_BY_EXCHANGE_ERROR_SELECTOR,
                  senderAddress
              );
          }
          function ExchangeManagerError(
              ExchangeManagerErrorCodes errorCodes,
              address exchangeAddress
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  EXCHANGE_MANAGER_ERROR_SELECTOR,
                  errorCodes,
                  exchangeAddress
              );
          }
          function InsufficientBalanceError(
              uint256 amount,
              uint256 balance
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INSUFFICIENT_BALANCE_ERROR_SELECTOR,
                  amount,
                  balance
              );
          }
          function OnlyCallableByPoolOperatorError(
              address senderAddress,
              bytes32 poolId
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_CALLABLE_BY_POOL_OPERATOR_ERROR_SELECTOR,
                  senderAddress,
                  poolId
              );
          }
          function BlockTimestampTooLowError(
              uint256 epochEndTime,
              uint256 currentBlockTimestamp
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  BLOCK_TIMESTAMP_TOO_LOW_ERROR_SELECTOR,
                  epochEndTime,
                  currentBlockTimestamp
              );
          }
          function OnlyCallableByStakingContractError(
              address senderAddress
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_CALLABLE_BY_STAKING_CONTRACT_ERROR_SELECTOR,
                  senderAddress
              );
          }
          function OnlyCallableIfInCatastrophicFailureError()
              internal
              pure
              returns (bytes memory)
          {
              return ONLY_CALLABLE_IF_IN_CATASTROPHIC_FAILURE_ERROR;
          }
          function OnlyCallableIfNotInCatastrophicFailureError()
              internal
              pure
              returns (bytes memory)
          {
              return ONLY_CALLABLE_IF_NOT_IN_CATASTROPHIC_FAILURE_ERROR;
          }
          function OperatorShareError(
              OperatorShareErrorCodes errorCodes,
              bytes32 poolId,
              uint32 operatorShare
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  OPERATOR_SHARE_ERROR_SELECTOR,
                  errorCodes,
                  poolId,
                  operatorShare
              );
          }
          function PoolExistenceError(
              bytes32 poolId,
              bool alreadyExists
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  POOL_EXISTENCE_ERROR_SELECTOR,
                  poolId,
                  alreadyExists
              );
          }
          function InvalidProtocolFeePaymentError(
              uint256 expectedProtocolFeePaid,
              uint256 actualProtocolFeePaid
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INVALID_PROTOCOL_FEE_PAYMENT_ERROR_SELECTOR,
                  expectedProtocolFeePaid,
                  actualProtocolFeePaid
              );
          }
          function InitializationError(InitializationErrorCodes code)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INITIALIZATION_ERROR_SELECTOR,
                  uint8(code)
              );
          }
          function InvalidParamValueError(InvalidParamValueErrorCodes code)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INVALID_PARAM_VALUE_ERROR_SELECTOR,
                  uint8(code)
              );
          }
          function ProxyDestinationCannotBeNilError()
              internal
              pure
              returns (bytes memory)
          {
              return PROXY_DESTINATION_CANNOT_BE_NIL_ERROR;
          }
          function PreviousEpochNotFinalizedError(
              uint256 unfinalizedEpoch,
              uint256 unfinalizedPoolsRemaining
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  PREVIOUS_EPOCH_NOT_FINALIZED_ERROR_SELECTOR,
                  unfinalizedEpoch,
                  unfinalizedPoolsRemaining
              );
          }
          function PoolNotFinalizedError(
              bytes32 poolId,
              uint256 epoch
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  POOL_NOT_FINALIZED_ERROR_SELECTOR,
                  poolId,
                  epoch
              );
          }
      }
      pragma solidity ^0.5.9;
      interface IStakingEvents {
          /// @dev Emitted by MixinStake when ZRX is staked.
          /// @param staker of ZRX.
          /// @param amount of ZRX staked.
          event Stake(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted by MixinStake when ZRX is unstaked.
          /// @param staker of ZRX.
          /// @param amount of ZRX unstaked.
          event Unstake(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted by MixinStake when ZRX is unstaked.
          /// @param staker of ZRX.
          /// @param amount of ZRX unstaked.
          event MoveStake(
              address indexed staker,
              uint256 amount,
              uint8 fromStatus,
              bytes32 indexed fromPool,
              uint8 toStatus,
              bytes32 indexed toPool
          );
          /// @dev Emitted by MixinExchangeManager when an exchange is added.
          /// @param exchangeAddress Address of new exchange.
          event ExchangeAdded(
              address exchangeAddress
          );
          /// @dev Emitted by MixinExchangeManager when an exchange is removed.
          /// @param exchangeAddress Address of removed exchange.
          event ExchangeRemoved(
              address exchangeAddress
          );
          /// @dev Emitted by MixinExchangeFees when a pool starts earning rewards in an epoch.
          /// @param epoch The epoch in which the pool earned rewards.
          /// @param poolId The ID of the pool.
          event StakingPoolEarnedRewardsInEpoch(
              uint256 indexed epoch,
              bytes32 indexed poolId
          );
          /// @dev Emitted by MixinFinalizer when an epoch has ended.
          /// @param epoch The epoch that ended.
          /// @param numPoolsToFinalize Number of pools that earned rewards during `epoch` and must be finalized.
          /// @param rewardsAvailable Rewards available to all pools that earned rewards during `epoch`.
          /// @param totalWeightedStake Total weighted stake across all pools that earned rewards during `epoch`.
          /// @param totalFeesCollected Total fees collected across all pools that earned rewards during `epoch`.
          event EpochEnded(
              uint256 indexed epoch,
              uint256 numPoolsToFinalize,
              uint256 rewardsAvailable,
              uint256 totalFeesCollected,
              uint256 totalWeightedStake
          );
          /// @dev Emitted by MixinFinalizer when an epoch is fully finalized.
          /// @param epoch The epoch being finalized.
          /// @param rewardsPaid Total amount of rewards paid out.
          /// @param rewardsRemaining Rewards left over.
          event EpochFinalized(
              uint256 indexed epoch,
              uint256 rewardsPaid,
              uint256 rewardsRemaining
          );
          /// @dev Emitted by MixinFinalizer when rewards are paid out to a pool.
          /// @param epoch The epoch when the rewards were earned.
          /// @param poolId The pool's ID.
          /// @param operatorReward Amount of reward paid to pool operator.
          /// @param membersReward Amount of reward paid to pool members.
          event RewardsPaid(
              uint256 indexed epoch,
              bytes32 indexed poolId,
              uint256 operatorReward,
              uint256 membersReward
          );
          /// @dev Emitted whenever staking parameters are changed via the `setParams()` function.
          /// @param epochDurationInSeconds Minimum seconds between epochs.
          /// @param rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          event ParamsSet(
              uint256 epochDurationInSeconds,
              uint32 rewardDelegatedStakeWeight,
              uint256 minimumPoolStake,
              uint256 cobbDouglasAlphaNumerator,
              uint256 cobbDouglasAlphaDenominator
          );
          /// @dev Emitted by MixinStakingPool when a new pool is created.
          /// @param poolId Unique id generated for pool.
          /// @param operator The operator (creator) of pool.
          /// @param operatorShare The share of rewards given to the operator, in ppm.
          event StakingPoolCreated(
              bytes32 poolId,
              address operator,
              uint32 operatorShare
          );
          /// @dev Emitted by MixinStakingPool when a maker sets their pool.
          /// @param makerAddress Adress of maker added to pool.
          /// @param poolId Unique id of pool.
          event MakerStakingPoolSet(
              address indexed makerAddress,
              bytes32 indexed poolId
          );
          /// @dev Emitted when a staking pool's operator share is decreased.
          /// @param poolId Unique Id of pool.
          /// @param oldOperatorShare Previous share of rewards owned by operator.
          /// @param newOperatorShare Newly decreased share of rewards owned by operator.
          event OperatorShareDecreased(
              bytes32 indexed poolId,
              uint32 oldOperatorShare,
              uint32 newOperatorShare
          );
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./IStructs.sol";
      contract IStakingProxy {
          /// @dev Emitted by StakingProxy when a staking contract is attached.
          /// @param newStakingContractAddress Address of newly attached staking contract.
          event StakingContractAttachedToProxy(
              address newStakingContractAddress
          );
          /// @dev Emitted by StakingProxy when a staking contract is detached.
          event StakingContractDetachedFromProxy();
          /// @dev Attach a staking contract; future calls will be delegated to the staking contract.
          /// Note that this is callable only by an authorized address.
          /// @param _stakingContract Address of staking contract.
          function attachStakingContract(address _stakingContract)
              external;
          /// @dev Detach the current staking contract.
          /// Note that this is callable only by an authorized address.
          function detachStakingContract()
              external;
          /// @dev Asserts that an epoch is between 5 and 30 days long.
          //       Asserts that 0 < cobb douglas alpha value <= 1.
          //       Asserts that a stake weight is <= 100%.
          //       Asserts that pools allow >= 1 maker.
          //       Asserts that all addresses are initialized.
          function assertValidStorageParams()
              external
              view;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../staking_pools/MixinStakingPool.sol";
      import "../libs/LibStakingRichErrors.sol";
      contract MixinStake is
          MixinStakingPool
      {
          using LibSafeMath for uint256;
          /// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
          ///      Unstake to retrieve the ZRX. Stake is in the 'Active' status.
          /// @param amount of ZRX to stake.
          function stake(uint256 amount)
              external
          {
              address staker = msg.sender;
              // deposit equivalent amount of ZRX into vault
              getZrxVault().depositFrom(staker, amount);
              // mint stake
              _increaseCurrentAndNextBalance(
                  _ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker],
                  amount
              );
              // notify
              emit Stake(
                  staker,
                  amount
              );
          }
          /// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
          ///      the staker. Stake must be in the 'undelegated' status in both the
          ///      current and next epoch in order to be unstaked.
          /// @param amount of ZRX to unstake.
          function unstake(uint256 amount)
              external
          {
              address staker = msg.sender;
              IStructs.StoredBalance memory undelegatedBalance =
                  _loadCurrentBalance(_ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker]);
              // stake must be undelegated in current and next epoch to be withdrawn
              uint256 currentWithdrawableStake = LibSafeMath.min256(
                  undelegatedBalance.currentEpochBalance,
                  undelegatedBalance.nextEpochBalance
              );
              if (amount > currentWithdrawableStake) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InsufficientBalanceError(
                          amount,
                          currentWithdrawableStake
                      )
                  );
              }
              // burn undelegated stake
              _decreaseCurrentAndNextBalance(
                  _ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker],
                  amount
              );
              // withdraw equivalent amount of ZRX from vault
              getZrxVault().withdrawFrom(staker, amount);
              // emit stake event
              emit Unstake(
                  staker,
                  amount
              );
          }
          /// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
          ///      Delegated stake can also be moved between pools.
          ///      This change comes into effect next epoch.
          /// @param from status to move stake out of.
          /// @param to status to move stake into.
          /// @param amount of stake to move.
          function moveStake(
              IStructs.StakeInfo calldata from,
              IStructs.StakeInfo calldata to,
              uint256 amount
          )
              external
          {
              address staker = msg.sender;
              // Sanity check: no-op if no stake is being moved.
              if (amount == 0) {
                  return;
              }
              // Sanity check: no-op if moving stake from undelegated to undelegated.
              if (from.status == IStructs.StakeStatus.UNDELEGATED &&
                  to.status == IStructs.StakeStatus.UNDELEGATED) {
                  return;
              }
              // handle delegation
              if (from.status == IStructs.StakeStatus.DELEGATED) {
                  _undelegateStake(
                      from.poolId,
                      staker,
                      amount
                  );
              }
              if (to.status == IStructs.StakeStatus.DELEGATED) {
                  _delegateStake(
                      to.poolId,
                      staker,
                      amount
                  );
              }
              // execute move
              IStructs.StoredBalance storage fromPtr = _ownerStakeByStatus[uint8(from.status)][staker];
              IStructs.StoredBalance storage toPtr = _ownerStakeByStatus[uint8(to.status)][staker];
              _moveStake(
                  fromPtr,
                  toPtr,
                  amount
              );
              // notify
              emit MoveStake(
                  staker,
                  amount,
                  uint8(from.status),
                  from.poolId,
                  uint8(to.status),
                  to.poolId
              );
          }
          /// @dev Delegates a owners stake to a staking pool.
          /// @param poolId Id of pool to delegate to.
          /// @param staker Owner who wants to delegate.
          /// @param amount Amount of stake to delegate.
          function _delegateStake(
              bytes32 poolId,
              address staker,
              uint256 amount
          )
              private
          {
              // Sanity check the pool we're delegating to exists.
              _assertStakingPoolExists(poolId);
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  staker
              );
              // Increase how much stake the staker has delegated to the input pool.
              _increaseNextBalance(
                  _delegatedStakeToPoolByOwner[staker][poolId],
                  amount
              );
              // Increase how much stake has been delegated to pool.
              _increaseNextBalance(
                  _delegatedStakeByPoolId[poolId],
                  amount
              );
              // Increase next balance of global delegated stake.
              _increaseNextBalance(
                  _globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)],
                  amount
              );
          }
          /// @dev Un-Delegates a owners stake from a staking pool.
          /// @param poolId Id of pool to un-delegate from.
          /// @param staker Owner who wants to un-delegate.
          /// @param amount Amount of stake to un-delegate.
          function _undelegateStake(
              bytes32 poolId,
              address staker,
              uint256 amount
          )
              private
          {
              // sanity check the pool we're undelegating from exists
              _assertStakingPoolExists(poolId);
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  staker
              );
              // Decrease how much stake the staker has delegated to the input pool.
              _decreaseNextBalance(
                  _delegatedStakeToPoolByOwner[staker][poolId],
                  amount
              );
              // Decrease how much stake has been delegated to pool.
              _decreaseNextBalance(
                  _delegatedStakeByPoolId[poolId],
                  amount
              );
              // Decrease next balance of global delegated stake (aggregated across all stakers).
              _decreaseNextBalance(
                  _globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)],
                  amount
              );
          }
      }
      pragma solidity ^0.5.9;
      import "./LibRichErrors.sol";
      import "./LibSafeMathRichErrors.sol";
      library LibSafeMath {
          function safeMul(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              if (a == 0) {
                  return 0;
              }
              uint256 c = a * b;
              if (c / a != b) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
                      a,
                      b
                  ));
              }
              return c;
          }
          function safeDiv(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              if (b == 0) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
                      a,
                      b
                  ));
              }
              uint256 c = a / b;
              return c;
          }
          function safeSub(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              if (b > a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
                      a,
                      b
                  ));
              }
              return a - b;
          }
          function safeAdd(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              uint256 c = a + b;
              if (c < a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
                      a,
                      b
                  ));
              }
              return c;
          }
          function max256(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              return a >= b ? a : b;
          }
          function min256(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              return a < b ? a : b;
          }
      }
      pragma solidity ^0.5.9;
      library LibSafeMathRichErrors {
          // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
          bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
              0xe946c1bb;
          // bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
          bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
              0xc996af7b;
          enum BinOpErrorCodes {
              ADDITION_OVERFLOW,
              MULTIPLICATION_OVERFLOW,
              SUBTRACTION_UNDERFLOW,
              DIVISION_BY_ZERO
          }
          enum DowncastErrorCodes {
              VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
              VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
              VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
          }
          // solhint-disable func-name-mixedcase
          function Uint256BinOpError(
              BinOpErrorCodes errorCode,
              uint256 a,
              uint256 b
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  UINT256_BINOP_ERROR_SELECTOR,
                  errorCode,
                  a,
                  b
              );
          }
          function Uint256DowncastError(
              DowncastErrorCodes errorCode,
              uint256 a
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  UINT256_DOWNCAST_ERROR_SELECTOR,
                  errorCode,
                  a
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStructs.sol";
      import "../sys/MixinAbstract.sol";
      import "./MixinStakingPoolRewards.sol";
      contract MixinStakingPool is
          MixinAbstract,
          MixinStakingPoolRewards
      {
          using LibSafeMath for uint256;
          using LibSafeDowncast for uint256;
          /// @dev Asserts that the sender is the operator of the input pool.
          /// @param poolId Pool sender must be operator of.
          modifier onlyStakingPoolOperator(bytes32 poolId) {
              _assertSenderIsPoolOperator(poolId);
              _;
          }
          /// @dev Create a new staking pool. The sender will be the operator of this pool.
          /// Note that an operator must be payable.
          /// @param operatorShare Portion of rewards owned by the operator, in ppm.
          /// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true.
          /// @return poolId The unique pool id generated for this pool.
          function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker)
              external
              returns (bytes32 poolId)
          {
              // note that an operator must be payable
              address operator = msg.sender;
              // compute unique id for this pool
              poolId = lastPoolId = bytes32(uint256(lastPoolId).safeAdd(1));
              // sanity check on operator share
              _assertNewOperatorShare(
                  poolId,
                  PPM_DENOMINATOR,    // max operator share
                  operatorShare
              );
              // create and store pool
              IStructs.Pool memory pool = IStructs.Pool({
                  operator: operator,
                  operatorShare: operatorShare
              });
              _poolById[poolId] = pool;
              // Staking pool has been created
              emit StakingPoolCreated(poolId, operator, operatorShare);
              if (addOperatorAsMaker) {
                  joinStakingPoolAsMaker(poolId);
              }
              return poolId;
          }
          /// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
          /// @param poolId Unique Id of pool.
          /// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
          function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
              external
              onlyStakingPoolOperator(poolId)
          {
              // load pool and assert that we can decrease
              uint32 currentOperatorShare = _poolById[poolId].operatorShare;
              _assertNewOperatorShare(
                  poolId,
                  currentOperatorShare,
                  newOperatorShare
              );
              // decrease operator share
              _poolById[poolId].operatorShare = newOperatorShare;
              emit OperatorShareDecreased(
                  poolId,
                  currentOperatorShare,
                  newOperatorShare
              );
          }
          /// @dev Allows caller to join a staking pool as a maker.
          /// @param poolId Unique id of pool.
          function joinStakingPoolAsMaker(bytes32 poolId)
              public
          {
              address maker = msg.sender;
              poolIdByMaker[maker] = poolId;
              emit MakerStakingPoolSet(
                  maker,
                  poolId
              );
          }
          /// @dev Returns a staking pool
          /// @param poolId Unique id of pool.
          function getStakingPool(bytes32 poolId)
              public
              view
              returns (IStructs.Pool memory)
          {
              return _poolById[poolId];
          }
          /// @dev Reverts iff a staking pool does not exist.
          /// @param poolId Unique id of pool.
          function _assertStakingPoolExists(bytes32 poolId)
              internal
              view
          {
              if (_poolById[poolId].operator == NIL_ADDRESS) {
                  // we use the pool's operator as a proxy for its existence
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.PoolExistenceError(
                          poolId,
                          false
                      )
                  );
              }
          }
          /// @dev Reverts iff the new operator share is invalid.
          /// @param poolId Unique id of pool.
          /// @param currentOperatorShare Current operator share.
          /// @param newOperatorShare New operator share.
          function _assertNewOperatorShare(
              bytes32 poolId,
              uint32 currentOperatorShare,
              uint32 newOperatorShare
          )
              private
              pure
          {
              // sanity checks
              if (newOperatorShare > PPM_DENOMINATOR) {
                  // operator share must be a valid fraction
                  LibRichErrors.rrevert(LibStakingRichErrors.OperatorShareError(
                      LibStakingRichErrors.OperatorShareErrorCodes.OperatorShareTooLarge,
                      poolId,
                      newOperatorShare
                  ));
              } else if (newOperatorShare >= currentOperatorShare) {
                  // new share must be less than the current share
                  LibRichErrors.rrevert(LibStakingRichErrors.OperatorShareError(
                      LibStakingRichErrors.OperatorShareErrorCodes.CanOnlyDecreaseOperatorShare,
                      poolId,
                      newOperatorShare
                  ));
              }
          }
          /// @dev Asserts that the sender is the operator of the input pool.
          /// @param poolId Pool sender must be operator of.
          function _assertSenderIsPoolOperator(bytes32 poolId)
              private
              view
          {
              address operator = _poolById[poolId].operator;
              if (msg.sender != operator) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.OnlyCallableByPoolOperatorError(
                          msg.sender,
                          poolId
                      )
                  );
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      /// @dev Exposes some internal functions from various contracts to avoid
      ///      cyclical dependencies.
      contract MixinAbstract {
          /// @dev Computes the reward owed to a pool during finalization.
          ///      Does nothing if the pool is already finalized.
          /// @param poolId The pool's ID.
          /// @return totalReward The total reward owed to a pool.
          /// @return membersStake The total stake for all non-operator members in
          ///         this pool.
          function _getUnfinalizedPoolRewards(bytes32 poolId)
              internal
              view
              returns (
                  uint256 totalReward,
                  uint256 membersStake
              );
          /// @dev Asserts that a pool has been finalized last epoch.
          /// @param poolId The id of the pool that should have been finalized.
          function _assertPoolFinalizedLastEpoch(bytes32 poolId)
              internal
              view;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "./MixinCumulativeRewards.sol";
      import "../sys/MixinAbstract.sol";
      contract MixinStakingPoolRewards is
          MixinAbstract,
          MixinCumulativeRewards
      {
          using LibSafeMath for uint256;
          /// @dev Withdraws the caller's WETH rewards that have accumulated
          ///      until the last epoch.
          /// @param poolId Unique id of pool.
          function withdrawDelegatorRewards(bytes32 poolId)
              external
          {
              _withdrawAndSyncDelegatorRewards(poolId, msg.sender);
          }
          /// @dev Computes the reward balance in ETH of the operator of a pool.
          /// @param poolId Unique id of pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfOperator(bytes32 poolId)
              external
              view
              returns (uint256 reward)
          {
              // Because operator rewards are immediately withdrawn as WETH
              // on finalization, the only factor in this function are unfinalized
              // rewards.
              IStructs.Pool memory pool = _poolById[poolId];
              // Get any unfinalized rewards.
              (uint256 unfinalizedTotalRewards, uint256 unfinalizedMembersStake) =
                  _getUnfinalizedPoolRewards(poolId);
              // Get the operators' portion.
              (reward,) = _computePoolRewardsSplit(
                  pool.operatorShare,
                  unfinalizedTotalRewards,
                  unfinalizedMembersStake
              );
              return reward;
          }
          /// @dev Computes the reward balance in ETH of a specific member of a pool.
          /// @param poolId Unique id of pool.
          /// @param member The member of the pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfDelegator(bytes32 poolId, address member)
              external
              view
              returns (uint256 reward)
          {
              IStructs.Pool memory pool = _poolById[poolId];
              // Get any unfinalized rewards.
              (uint256 unfinalizedTotalRewards, uint256 unfinalizedMembersStake) =
                  _getUnfinalizedPoolRewards(poolId);
              // Get the members' portion.
              (, uint256 unfinalizedMembersReward) = _computePoolRewardsSplit(
                  pool.operatorShare,
                  unfinalizedTotalRewards,
                  unfinalizedMembersStake
              );
              return _computeDelegatorReward(
                  poolId,
                  member,
                  unfinalizedMembersReward,
                  unfinalizedMembersStake
              );
          }
          /// @dev Syncs rewards for a delegator. This includes withdrawing rewards
          ///      rewards and adding/removing dependencies on cumulative rewards.
          /// @param poolId Unique id of pool.
          /// @param member of the pool.
          function _withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              internal
          {
              // Ensure the pool is finalized.
              _assertPoolFinalizedLastEpoch(poolId);
              // Compute balance owed to delegator
              uint256 balance = _computeDelegatorReward(
                  poolId,
                  member,
                  // No unfinalized values because we ensured the pool is already
                  // finalized.
                  0,
                  0
              );
              // Sync the delegated stake balance. This will ensure future calls of
              // `_computeDelegatorReward` during this epoch will return 0, 
              // preventing a delegator from withdrawing more than once an epoch.
              _delegatedStakeToPoolByOwner[member][poolId] =
                  _loadCurrentBalance(_delegatedStakeToPoolByOwner[member][poolId]);
              // Withdraw non-0 balance
              if (balance != 0) {
                  // Decrease the balance of the pool
                  _decreasePoolRewards(poolId, balance);
                  // Withdraw the member's WETH balance
                  getWethContract().transfer(member, balance);
              }
              // Ensure a cumulative reward entry exists for this epoch,
              // copying the previous epoch's CR if one doesn't exist already.
              _updateCumulativeReward(poolId);
          }
          /// @dev Handles a pool's reward at the current epoch.
          ///      This will split the reward between the operator and members,
          ///      depositing them into their respective vaults, and update the
          ///      accounting needed to allow members to withdraw their individual
          ///      rewards.
          /// @param poolId Unique Id of pool.
          /// @param reward received by the pool.
          /// @param membersStake the amount of non-operator delegated stake that
          ///        will split the  reward.
          /// @return operatorReward Portion of `reward` given to the pool operator.
          /// @return membersReward Portion of `reward` given to the pool members.
          function _syncPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              internal
              returns (uint256 operatorReward, uint256 membersReward)
          {
              IStructs.Pool memory pool = _poolById[poolId];
              // Split the reward between operator and members
              (operatorReward, membersReward) = _computePoolRewardsSplit(
                  pool.operatorShare,
                  reward,
                  membersStake
              );
              if (operatorReward > 0) {
                  // Transfer the operator's weth reward to the operator
                  getWethContract().transfer(pool.operator, operatorReward);
              }
              if (membersReward > 0) {
                  // Increase the balance of the pool
                  _increasePoolRewards(poolId, membersReward);
                  // Create a cumulative reward entry at the current epoch.
                  _addCumulativeReward(poolId, membersReward, membersStake);
              }
              return (operatorReward, membersReward);
          }
          /// @dev Compute the split of a pool reward between the operator and members
          ///      based on the `operatorShare` and `membersStake`.
          /// @param operatorShare The fraction of rewards owed to the operator,
          ///        in PPM.
          /// @param totalReward The pool reward.
          /// @param membersStake The amount of member (non-operator) stake delegated
          ///        to the pool in the epoch the rewards were earned.
          /// @return operatorReward Portion of `totalReward` given to the pool operator.
          /// @return membersReward Portion of `totalReward` given to the pool members.
          function _computePoolRewardsSplit(
              uint32 operatorShare,
              uint256 totalReward,
              uint256 membersStake
          )
              internal
              pure
              returns (uint256 operatorReward, uint256 membersReward)
          {
              if (membersStake == 0) {
                  operatorReward = totalReward;
              } else {
                  operatorReward = LibMath.getPartialAmountCeil(
                      uint256(operatorShare),
                      PPM_DENOMINATOR,
                      totalReward
                  );
                  membersReward = totalReward.safeSub(operatorReward);
              }
              return (operatorReward, membersReward);
          }
          /// @dev Computes the reward balance in ETH of a specific member of a pool.
          /// @param poolId Unique id of pool.
          /// @param member of the pool.
          /// @param unfinalizedMembersReward Unfinalized total members reward (if any).
          /// @param unfinalizedMembersStake Unfinalized total members stake (if any).
          /// @return reward Balance in WETH.
          function _computeDelegatorReward(
              bytes32 poolId,
              address member,
              uint256 unfinalizedMembersReward,
              uint256 unfinalizedMembersStake
          )
              private
              view
              returns (uint256 reward)
          {
              uint256 currentEpoch_ = currentEpoch;
              IStructs.StoredBalance memory delegatedStake = _delegatedStakeToPoolByOwner[member][poolId];
              // There can be no rewards if the last epoch when stake was stored is
              // equal to the current epoch, because all prior rewards, including
              // rewards finalized this epoch have been claimed.
              if (delegatedStake.currentEpoch == currentEpoch_) {
                  return 0;
              }
              // We account for rewards over 3 intervals, below.
              // 1/3 Unfinalized rewards earned in `currentEpoch - 1`.
              reward = _computeUnfinalizedDelegatorReward(
                  delegatedStake,
                  currentEpoch_,
                  unfinalizedMembersReward,
                  unfinalizedMembersStake
              );
              // 2/3 Finalized rewards earned in epochs [`delegatedStake.currentEpoch + 1` .. `currentEpoch - 1`]
              uint256 delegatedStakeNextEpoch = uint256(delegatedStake.currentEpoch).safeAdd(1);
              reward = reward.safeAdd(
                  _computeMemberRewardOverInterval(
                      poolId,
                      delegatedStake.currentEpochBalance,
                      delegatedStake.currentEpoch,
                      delegatedStakeNextEpoch
                  )
              );
              // 3/3 Finalized rewards earned in epoch `delegatedStake.currentEpoch`.
              reward = reward.safeAdd(
                  _computeMemberRewardOverInterval(
                      poolId,
                      delegatedStake.nextEpochBalance,
                      delegatedStakeNextEpoch,
                      currentEpoch_
                  )
              );
              return reward;
          }
          /// @dev Computes the unfinalized rewards earned by a delegator in the last epoch.
          /// @param delegatedStake Amount of stake delegated to pool by a specific staker
          /// @param currentEpoch_ The epoch in which this call is executing
          /// @param unfinalizedMembersReward Unfinalized total members reward (if any).
          /// @param unfinalizedMembersStake Unfinalized total members stake (if any).
          /// @return reward Balance in WETH.
          function _computeUnfinalizedDelegatorReward(
              IStructs.StoredBalance memory delegatedStake,
              uint256 currentEpoch_,
              uint256 unfinalizedMembersReward,
              uint256 unfinalizedMembersStake
          )
              private
              pure
              returns (uint256)
          {
              // If there are unfinalized rewards this epoch, compute the member's
              // share.
              if (unfinalizedMembersReward == 0 || unfinalizedMembersStake == 0) {
                  return 0;
              }
              // Unfinalized rewards are always earned from stake in
              // the prior epoch so we want the stake at `currentEpoch_-1`.
              uint256 unfinalizedStakeBalance = delegatedStake.currentEpoch >= currentEpoch_.safeSub(1) ?
                  delegatedStake.currentEpochBalance :
                  delegatedStake.nextEpochBalance;
              // Sanity check to save gas on computation
              if (unfinalizedStakeBalance == 0) {
                  return 0;
              }
              // Compute unfinalized reward
              return LibMath.getPartialAmountFloor(
                  unfinalizedMembersReward,
                  unfinalizedMembersStake,
                  unfinalizedStakeBalance
              );
          }
          /// @dev Increases rewards for a pool.
          /// @param poolId Unique id of pool.
          /// @param amount Amount to increment rewards by.
          function _increasePoolRewards(bytes32 poolId, uint256 amount)
              private
          {
              rewardsByPoolId[poolId] = rewardsByPoolId[poolId].safeAdd(amount);
              wethReservedForPoolRewards = wethReservedForPoolRewards.safeAdd(amount);
          }
          /// @dev Decreases rewards for a pool.
          /// @param poolId Unique id of pool.
          /// @param amount Amount to decrement rewards by.
          function _decreasePoolRewards(bytes32 poolId, uint256 amount)
              private
          {
              rewardsByPoolId[poolId] = rewardsByPoolId[poolId].safeSub(amount);
              wethReservedForPoolRewards = wethReservedForPoolRewards.safeSub(amount);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "./LibMathRichErrors.sol";
      library LibMath {
          using LibSafeMath for uint256;
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          ///      Reverts if rounding error is >= 0.1%
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded down.
          function safeGetPartialAmountFloor(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              if (isRoundingErrorFloor(
                      numerator,
                      denominator,
                      target
              )) {
                  LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
                      numerator,
                      denominator,
                      target
                  ));
              }
              partialAmount = numerator.safeMul(target).safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          ///      Reverts if rounding error is >= 0.1%
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded up.
          function safeGetPartialAmountCeil(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              if (isRoundingErrorCeil(
                      numerator,
                      denominator,
                      target
              )) {
                  LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
                      numerator,
                      denominator,
                      target
                  ));
              }
              // safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
              //       ceil(a / b) = floor((a + b - 1) / b)
              // To implement `ceil(a / b)` using safeDiv.
              partialAmount = numerator.safeMul(target)
                  .safeAdd(denominator.safeSub(1))
                  .safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded down.
          function getPartialAmountFloor(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              partialAmount = numerator.safeMul(target).safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded up.
          function getPartialAmountCeil(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              // safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
              //       ceil(a / b) = floor((a + b - 1) / b)
              // To implement `ceil(a / b)` using safeDiv.
              partialAmount = numerator.safeMul(target)
                  .safeAdd(denominator.safeSub(1))
                  .safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Checks if rounding error >= 0.1% when rounding down.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to multiply with numerator/denominator.
          /// @return Rounding error is present.
          function isRoundingErrorFloor(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (bool isError)
          {
              if (denominator == 0) {
                  LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
              }
              // The absolute rounding error is the difference between the rounded
              // value and the ideal value. The relative rounding error is the
              // absolute rounding error divided by the absolute value of the
              // ideal value. This is undefined when the ideal value is zero.
              //
              // The ideal value is `numerator * target / denominator`.
              // Let's call `numerator * target % denominator` the remainder.
              // The absolute error is `remainder / denominator`.
              //
              // When the ideal value is zero, we require the absolute error to
              // be zero. Fortunately, this is always the case. The ideal value is
              // zero iff `numerator == 0` and/or `target == 0`. In this case the
              // remainder and absolute error are also zero.
              if (target == 0 || numerator == 0) {
                  return false;
              }
              // Otherwise, we want the relative rounding error to be strictly
              // less than 0.1%.
              // The relative error is `remainder / (numerator * target)`.
              // We want the relative error less than 1 / 1000:
              //        remainder / (numerator * denominator)  <  1 / 1000
              // or equivalently:
              //        1000 * remainder  <  numerator * target
              // so we have a rounding error iff:
              //        1000 * remainder  >=  numerator * target
              uint256 remainder = mulmod(
                  target,
                  numerator,
                  denominator
              );
              isError = remainder.safeMul(1000) >= numerator.safeMul(target);
              return isError;
          }
          /// @dev Checks if rounding error >= 0.1% when rounding up.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to multiply with numerator/denominator.
          /// @return Rounding error is present.
          function isRoundingErrorCeil(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (bool isError)
          {
              if (denominator == 0) {
                  LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
              }
              // See the comments in `isRoundingError`.
              if (target == 0 || numerator == 0) {
                  // When either is zero, the ideal value and rounded value are zero
                  // and there is no rounding error. (Although the relative error
                  // is undefined.)
                  return false;
              }
              // Compute remainder as before
              uint256 remainder = mulmod(
                  target,
                  numerator,
                  denominator
              );
              remainder = denominator.safeSub(remainder) % denominator;
              isError = remainder.safeMul(1000) >= numerator.safeMul(target);
              return isError;
          }
      }
      pragma solidity ^0.5.9;
      library LibMathRichErrors {
          // bytes4(keccak256("DivisionByZeroError()"))
          bytes internal constant DIVISION_BY_ZERO_ERROR =
              hex"a791837c";
          // bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
          bytes4 internal constant ROUNDING_ERROR_SELECTOR =
              0x339f3de2;
          // solhint-disable func-name-mixedcase
          function DivisionByZeroError()
              internal
              pure
              returns (bytes memory)
          {
              return DIVISION_BY_ZERO_ERROR;
          }
          function RoundingError(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ROUNDING_ERROR_SELECTOR,
                  numerator,
                  denominator,
                  target
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibFractions.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../stake/MixinStakeBalances.sol";
      import "../immutable/MixinConstants.sol";
      contract MixinCumulativeRewards is
          MixinStakeBalances,
          MixinConstants
      {
          using LibSafeMath for uint256;
          /// @dev returns true iff Cumulative Rewards are set
          function _isCumulativeRewardSet(IStructs.Fraction memory cumulativeReward)
              internal
              pure
              returns (bool)
          {
              // We use the denominator as a proxy for whether the cumulative
              // reward is set, as setting the cumulative reward always sets this
              // field to at least 1.
              return cumulativeReward.denominator != 0;
          }
          /// @dev Sets a pool's cumulative delegator rewards for the current epoch,
          ///      given the rewards earned and stake from the last epoch, which will
          ///      be summed with the previous cumulative rewards for this pool.
          ///      If the last cumulative reward epoch is the current epoch, this is a
          ///      no-op.
          /// @param poolId The pool ID.
          /// @param reward The total reward earned by pool delegators from the last epoch.
          /// @param stake The total delegated stake in the pool in the last epoch.
          function _addCumulativeReward(
              bytes32 poolId,
              uint256 reward,
              uint256 stake
          )
              internal
          {
              // Fetch the last epoch at which we stored an entry for this pool;
              // this is the most up-to-date cumulative rewards for this pool.
              uint256 lastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              uint256 currentEpoch_ = currentEpoch;
              // If we already have a record for this epoch, don't overwrite it.
              if (lastStoredEpoch == currentEpoch_) {
                  return;
              }
              IStructs.Fraction memory mostRecentCumulativeReward =
                  _cumulativeRewardsByPool[poolId][lastStoredEpoch];
              // Compute new cumulative reward
              IStructs.Fraction memory cumulativeReward;
              if (_isCumulativeRewardSet(mostRecentCumulativeReward)) {
                  // If we have a prior cumulative reward entry, we sum them as fractions.
                  (cumulativeReward.numerator, cumulativeReward.denominator) = LibFractions.add(
                      mostRecentCumulativeReward.numerator,
                      mostRecentCumulativeReward.denominator,
                      reward,
                      stake
                  );
                  // Normalize to prevent overflows in future operations.
                  (cumulativeReward.numerator, cumulativeReward.denominator) = LibFractions.normalize(
                      cumulativeReward.numerator,
                      cumulativeReward.denominator
                  );
              } else {
                  (cumulativeReward.numerator, cumulativeReward.denominator) = (reward, stake);
              }
              // Store cumulative rewards for this epoch.
              _cumulativeRewardsByPool[poolId][currentEpoch_] = cumulativeReward;
              _cumulativeRewardsByPoolLastStored[poolId] = currentEpoch_;
          }
          /// @dev Sets a pool's cumulative delegator rewards for the current epoch,
          ///      using the last stored cumulative rewards. If we've already set
          ///      a CR for this epoch, this is a no-op.
          /// @param poolId The pool ID.
          function _updateCumulativeReward(bytes32 poolId)
              internal
          {
              // Just add empty rewards for this epoch, which will be added to
              // the previous CR, so we end up with the previous CR being set for
              // this epoch.
              _addCumulativeReward(poolId, 0, 1);
          }
          /// @dev Computes a member's reward over a given epoch interval.
          /// @param poolId Uniqud Id of pool.
          /// @param memberStakeOverInterval Stake delegated to pool by member over
          ///        the interval.
          /// @param beginEpoch Beginning of interval.
          /// @param endEpoch End of interval.
          /// @return rewards Reward accumulated over interval [beginEpoch, endEpoch]
          function _computeMemberRewardOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              internal
              view
              returns (uint256 reward)
          {
              // Sanity check if we can skip computation, as it will result in zero.
              if (memberStakeOverInterval == 0 || beginEpoch == endEpoch) {
                  return 0;
              }
              // Sanity check interval
              require(beginEpoch < endEpoch, "CR_INTERVAL_INVALID");
              // Sanity check begin reward
              IStructs.Fraction memory beginReward = _getCumulativeRewardAtEpoch(poolId, beginEpoch);
              IStructs.Fraction memory endReward = _getCumulativeRewardAtEpoch(poolId, endEpoch);
              // Compute reward
              reward = LibFractions.scaleDifference(
                  endReward.numerator,
                  endReward.denominator,
                  beginReward.numerator,
                  beginReward.denominator,
                  memberStakeOverInterval
              );
          }
          /// @dev Fetch the most recent cumulative reward entry for a pool.
          /// @param poolId Unique ID of pool.
          /// @return cumulativeReward The most recent cumulative reward `poolId`.
          function _getMostRecentCumulativeReward(bytes32 poolId)
              private
              view
              returns (IStructs.Fraction memory cumulativeReward)
          {
              uint256 lastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              return _cumulativeRewardsByPool[poolId][lastStoredEpoch];
          }
          /// @dev Fetch the cumulative reward for a given epoch.
          ///      If the corresponding CR does not exist in state, then we backtrack
          ///      to find its value by querying `epoch-1` and then most recent CR.
          /// @param poolId Unique ID of pool.
          /// @param epoch The epoch to find the
          /// @return cumulativeReward The cumulative reward for `poolId` at `epoch`.
          /// @return cumulativeRewardStoredAt Epoch that the `cumulativeReward` is stored at.
          function _getCumulativeRewardAtEpoch(bytes32 poolId, uint256 epoch)
              private
              view
              returns (IStructs.Fraction memory cumulativeReward)
          {
              // Return CR at `epoch`, given it's set.
              cumulativeReward = _cumulativeRewardsByPool[poolId][epoch];
              if (_isCumulativeRewardSet(cumulativeReward)) {
                  return cumulativeReward;
              }
              // Return CR at `epoch-1`, given it's set.
              uint256 lastEpoch = epoch.safeSub(1);
              cumulativeReward = _cumulativeRewardsByPool[poolId][lastEpoch];
              if (_isCumulativeRewardSet(cumulativeReward)) {
                  return cumulativeReward;
              }
              // Return the most recent CR, given it's less than `epoch`.
              uint256 mostRecentEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              if (mostRecentEpoch < epoch) {
                  cumulativeReward = _cumulativeRewardsByPool[poolId][mostRecentEpoch];
                  if (_isCumulativeRewardSet(cumulativeReward)) {
                      return cumulativeReward;
                  }
              }
              // Otherwise return an empty CR.
              return IStructs.Fraction(0, 1);
          }
      }
      pragma solidity ^0.5.9;
      import "./LibSafeMath.sol";
      library LibFractions {
          using LibSafeMath for uint256;
          /// @dev Safely adds two fractions `n1/d1 + n2/d2`
          /// @param n1 numerator of `1`
          /// @param d1 denominator of `1`
          /// @param n2 numerator of `2`
          /// @param d2 denominator of `2`
          /// @return numerator Numerator of sum
          /// @return denominator Denominator of sum
          function add(
              uint256 n1,
              uint256 d1,
              uint256 n2,
              uint256 d2
          )
              internal
              pure
              returns (
                  uint256 numerator,
                  uint256 denominator
              )
          {
              if (n1 == 0) {
                  return (numerator = n2, denominator = d2);
              }
              if (n2 == 0) {
                  return (numerator = n1, denominator = d1);
              }
              numerator = n1
                  .safeMul(d2)
                  .safeAdd(n2.safeMul(d1));
              denominator = d1.safeMul(d2);
              return (numerator, denominator);
          }
          /// @dev Rescales a fraction to prevent overflows during addition if either
          ///      the numerator or the denominator are > `maxValue`.
          /// @param numerator The numerator.
          /// @param denominator The denominator.
          /// @param maxValue The maximum value allowed for both the numerator and
          ///        denominator.
          /// @return scaledNumerator The rescaled numerator.
          /// @return scaledDenominator The rescaled denominator.
          function normalize(
              uint256 numerator,
              uint256 denominator,
              uint256 maxValue
          )
              internal
              pure
              returns (
                  uint256 scaledNumerator,
                  uint256 scaledDenominator
              )
          {
              // If either the numerator or the denominator are > `maxValue`,
              // re-scale them by `maxValue` to prevent overflows in future operations.
              if (numerator > maxValue || denominator > maxValue) {
                  uint256 rescaleBase = numerator >= denominator ? numerator : denominator;
                  rescaleBase = rescaleBase.safeDiv(maxValue);
                  scaledNumerator = numerator.safeDiv(rescaleBase);
                  scaledDenominator = denominator.safeDiv(rescaleBase);
              } else {
                  scaledNumerator = numerator;
                  scaledDenominator = denominator;
              }
              return (scaledNumerator, scaledDenominator);
          }
          /// @dev Rescales a fraction to prevent overflows during addition if either
          ///      the numerator or the denominator are > 2 ** 127.
          /// @param numerator The numerator.
          /// @param denominator The denominator.
          /// @return scaledNumerator The rescaled numerator.
          /// @return scaledDenominator The rescaled denominator.
          function normalize(
              uint256 numerator,
              uint256 denominator
          )
              internal
              pure
              returns (
                  uint256 scaledNumerator,
                  uint256 scaledDenominator
              )
          {
              return normalize(numerator, denominator, 2 ** 127);
          }
          /// @dev Safely scales the difference between two fractions.
          /// @param n1 numerator of `1`
          /// @param d1 denominator of `1`
          /// @param n2 numerator of `2`
          /// @param d2 denominator of `2`
          /// @param s scalar to multiply by difference.
          /// @return result `s * (n1/d1 - n2/d2)`.
          function scaleDifference(
              uint256 n1,
              uint256 d1,
              uint256 n2,
              uint256 d2,
              uint256 s
          )
              internal
              pure
              returns (uint256 result)
          {
              if (s == 0) {
                  return 0;
              }
              if (n2 == 0) {
                  return result = s
                      .safeMul(n1)
                      .safeDiv(d1);
              }
              uint256 numerator = n1
                  .safeMul(d2)
                  .safeSub(n2.safeMul(d1));
              uint256 tmp = numerator.safeDiv(d2);
              return s
                  .safeMul(tmp)
                  .safeDiv(d1);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../interfaces/IStructs.sol";
      import "../immutable/MixinDeploymentConstants.sol";
      import "./MixinStakeStorage.sol";
      contract MixinStakeBalances is
          MixinStakeStorage,
          MixinDeploymentConstants
      {
          using LibSafeMath for uint256;
          /// @dev Gets global stake for a given status.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Global stake for given status.
          function getGlobalStakeByStatus(IStructs.StakeStatus stakeStatus)
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(
                  _globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)]
              );
              if (stakeStatus == IStructs.StakeStatus.UNDELEGATED) {
                  // Undelegated stake is the difference between total stake and delegated stake
                  // Note that any ZRX erroneously sent to the vault will be counted as undelegated stake
                  uint256 totalStake = getZrxVault().balanceOfZrxVault();
                  balance.currentEpochBalance = totalStake.safeSub(balance.currentEpochBalance).downcastToUint96();
                  balance.nextEpochBalance = totalStake.safeSub(balance.nextEpochBalance).downcastToUint96();
              }
              return balance;
          }
          /// @dev Gets an owner's stake balances by status.
          /// @param staker Owner of stake.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Owner's stake balances for given status.
          function getOwnerStakeByStatus(
              address staker,
              IStructs.StakeStatus stakeStatus
          )
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(
                  _ownerStakeByStatus[uint8(stakeStatus)][staker]
              );
              return balance;
          }
          /// @dev Returns the total stake for a given staker.
          /// @param staker of stake.
          /// @return Total ZRX staked by `staker`.
          function getTotalStake(address staker)
              public
              view
              returns (uint256)
          {
              return getZrxVault().balanceOf(staker);
          }
          /// @dev Returns the stake delegated to a specific staking pool, by a given staker.
          /// @param staker of stake.
          /// @param poolId Unique Id of pool.
          /// @return Stake delegated to pool by staker.
          function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(_delegatedStakeToPoolByOwner[staker][poolId]);
              return balance;
          }
          /// @dev Returns the total stake delegated to a specific staking pool,
          ///      across all members.
          /// @param poolId Unique Id of pool.
          /// @return Total stake delegated to pool.
          function getTotalStakeDelegatedToPool(bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(_delegatedStakeByPoolId[poolId]);
              return balance;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
      import "../interfaces/IZrxVault.sol";
      // solhint-disable separate-by-one-line-in-contract
      contract MixinDeploymentConstants {
          // @TODO SET THESE VALUES FOR DEPLOYMENT
          // Mainnet WETH9 Address
          address constant private WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
          // Kovan WETH9 Address
          // address constant private WETH_ADDRESS = address(0xd0A1E359811322d97991E03f863a0C30C2cF029C);
          // Ropsten & Rinkeby WETH9 Address
          // address constant private WETH_ADDRESS = address(0xc778417E063141139Fce010982780140Aa0cD5Ab);
          // @TODO SET THESE VALUES FOR DEPLOYMENT
          // Mainnet ZrxVault address
          address constant private ZRX_VAULT_ADDRESS = address(0xcE2a4B118813cBfa27Ee11cf8E67B101867fa85E);
          // Kovan ZrxVault address
          // address constant private ZRX_VAULT_ADDRESS = address(0xf36eabdFE986B35b62c8FD5a98A7f2aEBB79B291);
          // Ropsten ZrxVault address
          // address constant private ZRX_VAULT_ADDRESS = address(0xffD161026865Ad8B4aB28a76840474935eEc4DfA);
          // Rinkeby ZrxVault address
          // address constant private ZRX_VAULT_ADDRESS = address(0xA5Bf6aC73bC40790FC6Ffc9DBbbCE76c9176e224);
          /// @dev An overridable way to access the deployed WETH contract.
          ///      Must be view to allow overrides to access state.
          /// @return wethContract The WETH contract instance.
          function getWethContract()
              public
              view
              returns (IEtherToken wethContract)
          {
              wethContract = IEtherToken(WETH_ADDRESS);
              return wethContract;
          }
          /// @dev An overridable way to access the deployed zrxVault.
          ///      Must be view to allow overrides to access state.
          /// @return zrxVault The zrxVault contract.
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              zrxVault = IZrxVault(ZRX_VAULT_ADDRESS);
              return zrxVault;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "../libs/LibSafeDowncast.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../interfaces/IStructs.sol";
      import "../sys/MixinScheduler.sol";
      /// @dev This mixin contains logic for managing stake storage.
      contract MixinStakeStorage is
          MixinScheduler
      {
          using LibSafeMath for uint256;
          using LibSafeDowncast for uint256;
          /// @dev Moves stake between states: 'undelegated' or 'delegated'.
          ///      This change comes into effect next epoch.
          /// @param fromPtr pointer to storage location of `from` stake.
          /// @param toPtr pointer to storage location of `to` stake.
          /// @param amount of stake to move.
          function _moveStake(
              IStructs.StoredBalance storage fromPtr,
              IStructs.StoredBalance storage toPtr,
              uint256 amount
          )
              internal
          {
              // do nothing if pointers are equal
              if (_arePointersEqual(fromPtr, toPtr)) {
                  return;
              }
              // load current balances from storage
              IStructs.StoredBalance memory from = _loadCurrentBalance(fromPtr);
              IStructs.StoredBalance memory to = _loadCurrentBalance(toPtr);
              // sanity check on balance
              if (amount > from.nextEpochBalance) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InsufficientBalanceError(
                          amount,
                          from.nextEpochBalance
                      )
                  );
              }
              // move stake for next epoch
              from.nextEpochBalance = uint256(from.nextEpochBalance).safeSub(amount).downcastToUint96();
              to.nextEpochBalance = uint256(to.nextEpochBalance).safeAdd(amount).downcastToUint96();
              // update state in storage
              _storeBalance(fromPtr, from);
              _storeBalance(toPtr, to);
          }
          /// @dev Loads a balance from storage and updates its fields to reflect values for the current epoch.
          /// @param balancePtr to load.
          /// @return current balance.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
              uint256 currentEpoch_ = currentEpoch;
              if (currentEpoch_ > balance.currentEpoch) {
                  balance.currentEpoch = currentEpoch_.downcastToUint64();
                  balance.currentEpochBalance = balance.nextEpochBalance;
              }
              return balance;
          }
          /// @dev Increments both the `current` and `next` fields.
          /// @param balancePtr storage pointer to balance.
          /// @param amount to mint.
          function _increaseCurrentAndNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Remove stake from balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeAdd(amount).downcastToUint96();
              balance.currentEpochBalance = uint256(balance.currentEpochBalance).safeAdd(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Decrements both the `current` and `next` fields.
          /// @param balancePtr storage pointer to balance.
          /// @param amount to mint.
          function _decreaseCurrentAndNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Remove stake from balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeSub(amount).downcastToUint96();
              balance.currentEpochBalance = uint256(balance.currentEpochBalance).safeSub(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Increments the `next` field (but not the `current` field).
          /// @param balancePtr storage pointer to balance.
          /// @param amount to increment by.
          function _increaseNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Add stake to balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeAdd(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Decrements the `next` field (but not the `current` field).
          /// @param balancePtr storage pointer to balance.
          /// @param amount to decrement by.
          function _decreaseNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Remove stake from balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeSub(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Stores a balance in storage.
          /// @param balancePtr points to where `balance` will be stored.
          /// @param balance to save to storage.
          function _storeBalance(
              IStructs.StoredBalance storage balancePtr,
              IStructs.StoredBalance memory balance
          )
              private
          {
              // note - this compresses into a single `sstore` when optimizations are enabled,
              // since the StoredBalance struct occupies a single word of storage.
              balancePtr.currentEpoch = balance.currentEpoch;
              balancePtr.nextEpochBalance = balance.nextEpochBalance;
              balancePtr.currentEpochBalance = balance.currentEpochBalance;
          }
          /// @dev Returns true iff storage pointers resolve to same storage location.
          /// @param balancePtrA first storage pointer.
          /// @param balancePtrB second storage pointer.
          /// @return true iff pointers are equal.
          function _arePointersEqual(
              // solhint-disable-next-line no-unused-vars
              IStructs.StoredBalance storage balancePtrA,
              // solhint-disable-next-line no-unused-vars
              IStructs.StoredBalance storage balancePtrB
          )
              private
              pure
              returns (bool areEqual)
          {
              assembly {
                  areEqual := and(
                      eq(balancePtrA_slot, balancePtrB_slot),
                      eq(balancePtrA_offset, balancePtrB_offset)
                  )
              }
              return areEqual;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMathRichErrors.sol";
      library LibSafeDowncast {
          /// @dev Safely downcasts to a uint96
          /// Note that this reverts if the input value is too large.
          function downcastToUint96(uint256 a)
              internal
              pure
              returns (uint96 b)
          {
              b = uint96(a);
              if (uint256(b) != a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256DowncastError(
                      LibSafeMathRichErrors.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96,
                      a
                  ));
              }
              return b;
          }
          /// @dev Safely downcasts to a uint64
          /// Note that this reverts if the input value is too large.
          function downcastToUint64(uint256 a)
              internal
              pure
              returns (uint64 b)
          {
              b = uint64(a);
              if (uint256(b) != a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256DowncastError(
                      LibSafeMathRichErrors.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
                      a
                  ));
              }
              return b;
          }
          /// @dev Safely downcasts to a uint32
          /// Note that this reverts if the input value is too large.
          function downcastToUint32(uint256 a)
              internal
              pure
              returns (uint32 b)
          {
              b = uint32(a);
              if (uint256(b) != a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256DowncastError(
                      LibSafeMathRichErrors.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
                      a
                  ));
              }
              return b;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../immutable/MixinStorage.sol";
      import "../interfaces/IStakingEvents.sol";
      contract MixinScheduler is
          IStakingEvents,
          MixinStorage
      {
          using LibSafeMath for uint256;
          /// @dev Returns the earliest end time in seconds of this epoch.
          ///      The next epoch can begin once this time is reached.
          ///      Epoch period = [startTimeInSeconds..endTimeInSeconds)
          /// @return Time in seconds.
          function getCurrentEpochEarliestEndTimeInSeconds()
              public
              view
              returns (uint256)
          {
              return currentEpochStartTimeInSeconds.safeAdd(epochDurationInSeconds);
          }
          /// @dev Initializes state owned by this mixin.
          ///      Fails if state was already initialized.
          function _initMixinScheduler()
              internal
          {
              // assert the current values before overwriting them.
              _assertSchedulerNotInitialized();
              // solhint-disable-next-line
              currentEpochStartTimeInSeconds = block.timestamp;
              currentEpoch = 1;
          }
          /// @dev Moves to the next epoch, given the current epoch period has ended.
          ///      Time intervals that are measured in epochs (like timeLocks) are also incremented, given
          ///      their periods have ended.
          function _goToNextEpoch()
              internal
          {
              // get current timestamp
              // solhint-disable-next-line not-rely-on-time
              uint256 currentBlockTimestamp = block.timestamp;
              // validate that we can increment the current epoch
              uint256 epochEndTime = getCurrentEpochEarliestEndTimeInSeconds();
              if (epochEndTime > currentBlockTimestamp) {
                  LibRichErrors.rrevert(LibStakingRichErrors.BlockTimestampTooLowError(
                      epochEndTime,
                      currentBlockTimestamp
                  ));
              }
              // incremment epoch
              uint256 nextEpoch = currentEpoch.safeAdd(1);
              currentEpoch = nextEpoch;
              currentEpochStartTimeInSeconds = currentBlockTimestamp;
          }
          /// @dev Assert scheduler state before initializing it.
          /// This must be updated for each migration.
          function _assertSchedulerNotInitialized()
              internal
              view
          {
              if (currentEpochStartTimeInSeconds != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InitializationError(
                          LibStakingRichErrors.InitializationErrorCodes.MixinSchedulerAlreadyInitialized
                      )
                  );
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStructs.sol";
      import "../sys/MixinFinalizer.sol";
      import "../staking_pools/MixinStakingPool.sol";
      import "./MixinExchangeManager.sol";
      contract MixinExchangeFees is
          MixinExchangeManager,
          MixinStakingPool,
          MixinFinalizer
      {
          using LibSafeMath for uint256;
          /// @dev Pays a protocol fee in ETH or WETH.
          ///      Only a known 0x exchange can call this method. See
          ///      (MixinExchangeManager).
          /// @param makerAddress The address of the order's maker.
          /// @param payerAddress The address of the protocol fee payer.
          /// @param protocolFee The protocol fee amount. This is either passed as ETH or transferred as WETH.
          function payProtocolFee(
              address makerAddress,
              address payerAddress,
              uint256 protocolFee
          )
              external
              payable
              onlyExchange
          {
              _assertValidProtocolFee(protocolFee);
              // Transfer the protocol fee to this address if it should be paid in
              // WETH.
              if (msg.value == 0) {
                  require(
                      getWethContract().transferFrom(
                          payerAddress,
                          address(this),
                          protocolFee
                      ),
                      "WETH_TRANSFER_FAILED"
                  );
              }
              // Get the pool id of the maker address.
              bytes32 poolId = poolIdByMaker[makerAddress];
              // Only attribute the protocol fee payment to a pool if the maker is
              // registered to a pool.
              if (poolId == NIL_POOL_ID) {
                  return;
              }
              uint256 poolStake = getTotalStakeDelegatedToPool(poolId).currentEpochBalance;
              // Ignore pools with dust stake.
              if (poolStake < minimumPoolStake) {
                  return;
              }
              // Look up the pool stats and aggregated stats for this epoch.
              uint256 currentEpoch_ = currentEpoch;
              IStructs.PoolStats storage poolStatsPtr = poolStatsByEpoch[poolId][currentEpoch_];
              IStructs.AggregatedStats storage aggregatedStatsPtr = aggregatedStatsByEpoch[currentEpoch_];
              // Perform some initialization if this is the pool's first protocol fee in this epoch.
              uint256 feesCollectedByPool = poolStatsPtr.feesCollected;
              if (feesCollectedByPool == 0) {
                  // Compute member and total weighted stake.
                  (uint256 membersStakeInPool, uint256 weightedStakeInPool) = _computeMembersAndWeightedStake(poolId, poolStake);
                  poolStatsPtr.membersStake = membersStakeInPool;
                  poolStatsPtr.weightedStake = weightedStakeInPool;
                  // Increase the total weighted stake.
                  aggregatedStatsPtr.totalWeightedStake = aggregatedStatsPtr.totalWeightedStake.safeAdd(weightedStakeInPool);
                  // Increase the number of pools to finalize.
                  aggregatedStatsPtr.numPoolsToFinalize = aggregatedStatsPtr.numPoolsToFinalize.safeAdd(1);
                  // Emit an event so keepers know what pools earned rewards this epoch.
                  emit StakingPoolEarnedRewardsInEpoch(currentEpoch_, poolId);
              }
              // Credit the fees to the pool.
              poolStatsPtr.feesCollected = feesCollectedByPool.safeAdd(protocolFee);
              // Increase the total fees collected this epoch.
              aggregatedStatsPtr.totalFeesCollected = aggregatedStatsPtr.totalFeesCollected.safeAdd(protocolFee);
          }
          /// @dev Get stats on a staking pool in this epoch.
          /// @param poolId Pool Id to query.
          /// @return PoolStats struct for pool id.
          function getStakingPoolStatsThisEpoch(bytes32 poolId)
              external
              view
              returns (IStructs.PoolStats memory)
          {
              return poolStatsByEpoch[poolId][currentEpoch];
          }
          /// @dev Computes the members and weighted stake for a pool at the current
          ///      epoch.
          /// @param poolId ID of the pool.
          /// @param totalStake Total (unweighted) stake in the pool.
          /// @return membersStake Non-operator stake in the pool.
          /// @return weightedStake Weighted stake of the pool.
          function _computeMembersAndWeightedStake(
              bytes32 poolId,
              uint256 totalStake
          )
              private
              view
              returns (uint256 membersStake, uint256 weightedStake)
          {
              uint256 operatorStake = getStakeDelegatedToPoolByOwner(
                  _poolById[poolId].operator,
                  poolId
              ).currentEpochBalance;
              membersStake = totalStake.safeSub(operatorStake);
              weightedStake = operatorStake.safeAdd(
                  LibMath.getPartialAmountFloor(
                      rewardDelegatedStakeWeight,
                      PPM_DENOMINATOR,
                      membersStake
                  )
              );
              return (membersStake, weightedStake);
          }
          /// @dev Checks that the protocol fee passed into `payProtocolFee()` is
          ///      valid.
          /// @param protocolFee The `protocolFee` parameter to
          ///        `payProtocolFee.`
          function _assertValidProtocolFee(uint256 protocolFee)
              private
              view
          {
              // The protocol fee must equal the value passed to the contract; unless
              // the value is zero, in which case the fee is taken in WETH.
              if (msg.value != protocolFee && msg.value != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InvalidProtocolFeePaymentError(
                          protocolFee,
                          msg.value
                      )
                  );
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibCobbDouglas.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStructs.sol";
      import "../staking_pools/MixinStakingPoolRewards.sol";
      contract MixinFinalizer is
          MixinStakingPoolRewards
      {
          using LibSafeMath for uint256;
          /// @dev Begins a new epoch, preparing the prior one for finalization.
          ///      Throws if not enough time has passed between epochs or if the
          ///      previous epoch was not fully finalized.
          /// @return numPoolsToFinalize The number of unfinalized pools.
          function endEpoch()
              external
              returns (uint256)
          {
              uint256 currentEpoch_ = currentEpoch;
              uint256 prevEpoch = currentEpoch_.safeSub(1);
              // Make sure the previous epoch has been fully finalized.
              uint256 numPoolsToFinalizeFromPrevEpoch = aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize;
              if (numPoolsToFinalizeFromPrevEpoch != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.PreviousEpochNotFinalizedError(
                          prevEpoch,
                          numPoolsToFinalizeFromPrevEpoch
                      )
                  );
              }
              // Convert all ETH to WETH; the WETH balance of this contract is the total rewards.
              _wrapEth();
              // Load aggregated stats for the epoch we're ending.
              aggregatedStatsByEpoch[currentEpoch_].rewardsAvailable = _getAvailableWethBalance();
              IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[currentEpoch_];
              // Emit an event.
              emit EpochEnded(
                  currentEpoch_,
                  aggregatedStats.numPoolsToFinalize,
                  aggregatedStats.rewardsAvailable,
                  aggregatedStats.totalFeesCollected,
                  aggregatedStats.totalWeightedStake
              );
              // Advance the epoch. This will revert if not enough time has passed.
              _goToNextEpoch();
              // If there are no pools to finalize then the epoch is finalized.
              if (aggregatedStats.numPoolsToFinalize == 0) {
                  emit EpochFinalized(currentEpoch_, 0, aggregatedStats.rewardsAvailable);
              }
              return aggregatedStats.numPoolsToFinalize;
          }
          /// @dev Instantly finalizes a single pool that earned rewards in the previous
          ///      epoch, crediting it rewards for members and withdrawing operator's
          ///      rewards as WETH. This can be called by internal functions that need
          ///      to finalize a pool immediately. Does nothing if the pool is already
          ///      finalized or did not earn rewards in the previous epoch.
          /// @param poolId The pool ID to finalize.
          function finalizePool(bytes32 poolId)
              external
          {
              // Compute relevant epochs
              uint256 currentEpoch_ = currentEpoch;
              uint256 prevEpoch = currentEpoch_.safeSub(1);
              // Load the aggregated stats into memory; noop if no pools to finalize.
              IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[prevEpoch];
              if (aggregatedStats.numPoolsToFinalize == 0) {
                  return;
              }
              // Noop if the pool did not earn rewards or already finalized (has no fees).
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
              if (poolStats.feesCollected == 0) {
                  return;
              }
              // Clear the pool stats so we don't finalize it again, and to recoup
              // some gas.
              delete poolStatsByEpoch[poolId][prevEpoch];
              // Compute the rewards.
              uint256 rewards = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStats);
              // Pay the operator and update rewards for the pool.
              // Note that we credit at the CURRENT epoch even though these rewards
              // were earned in the previous epoch.
              (uint256 operatorReward, uint256 membersReward) = _syncPoolRewards(
                  poolId,
                  rewards,
                  poolStats.membersStake
              );
              // Emit an event.
              emit RewardsPaid(
                  currentEpoch_,
                  poolId,
                  operatorReward,
                  membersReward
              );
              uint256 totalReward = operatorReward.safeAdd(membersReward);
              // Increase `totalRewardsFinalized`.
              aggregatedStatsByEpoch[prevEpoch].totalRewardsFinalized =
                  aggregatedStats.totalRewardsFinalized =
                  aggregatedStats.totalRewardsFinalized.safeAdd(totalReward);
              // Decrease the number of unfinalized pools left.
              aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize =
                  aggregatedStats.numPoolsToFinalize =
                  aggregatedStats.numPoolsToFinalize.safeSub(1);
              // If there are no more unfinalized pools remaining, the epoch is
              // finalized.
              if (aggregatedStats.numPoolsToFinalize == 0) {
                  emit EpochFinalized(
                      prevEpoch,
                      aggregatedStats.totalRewardsFinalized,
                      aggregatedStats.rewardsAvailable.safeSub(aggregatedStats.totalRewardsFinalized)
                  );
              }
          }
          /// @dev Computes the reward owed to a pool during finalization.
          ///      Does nothing if the pool is already finalized.
          /// @param poolId The pool's ID.
          /// @return totalReward The total reward owed to a pool.
          /// @return membersStake The total stake for all non-operator members in
          ///         this pool.
          function _getUnfinalizedPoolRewards(bytes32 poolId)
              internal
              view
              returns (
                  uint256 reward,
                  uint256 membersStake
              )
          {
              uint256 prevEpoch = currentEpoch.safeSub(1);
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
              reward = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStatsByEpoch[prevEpoch]);
              membersStake = poolStats.membersStake;
          }
          /// @dev Converts the entire ETH balance of this contract into WETH.
          function _wrapEth()
              internal
          {
              uint256 ethBalance = address(this).balance;
              if (ethBalance != 0) {
                  getWethContract().deposit.value(ethBalance)();
              }
          }
          /// @dev Returns the WETH balance of this contract, minus
          ///      any WETH that has already been reserved for rewards.
          function _getAvailableWethBalance()
              internal
              view
              returns (uint256 wethBalance)
          {
              wethBalance = getWethContract().balanceOf(address(this))
                  .safeSub(wethReservedForPoolRewards);
              return wethBalance;
          }
          /// @dev Asserts that a pool has been finalized last epoch.
          /// @param poolId The id of the pool that should have been finalized.
          function _assertPoolFinalizedLastEpoch(bytes32 poolId)
              internal
              view
          {
              uint256 prevEpoch = currentEpoch.safeSub(1);
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
              // A pool that has any fees remaining has not been finalized
              if (poolStats.feesCollected != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.PoolNotFinalizedError(
                          poolId,
                          prevEpoch
                      )
                  );
              }
          }
          /// @dev Computes the reward owed to a pool during finalization.
          /// @param poolStats Stats for a specific pool.
          /// @param aggregatedStats Stats aggregated across all pools.
          /// @return rewards Unfinalized rewards for the input pool.
          function _getUnfinalizedPoolRewardsFromPoolStats(
              IStructs.PoolStats memory poolStats,
              IStructs.AggregatedStats memory aggregatedStats
          )
              private
              view
              returns (uint256 rewards)
          {
              // There can't be any rewards if the pool did not collect any fees.
              if (poolStats.feesCollected == 0) {
                  return rewards;
              }
              // Use the cobb-douglas function to compute the total reward.
              rewards = LibCobbDouglas.cobbDouglas(
                  aggregatedStats.rewardsAvailable,
                  poolStats.feesCollected,
                  aggregatedStats.totalFeesCollected,
                  poolStats.weightedStake,
                  aggregatedStats.totalWeightedStake,
                  cobbDouglasAlphaNumerator,
                  cobbDouglasAlphaDenominator
              );
              // Clip the reward to always be under
              // `rewardsAvailable - totalRewardsPaid`,
              // in case cobb-douglas overflows, which should be unlikely.
              uint256 rewardsRemaining = aggregatedStats.rewardsAvailable.safeSub(aggregatedStats.totalRewardsFinalized);
              if (rewardsRemaining < rewards) {
                  rewards = rewardsRemaining;
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./LibFixedMath.sol";
      library LibCobbDouglas {
          /// @dev The cobb-douglas function used to compute fee-based rewards for
          ///      staking pools in a given epoch. This function does not perform
          ///      bounds checking on the inputs, but the following conditions
          ///      need to be true:
          ///         0 <= fees / totalFees <= 1
          ///         0 <= stake / totalStake <= 1
          ///         0 <= alphaNumerator / alphaDenominator <= 1
          /// @param totalRewards collected over an epoch.
          /// @param fees Fees attributed to the the staking pool.
          /// @param totalFees Total fees collected across all pools that earned rewards.
          /// @param stake Stake attributed to the staking pool.
          /// @param totalStake Total stake across all pools that earned rewards.
          /// @param alphaNumerator Numerator of `alpha` in the cobb-douglas function.
          /// @param alphaDenominator Denominator of `alpha` in the cobb-douglas
          ///        function.
          /// @return rewards Rewards owed to the staking pool.
          function cobbDouglas(
              uint256 totalRewards,
              uint256 fees,
              uint256 totalFees,
              uint256 stake,
              uint256 totalStake,
              uint32 alphaNumerator,
              uint32 alphaDenominator
          )
              internal
              pure
              returns (uint256 rewards)
          {
              int256 feeRatio = LibFixedMath.toFixed(fees, totalFees);
              int256 stakeRatio = LibFixedMath.toFixed(stake, totalStake);
              if (feeRatio == 0 || stakeRatio == 0) {
                  return rewards = 0;
              }
              // The cobb-doublas function has the form:
              // `totalRewards * feeRatio ^ alpha * stakeRatio ^ (1-alpha)`
              // This is equivalent to:
              // `totalRewards * stakeRatio * e^(alpha * (ln(feeRatio / stakeRatio)))`
              // However, because `ln(x)` has the domain of `0 < x < 1`
              // and `exp(x)` has the domain of `x < 0`,
              // and fixed-point math easily overflows with multiplication,
              // we will choose the following if `stakeRatio > feeRatio`:
              // `totalRewards * stakeRatio / e^(alpha * (ln(stakeRatio / feeRatio)))`
              // Compute
              // `e^(alpha * ln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio
              // or
              // `e^(alpa * ln(stakeRatio/feeRatio))` if feeRatio > stakeRatio
              int256 n = feeRatio <= stakeRatio ?
                  LibFixedMath.div(feeRatio, stakeRatio) :
                  LibFixedMath.div(stakeRatio, feeRatio);
              n = LibFixedMath.exp(
                  LibFixedMath.mulDiv(
                      LibFixedMath.ln(n),
                      int256(alphaNumerator),
                      int256(alphaDenominator)
                  )
              );
              // Compute
              // `totalRewards * n` if feeRatio <= stakeRatio
              // or
              // `totalRewards / n` if stakeRatio > feeRatio
              // depending on the choice we made earlier.
              n = feeRatio <= stakeRatio ?
                  LibFixedMath.mul(stakeRatio, n) :
                  LibFixedMath.div(stakeRatio, n);
              // Multiply the above with totalRewards.
              rewards = LibFixedMath.uintMul(n, totalRewards);
          }
      }
      /*
        Copyright 2017 Bprotocol Foundation, 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./LibFixedMathRichErrors.sol";
      // solhint-disable indent
      /// @dev Signed, fixed-point, 127-bit precision math library.
      library LibFixedMath {
          // 1
          int256 private constant FIXED_1 = int256(0x0000000000000000000000000000000080000000000000000000000000000000);
          // 2**255
          int256 private constant MIN_FIXED_VAL = int256(0x8000000000000000000000000000000000000000000000000000000000000000);
          // 1^2 (in fixed-point)
          int256 private constant FIXED_1_SQUARED = int256(0x4000000000000000000000000000000000000000000000000000000000000000);
          // 1
          int256 private constant LN_MAX_VAL = FIXED_1;
          // e ^ -63.875
          int256 private constant LN_MIN_VAL = int256(0x0000000000000000000000000000000000000000000000000000000733048c5a);
          // 0
          int256 private constant EXP_MAX_VAL = 0;
          // -63.875
          int256 private constant EXP_MIN_VAL = -int256(0x0000000000000000000000000000001ff0000000000000000000000000000000);
          /// @dev Get one as a fixed-point number.
          function one() internal pure returns (int256 f) {
              f = FIXED_1;
          }
          /// @dev Returns the addition of two fixed point numbers, reverting on overflow.
          function add(int256 a, int256 b) internal pure returns (int256 c) {
              c = _add(a, b);
          }
          /// @dev Returns the addition of two fixed point numbers, reverting on overflow.
          function sub(int256 a, int256 b) internal pure returns (int256 c) {
              if (b == MIN_FIXED_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_SMALL,
                      b
                  ));
              }
              c = _add(a, -b);
          }
          /// @dev Returns the multiplication of two fixed point numbers, reverting on overflow.
          function mul(int256 a, int256 b) internal pure returns (int256 c) {
              c = _mul(a, b) / FIXED_1;
          }
          /// @dev Returns the division of two fixed point numbers.
          function div(int256 a, int256 b) internal pure returns (int256 c) {
              c = _div(_mul(a, FIXED_1), b);
          }
          /// @dev Performs (a * n) / d, without scaling for precision.
          function mulDiv(int256 a, int256 n, int256 d) internal pure returns (int256 c) {
              c = _div(_mul(a, n), d);
          }
          /// @dev Returns the unsigned integer result of multiplying a fixed-point
          ///      number with an integer, reverting if the multiplication overflows.
          ///      Negative results are clamped to zero.
          function uintMul(int256 f, uint256 u) internal pure returns (uint256) {
              if (int256(u) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      u
                  ));
              }
              int256 c = _mul(f, int256(u));
              if (c <= 0) {
                  return 0;
              }
              return uint256(uint256(c) >> 127);
          }
          /// @dev Returns the absolute value of a fixed point number.
          function abs(int256 f) internal pure returns (int256 c) {
              if (f == MIN_FIXED_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_SMALL,
                      f
                  ));
              }
              if (f >= 0) {
                  c = f;
              } else {
                  c = -f;
              }
          }
          /// @dev Returns 1 / `x`, where `x` is a fixed-point number.
          function invert(int256 f) internal pure returns (int256 c) {
              c = _div(FIXED_1_SQUARED, f);
          }
          /// @dev Convert signed `n` / 1 to a fixed-point number.
          function toFixed(int256 n) internal pure returns (int256 f) {
              f = _mul(n, FIXED_1);
          }
          /// @dev Convert signed `n` / `d` to a fixed-point number.
          function toFixed(int256 n, int256 d) internal pure returns (int256 f) {
              f = _div(_mul(n, FIXED_1), d);
          }
          /// @dev Convert unsigned `n` / 1 to a fixed-point number.
          ///      Reverts if `n` is too large to fit in a fixed-point number.
          function toFixed(uint256 n) internal pure returns (int256 f) {
              if (int256(n) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      n
                  ));
              }
              f = _mul(int256(n), FIXED_1);
          }
          /// @dev Convert unsigned `n` / `d` to a fixed-point number.
          ///      Reverts if `n` / `d` is too large to fit in a fixed-point number.
          function toFixed(uint256 n, uint256 d) internal pure returns (int256 f) {
              if (int256(n) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      n
                  ));
              }
              if (int256(d) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      d
                  ));
              }
              f = _div(_mul(int256(n), FIXED_1), int256(d));
          }
          /// @dev Convert a fixed-point number to an integer.
          function toInteger(int256 f) internal pure returns (int256 n) {
              return f / FIXED_1;
          }
          /// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL
          function ln(int256 x) internal pure returns (int256 r) {
              if (x > LN_MAX_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      x
                  ));
              }
              if (x <= 0) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_SMALL,
                      x
                  ));
              }
              if (x == FIXED_1) {
                  return 0;
              }
              if (x <= LN_MIN_VAL) {
                  return EXP_MIN_VAL;
              }
              int256 y;
              int256 z;
              int256 w;
              // Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2
              // For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522)
              //              = 1 - 0.25 - log(1 + 0.0471028872385522)
              // e ^ -32
              if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) {
                  r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32
                  x = x * FIXED_1 / int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32
              }
              // e ^ -16
              if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) {
                  r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16
                  x = x * FIXED_1 / int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16
              }
              // e ^ -8
              if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8
                  x = x * FIXED_1 / int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8
              }
              // e ^ -4
              if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4
                  x = x * FIXED_1 / int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4
              }
              // e ^ -2
              if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2
                  x = x * FIXED_1 / int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2
              }
              // e ^ -1
              if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1
                  x = x * FIXED_1 / int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1
              }
              // e ^ -0.5
              if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5
                  x = x * FIXED_1 / int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5
              }
              // e ^ -0.25
              if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25
                  x = x * FIXED_1 / int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25
              }
              // e ^ -0.125
              if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) {
                  r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125
                  x = x * FIXED_1 / int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125
              }
              // `x` is now our residual in the range of 1 <= x <= 2 (or close enough).
              // Add the taylor series for log(1 + z), where z = x - 1
              z = y = x - FIXED_1;
              w = y * y / FIXED_1;
              r += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
              r += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
              r += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
              r += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
              r += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
              r += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
              r += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
              r += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000;                      // add y^15 / 15 - y^16 / 16
          }
          /// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1
          function exp(int256 x) internal pure returns (int256 r) {
              if (x < EXP_MIN_VAL) {
                  // Saturate to zero below EXP_MIN_VAL.
                  return 0;
              }
              if (x == 0) {
                  return FIXED_1;
              }
              if (x > EXP_MAX_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      x
                  ));
              }
              // Rewrite the input as a product of natural exponents and a
              // single residual q, where q is a number of small magnitude.
              // For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044)
              //              = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044
              //              -> q = -0.044
              // Multiply with the taylor series for e^q
              int256 y;
              int256 z;
              // q = x % 0.125 (the residual)
              z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000;
              z = z * y / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
              z = z * y / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
              z = z * y / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
              z = z * y / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
              z = z * y / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
              z = z * y / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
              z = z * y / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
              z = z * y / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
              z = z * y / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
              z = z * y / FIXED_1; r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
              z = z * y / FIXED_1; r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
              z = z * y / FIXED_1; r += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
              z = z * y / FIXED_1; r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
              z = z * y / FIXED_1; r += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
              z = z * y / FIXED_1; r += z * 0x000000000001c638; // add y^16 * (20! / 16!)
              z = z * y / FIXED_1; r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
              z = z * y / FIXED_1; r += z * 0x000000000000017c; // add y^18 * (20! / 18!)
              z = z * y / FIXED_1; r += z * 0x0000000000000014; // add y^19 * (20! / 19!)
              z = z * y / FIXED_1; r += z * 0x0000000000000001; // add y^20 * (20! / 20!)
              r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
              // Multiply with the non-residual terms.
              x = -x;
              // e ^ -32
              if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) {
                  r = r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)
                      / int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32
              }
              // e ^ -16
              if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) {
                  r = r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)
                      / int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16
              }
              // e ^ -8
              if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) {
                  r = r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)
                      / int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8
              }
              // e ^ -4
              if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) {
                  r = r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)
                      / int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4
              }
              // e ^ -2
              if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) {
                  r = r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)
                      / int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2
              }
              // e ^ -1
              if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) {
                  r = r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)
                      / int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1
              }
              // e ^ -0.5
              if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) {
                  r = r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)
                      / int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5
              }
              // e ^ -0.25
              if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) {
                  r = r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)
                      / int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25
              }
              // e ^ -0.125
              if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) {
                  r = r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)
                      / int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125
              }
          }
          /// @dev Returns the multiplication two numbers, reverting on overflow.
          function _mul(int256 a, int256 b) private pure returns (int256 c) {
              if (a == 0) {
                  return 0;
              }
              c = a * b;
              if (c / a != b || c / b != a) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
                      a,
                      b
                  ));
              }
          }
          /// @dev Returns the division of two numbers, reverting on division by zero.
          function _div(int256 a, int256 b) private pure returns (int256 c) {
              if (b == 0) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
                      a,
                      b
                  ));
              }
              if (a == MIN_FIXED_VAL && b == -1) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.DIVISION_OVERFLOW,
                      a,
                      b
                  ));
              }
              c = a / b;
          }
          /// @dev Adds two numbers, reverting on overflow.
          function _add(int256 a, int256 b) private pure returns (int256 c) {
              c = a + b;
              if ((a < 0 && b < 0 && c > a) || (a > 0 && b > 0 && c < a)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
                      a,
                      b
                  ));
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      library LibFixedMathRichErrors {
          enum ValueErrorCodes {
              TOO_SMALL,
              TOO_LARGE
          }
          enum BinOpErrorCodes {
              ADDITION_OVERFLOW,
              MULTIPLICATION_OVERFLOW,
              DIVISION_BY_ZERO,
              DIVISION_OVERFLOW
          }
          // bytes4(keccak256("SignedValueError(uint8,int256)"))
          bytes4 internal constant SIGNED_VALUE_ERROR_SELECTOR =
              0xed2f26a1;
          // bytes4(keccak256("UnsignedValueError(uint8,uint256)"))
          bytes4 internal constant UNSIGNED_VALUE_ERROR_SELECTOR =
              0xbd79545f;
          // bytes4(keccak256("BinOpError(uint8,int256,int256)"))
          bytes4 internal constant BIN_OP_ERROR_SELECTOR =
              0x8c12dfe7;
          // solhint-disable func-name-mixedcase
          function SignedValueError(
              ValueErrorCodes error,
              int256 n
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  SIGNED_VALUE_ERROR_SELECTOR,
                  uint8(error),
                  n
              );
          }
          function UnsignedValueError(
              ValueErrorCodes error,
              uint256 n
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  UNSIGNED_VALUE_ERROR_SELECTOR,
                  uint8(error),
                  n
              );
          }
          function BinOpError(
              BinOpErrorCodes error,
              int256 a,
              int256 b
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  BIN_OP_ERROR_SELECTOR,
                  uint8(error),
                  a,
                  b
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStakingEvents.sol";
      import "../immutable/MixinStorage.sol";
      contract MixinExchangeManager is
          IStakingEvents,
          MixinStorage
      {
          /// @dev Asserts that the call is coming from a valid exchange.
          modifier onlyExchange() {
              if (!validExchanges[msg.sender]) {
                  LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableByExchangeError(
                      msg.sender
                  ));
              }
              _;
          }
          /// @dev Adds a new exchange address
          /// @param addr Address of exchange contract to add
          function addExchangeAddress(address addr)
              external
              onlyAuthorized
          {
              if (validExchanges[addr]) {
                  LibRichErrors.rrevert(LibStakingRichErrors.ExchangeManagerError(
                      LibStakingRichErrors.ExchangeManagerErrorCodes.ExchangeAlreadyRegistered,
                      addr
                  ));
              }
              validExchanges[addr] = true;
              emit ExchangeAdded(addr);
          }
          /// @dev Removes an existing exchange address
          /// @param addr Address of exchange contract to remove
          function removeExchangeAddress(address addr)
              external
              onlyAuthorized
          {
              if (!validExchanges[addr]) {
                  LibRichErrors.rrevert(LibStakingRichErrors.ExchangeManagerError(
                      LibStakingRichErrors.ExchangeManagerErrorCodes.ExchangeNotRegistered,
                      addr
                  ));
              }
              validExchanges[addr] = false;
              emit ExchangeRemoved(addr);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./libs/LibSafeDowncast.sol";
      import "./immutable/MixinStorage.sol";
      import "./immutable/MixinConstants.sol";
      import "./interfaces/IStorageInit.sol";
      import "./interfaces/IStakingProxy.sol";
      contract StakingProxy is
          IStakingProxy,
          MixinStorage,
          MixinConstants
      {
          using LibSafeDowncast for uint256;
          /// @dev Constructor.
          /// @param _stakingContract Staking contract to delegate calls to.
          constructor(address _stakingContract)
              public
              MixinStorage()
          {
              // Deployer address must be authorized in order to call `init`
              _addAuthorizedAddress(msg.sender);
              // Attach the staking contract and initialize state
              _attachStakingContract(_stakingContract);
              // Remove the sender as an authorized address
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          /// @dev Delegates calls to the staking contract, if it is set.
          function ()
              external
              payable
          {
              // Sanity check that we have a staking contract to call
              address stakingContract_ = stakingContract;
              if (stakingContract_ == NIL_ADDRESS) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.ProxyDestinationCannotBeNilError()
                  );
              }
              // Call the staking contract with the provided calldata.
              (bool success, bytes memory returnData) = stakingContract_.delegatecall(msg.data);
              // Revert on failure or return on success.
              assembly {
                  switch success
                  case 0 {
                      revert(add(0x20, returnData), mload(returnData))
                  }
                  default {
                      return(add(0x20, returnData), mload(returnData))
                  }
              }
          }
          /// @dev Attach a staking contract; future calls will be delegated to the staking contract.
          /// Note that this is callable only by an authorized address.
          /// @param _stakingContract Address of staking contract.
          function attachStakingContract(address _stakingContract)
              external
              onlyAuthorized
          {
              _attachStakingContract(_stakingContract);
          }
          /// @dev Detach the current staking contract.
          /// Note that this is callable only by an authorized address.
          function detachStakingContract()
              external
              onlyAuthorized
          {
              stakingContract = NIL_ADDRESS;
              emit StakingContractDetachedFromProxy();
          }
          /// @dev Batch executes a series of calls to the staking contract.
          /// @param data An array of data that encodes a sequence of functions to
          ///             call in the staking contracts.
          function batchExecute(bytes[] calldata data)
              external
              returns (bytes[] memory batchReturnData)
          {
              // Initialize commonly used variables.
              bool success;
              bytes memory returnData;
              uint256 dataLength = data.length;
              batchReturnData = new bytes[](dataLength);
              address staking = stakingContract;
              // Ensure that a staking contract has been attached to the proxy.
              if (staking == NIL_ADDRESS) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.ProxyDestinationCannotBeNilError()
                  );
              }
              // Execute all of the calls encoded in the provided calldata.
              for (uint256 i = 0; i != dataLength; i++) {
                  // Call the staking contract with the provided calldata.
                  (success, returnData) = staking.delegatecall(data[i]);
                  // Revert on failure.
                  if (!success) {
                      assembly {
                          revert(add(0x20, returnData), mload(returnData))
                      }
                  }
                  // Add the returndata to the batch returndata.
                  batchReturnData[i] = returnData;
              }
              return batchReturnData;
          }
          /// @dev Asserts that an epoch is between 5 and 30 days long.
          //       Asserts that 0 < cobb douglas alpha value <= 1.
          //       Asserts that a stake weight is <= 100%.
          //       Asserts that pools allow >= 1 maker.
          //       Asserts that all addresses are initialized.
          function assertValidStorageParams()
              public
              view
          {
              // Epoch length must be between 5 and 30 days long
              uint256 _epochDurationInSeconds = epochDurationInSeconds;
              if (_epochDurationInSeconds < 5 days || _epochDurationInSeconds > 30 days) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InvalidParamValueError(
                          LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidEpochDuration
                  ));
              }
              // Alpha must be 0 < x <= 1
              uint32 _cobbDouglasAlphaDenominator = cobbDouglasAlphaDenominator;
              if (cobbDouglasAlphaNumerator > _cobbDouglasAlphaDenominator || _cobbDouglasAlphaDenominator == 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InvalidParamValueError(
                          LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha
                  ));
              }
              // Weight of delegated stake must be <= 100%
              if (rewardDelegatedStakeWeight > PPM_DENOMINATOR) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InvalidParamValueError(
                          LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight
                  ));
              }
              // Minimum stake must be > 1
              if (minimumPoolStake < 2) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InvalidParamValueError(
                          LibStakingRichErrors.InvalidParamValueErrorCodes.InvalidMinimumPoolStake
                  ));
              }
          }
          /// @dev Attach a staking contract; future calls will be delegated to the staking contract.
          /// @param _stakingContract Address of staking contract.
          function _attachStakingContract(address _stakingContract)
              internal
          {
              // Attach the staking contract
              stakingContract = _stakingContract;
              emit StakingContractAttachedToProxy(_stakingContract);
              // Call `init()` on the staking contract to initialize storage.
              (bool didInitSucceed, bytes memory initReturnData) = stakingContract.delegatecall(
                  abi.encodeWithSelector(IStorageInit(0).init.selector)
              );
              if (!didInitSucceed) {
                  assembly {
                      revert(add(initReturnData, 0x20), mload(initReturnData))
                  }
              }
              // Assert initialized storage values are valid
              assertValidStorageParams();
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      interface IStorageInit {
          /// @dev Initialize storage owned by this contract.
          function init()
              external;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/Authorizable.sol";
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetProxy.sol";
      import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
      import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
      import "./libs/LibStakingRichErrors.sol";
      import "./interfaces/IZrxVault.sol";
      contract ZrxVault is
          Authorizable,
          IZrxVault
      {
          using LibSafeMath for uint256;
          // Address of staking proxy contract
          address public stakingProxyAddress;
          // True iff vault has been set to Catastrophic Failure Mode
          bool public isInCatastrophicFailure;
          // Mapping from staker to ZRX balance
          mapping (address => uint256) internal _balances;
          // Zrx Asset Proxy
          IAssetProxy public zrxAssetProxy;
          // Zrx Token
          IERC20Token internal _zrxToken;
          // Asset data for the ERC20 Proxy
          bytes internal _zrxAssetData;
          /// @dev Only stakingProxy can call this function.
          modifier onlyStakingProxy() {
              _assertSenderIsStakingProxy();
              _;
          }
          /// @dev Function can only be called in catastrophic failure mode.
          modifier onlyInCatastrophicFailure() {
              _assertInCatastrophicFailure();
              _;
          }
          /// @dev Function can only be called not in catastropic failure mode
          modifier onlyNotInCatastrophicFailure() {
              _assertNotInCatastrophicFailure();
              _;
          }
          /// @dev Constructor.
          /// @param _zrxProxyAddress Address of the 0x Zrx Proxy.
          /// @param _zrxTokenAddress Address of the Zrx Token.
          constructor(
              address _zrxProxyAddress,
              address _zrxTokenAddress
          )
              public
              Authorizable()
          {
              zrxAssetProxy = IAssetProxy(_zrxProxyAddress);
              _zrxToken = IERC20Token(_zrxTokenAddress);
              _zrxAssetData = abi.encodeWithSelector(
                  IAssetData(address(0)).ERC20Token.selector,
                  _zrxTokenAddress
              );
          }
          /// @dev Sets the address of the StakingProxy contract.
          /// Note that only the contract owner can call this function.
          /// @param _stakingProxyAddress Address of Staking proxy contract.
          function setStakingProxy(address _stakingProxyAddress)
              external
              onlyAuthorized
          {
              stakingProxyAddress = _stakingProxyAddress;
              emit StakingProxySet(_stakingProxyAddress);
          }
          /// @dev Vault enters into Catastrophic Failure Mode.
          /// *** WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! ***
          /// Note that only the contract owner can call this function.
          function enterCatastrophicFailure()
              external
              onlyAuthorized
              onlyNotInCatastrophicFailure
          {
              isInCatastrophicFailure = true;
              emit InCatastrophicFailureMode(msg.sender);
          }
          /// @dev Sets the Zrx proxy.
          /// Note that only an authorized address can call this function.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param _zrxProxyAddress Address of the 0x Zrx Proxy.
          function setZrxProxy(address _zrxProxyAddress)
              external
              onlyAuthorized
              onlyNotInCatastrophicFailure
          {
              zrxAssetProxy = IAssetProxy(_zrxProxyAddress);
              emit ZrxProxySet(_zrxProxyAddress);
          }
          /// @dev Deposit an `amount` of Zrx Tokens from `staker` into the vault.
          /// Note that only the Staking contract can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to deposit.
          function depositFrom(address staker, uint256 amount)
              external
              onlyStakingProxy
              onlyNotInCatastrophicFailure
          {
              // update balance
              _balances[staker] = _balances[staker].safeAdd(amount);
              // notify
              emit Deposit(staker, amount);
              // deposit ZRX from staker
              zrxAssetProxy.transferFrom(
                  _zrxAssetData,
                  staker,
                  address(this),
                  amount
              );
          }
          /// @dev Withdraw an `amount` of Zrx Tokens to `staker` from the vault.
          /// Note that only the Staking contract can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to withdraw.
          function withdrawFrom(address staker, uint256 amount)
              external
              onlyStakingProxy
              onlyNotInCatastrophicFailure
          {
              _withdrawFrom(staker, amount);
          }
          /// @dev Withdraw ALL Zrx Tokens to `staker` from the vault.
          /// Note that this can only be called when *in* Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          function withdrawAllFrom(address staker)
              external
              onlyInCatastrophicFailure
              returns (uint256)
          {
              // get total balance
              uint256 totalBalance = _balances[staker];
              // withdraw ZRX to staker
              _withdrawFrom(staker, totalBalance);
              return totalBalance;
          }
          /// @dev Returns the balance in Zrx Tokens of the `staker`
          /// @return Balance in Zrx.
          function balanceOf(address staker)
              external
              view
              returns (uint256)
          {
              return _balances[staker];
          }
          /// @dev Returns the entire balance of Zrx tokens in the vault.
          function balanceOfZrxVault()
              external
              view
              returns (uint256)
          {
              return _zrxToken.balanceOf(address(this));
          }
          /// @dev Withdraw an `amount` of Zrx Tokens to `staker` from the vault.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to withdraw.
          function _withdrawFrom(address staker, uint256 amount)
              internal
          {
              // update balance
              // note that this call will revert if trying to withdraw more
              // than the current balance
              _balances[staker] = _balances[staker].safeSub(amount);
              // notify
              emit Withdraw(staker, amount);
              // withdraw ZRX to staker
              _zrxToken.transfer(
                  staker,
                  amount
              );
          }
          /// @dev Asserts that sender is stakingProxy contract.
          function _assertSenderIsStakingProxy()
              private
              view
          {
              if (msg.sender != stakingProxyAddress) {
                  LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableByStakingContractError(
                      msg.sender
                  ));
              }
          }
          /// @dev Asserts that vault is in catastrophic failure mode.
          function _assertInCatastrophicFailure()
              private
              view
          {
              if (!isInCatastrophicFailure) {
                  LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableIfInCatastrophicFailureError());
              }
          }
          /// @dev Asserts that vault is not in catastrophic failure mode.
          function _assertNotInCatastrophicFailure()
              private
              view
          {
              if (isInCatastrophicFailure) {
                  LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableIfNotInCatastrophicFailureError());
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract IAssetProxy {
          /// @dev Transfers assets. Either succeeds or throws.
          /// @param assetData Byte array encoded for the respective asset proxy.
          /// @param from Address to transfer asset from.
          /// @param to Address to transfer asset to.
          /// @param amount Amount of asset to transfer.
          function transferFrom(
              bytes calldata assetData,
              address from,
              address to,
              uint256 amount
          )
              external;
          
          /// @dev Gets the proxy id associated with the proxy address.
          /// @return Proxy id.
          function getProxyId()
              external
              pure
              returns (bytes4);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      // solhint-disable
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      // @dev Interface of the asset proxy's assetData.
      // The asset proxies take an ABI encoded `bytes assetData` as argument.
      // This argument is ABI encoded as one of the methods of this interface.
      interface IAssetData {
          /// @dev Function signature for encoding ERC20 assetData.
          /// @param tokenAddress Address of ERC20Token contract.
          function ERC20Token(address tokenAddress)
              external;
          /// @dev Function signature for encoding ERC721 assetData.
          /// @param tokenAddress Address of ERC721 token contract.
          /// @param tokenId Id of ERC721 token to be transferred.
          function ERC721Token(
              address tokenAddress,
              uint256 tokenId
          )
              external;
          /// @dev Function signature for encoding ERC1155 assetData.
          /// @param tokenAddress Address of ERC1155 token contract.
          /// @param tokenIds Array of ids of tokens to be transferred.
          /// @param values Array of values that correspond to each token id to be transferred.
          ///        Note that each value will be multiplied by the amount being filled in the order before transferring.
          /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function.
          function ERC1155Assets(
              address tokenAddress,
              uint256[] calldata tokenIds,
              uint256[] calldata values,
              bytes calldata callbackData
          )
              external;
          /// @dev Function signature for encoding MultiAsset assetData.
          /// @param values Array of amounts that correspond to each asset to be transferred.
          ///        Note that each value will be multiplied by the amount being filled in the order before transferring.
          /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract.
          function MultiAsset(
              uint256[] calldata values,
              bytes[] calldata nestedAssetData
          )
              external;
          /// @dev Function signature for encoding StaticCall assetData.
          /// @param staticCallTargetAddress Address that will execute the staticcall.
          /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress.
          /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data.
          function StaticCall(
              address staticCallTargetAddress,
              bytes calldata staticCallData,
              bytes32 expectedReturnDataHash
          )
              external;
          /// @dev Function signature for encoding ERC20Bridge assetData.
          /// @param tokenAddress Address of token to transfer.
          /// @param bridgeAddress Address of the bridge contract.
          /// @param bridgeData Arbitrary data to be passed to the bridge contract.
          function ERC20Bridge(
              address tokenAddress,
              address bridgeAddress,
              bytes calldata bridgeData
          )
              external;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../interfaces/IZrxVault.sol";
      import "../interfaces/IStructs.sol";
      interface IStorage {
          function stakingContract()
              external
              view
              returns (address);
          function lastPoolId()
              external
              view
              returns (bytes32);
          function numMakersByPoolId(bytes32 poolId)
              external
              view
              returns (uint256);
          function currentEpoch()
              external
              view
              returns (uint256);
          function currentEpochStartTimeInSeconds()
              external
              view
              returns (uint256);
          function protocolFeesThisEpochByPool(bytes32 poolId)
              external
              view
              returns (uint256);
          function validExchanges(address exchangeAddress)
              external
              view
              returns (bool);
          function epochDurationInSeconds()
              external
              view
              returns (uint256);
          function rewardDelegatedStakeWeight()
              external
              view
              returns(uint32);
          function minimumPoolStake()
              external
              view
              returns (uint256);
          function cobbDouglasAlphaNumerator()
              external
              view
              returns (uint32);
          function cobbDouglasAlphaDenominator()
              external
              view
              returns (uint32);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/StakingProxy.sol";
      // solhint-disable no-empty-blocks
      contract TestAssertStorageParams is
          StakingProxy
      {
          struct StorageParams {
              uint256 epochDurationInSeconds;
              uint32 rewardDelegatedStakeWeight;
              uint256 minimumPoolStake;
              uint32 cobbDouglasAlphaNumerator;
              uint32 cobbDouglasAlphaDenominator;
          }
          constructor()
              public
              StakingProxy(NIL_ADDRESS)
          {}
          function setAndAssertParams(StorageParams memory params)
              public
          {
              epochDurationInSeconds = params.epochDurationInSeconds;
              rewardDelegatedStakeWeight = params.rewardDelegatedStakeWeight;
              minimumPoolStake = params.minimumPoolStake;
              cobbDouglasAlphaNumerator = params.cobbDouglasAlphaNumerator;
              cobbDouglasAlphaDenominator = params.cobbDouglasAlphaDenominator;
              assertValidStorageParams();
          }
          function _attachStakingContract(address)
              internal
          {}
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/libs/LibCobbDouglas.sol";
      contract TestCobbDouglas {
          function cobbDouglas(
              uint256 totalRewards,
              uint256 fees,
              uint256 totalFees,
              uint256 stake,
              uint256 totalStake,
              uint32 alphaNumerator,
              uint32 alphaDenominator
          )
              external
              pure
              returns (uint256 rewards)
          {
              rewards = LibCobbDouglas.cobbDouglas(
                  totalRewards,
                  fees,
                  totalFees,
                  stake,
                  totalStake,
                  alphaNumerator,
                  alphaDenominator
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./TestStaking.sol";
      // solhint-disable no-empty-blocks
      contract TestCumulativeRewardTracking is
          TestStaking
      {
          event SetCumulativeReward(
              bytes32 poolId,
              uint256 epoch
          );
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
              TestStaking(
                  wethAddress,
                  zrxVaultAddress
              )
          {}
          function init() public {}
          function _addCumulativeReward(
              bytes32 poolId,
              uint256 reward,
              uint256 stake
          )
              internal
          {
              uint256 lastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              MixinCumulativeRewards._addCumulativeReward(
                  poolId,
                  reward,
                  stake
              );
              uint256 newLastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              if (newLastStoredEpoch != lastStoredEpoch) {
                  emit SetCumulativeReward(poolId, currentEpoch);
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
      import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
      import "../src/Staking.sol";
      contract TestStaking is
          Staking
      {
          address public testWethAddress;
          address public testZrxVaultAddress;
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
          {
              testWethAddress = wethAddress;
              testZrxVaultAddress = zrxVaultAddress;
          }
          /// @dev Sets the weth contract address.
          /// @param wethAddress The address of the weth contract.
          function setWethContract(address wethAddress)
              external
          {
              testWethAddress = wethAddress;
          }
          /// @dev Sets the zrx vault address.
          /// @param zrxVaultAddress The address of a zrx vault.
          function setZrxVault(address zrxVaultAddress)
              external
          {
              testZrxVaultAddress = zrxVaultAddress;
          }
          /// @dev Overridden to use testWethAddress;
          function getWethContract()
              public
              view
              returns (IEtherToken)
          {
              // `testWethAddress` will not be set on the proxy this contract is
              // attached to, so we need to access the storage of the deployed
              // instance of this contract.
              address wethAddress = TestStaking(address(uint160(stakingContract))).testWethAddress();
              return IEtherToken(wethAddress);
          }
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              address zrxVaultAddress = TestStaking(address(uint160(stakingContract))).testZrxVaultAddress();
              zrxVault = IZrxVault(zrxVaultAddress);
              return zrxVault;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestDelegatorRewards is
          TestStakingNoWETH
      {
          event FinalizePool(
              bytes32 poolId,
              uint256 operatorReward,
              uint256 membersReward,
              uint256 membersStake
          );
          struct UnfinalizedPoolReward {
              uint256 operatorReward;
              uint256 membersReward;
              uint256 membersStake;
          }
          constructor() public {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          mapping (uint256 => mapping (bytes32 => UnfinalizedPoolReward)) private
              unfinalizedPoolRewardsByEpoch;
          /// @dev Set unfinalized rewards for a pool in the current epoch.
          function setUnfinalizedPoolReward(
              bytes32 poolId,
              address payable operatorAddress,
              uint256 operatorReward,
              uint256 membersReward,
              uint256 membersStake
          )
              external
          {
              unfinalizedPoolRewardsByEpoch[currentEpoch][poolId] = UnfinalizedPoolReward({
                  operatorReward: operatorReward,
                  membersReward: membersReward,
                  membersStake: membersStake
              });
              // Lazily initialize this pool.
              _poolById[poolId].operator = operatorAddress;
              _setOperatorShare(poolId, operatorReward, membersReward);
          }
          /// @dev Expose/wrap `_syncPoolRewards`.
          function syncPoolRewards(
              bytes32 poolId,
              address payable operatorAddress,
              uint256 operatorReward,
              uint256 membersReward,
              uint256 membersStake
          )
              external
          {
              // Lazily initialize this pool.
              _poolById[poolId].operator = operatorAddress;
              _setOperatorShare(poolId, operatorReward, membersReward);
              _syncPoolRewards(
                  poolId,
                  operatorReward + membersReward,
                  membersStake
              );
          }
          /// @dev Advance the epoch.
          function advanceEpoch() external {
              currentEpoch += 1;
          }
          /// @dev Create and delegate stake to the current epoch.
          ///      Only used to test purportedly unreachable states.
          ///      Also withdraws pending rewards.
          function delegateStakeNow(
              address delegator,
              bytes32 poolId,
              uint256 stake
          )
              external
          {
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
              IStructs.StoredBalance storage _stake = _delegatedStakeToPoolByOwner[delegator][poolId];
              _stake.currentEpochBalance += uint96(stake);
              _stake.nextEpochBalance += uint96(stake);
              _stake.currentEpoch = uint32(currentEpoch);
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
          }
          /// @dev Create and delegate stake that will occur in the next epoch
          ///      (normal behavior).
          ///      Also withdraws pending rewards.
          function delegateStake(
              address delegator,
              bytes32 poolId,
              uint256 stake
          )
              external
          {
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
              IStructs.StoredBalance storage _stake = _delegatedStakeToPoolByOwner[delegator][poolId];
              if (_stake.currentEpoch < currentEpoch) {
                  _stake.currentEpochBalance = _stake.nextEpochBalance;
              }
              _stake.nextEpochBalance += uint96(stake);
              _stake.currentEpoch = uint32(currentEpoch);
          }
          /// @dev Clear stake that will occur in the next epoch
          ///      (normal behavior).
          ///      Also withdraws pending rewards.
          function undelegateStake(
              address delegator,
              bytes32 poolId,
              uint256 stake
          )
              external
          {
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
              IStructs.StoredBalance storage _stake = _delegatedStakeToPoolByOwner[delegator][poolId];
              if (_stake.currentEpoch < currentEpoch) {
                  _stake.currentEpochBalance = _stake.nextEpochBalance;
              }
              _stake.nextEpochBalance -= uint96(stake);
              _stake.currentEpoch = uint32(currentEpoch);
          }
          // solhint-disable no-simple-event-func-name
          /// @dev Overridden to realize `unfinalizedPoolRewardsByEpoch` in
          ///      the current epoch and emit a event,
          function finalizePool(bytes32 poolId)
              external
          {
              UnfinalizedPoolReward memory reward = unfinalizedPoolRewardsByEpoch[currentEpoch][poolId];
              delete unfinalizedPoolRewardsByEpoch[currentEpoch][poolId];
              _setOperatorShare(poolId, reward.operatorReward, reward.membersReward);
              uint256 totalRewards = reward.operatorReward + reward.membersReward;
              uint256 membersStake = reward.membersStake;
              (uint256 operatorReward, uint256 membersReward) =
                  _syncPoolRewards(poolId, totalRewards, membersStake);
              emit FinalizePool(poolId, operatorReward, membersReward, membersStake);
          }
          /// @dev Overridden to use unfinalizedPoolRewardsByEpoch.
          function _getUnfinalizedPoolRewards(bytes32 poolId)
              internal
              view
              returns (
                  uint256 totalReward,
                  uint256 membersStake
              )
          {
              UnfinalizedPoolReward storage reward = unfinalizedPoolRewardsByEpoch[currentEpoch][poolId];
              totalReward = reward.operatorReward + reward.membersReward;
              membersStake = reward.membersStake;
          }
          /// @dev Set the operator share of a pool based on reward ratios.
          function _setOperatorShare(
              bytes32 poolId,
              uint256 operatorReward,
              uint256 membersReward
          )
              private
          {
              uint32 operatorShare = 0;
              uint256 totalReward = operatorReward + membersReward;
              if (totalReward != 0) {
                  operatorShare = uint32(
                      operatorReward * PPM_DENOMINATOR / totalReward
                  );
              }
              _poolById[poolId].operatorShare = operatorShare;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/Staking.sol";
      // solhint-disable no-empty-blocks,no-simple-event-func-name
      /// @dev A version of the staking contract with WETH-related functions
      ///      overridden to do nothing.
      contract TestStakingNoWETH is
          Staking
      {
          event Transfer(
              address indexed _from,
              address indexed _to,
              uint256 _value
          );
          function transfer(address to, uint256 amount)
              external
              returns (bool)
          {
              emit Transfer(address(this), to, amount);
              return true;
          }
          function getWethContract()
              public
              view
              returns (IEtherToken)
          {
              return IEtherToken(address(this));
          }
          function _wrapEth()
              internal
          {}
          function _getAvailableWethBalance()
              internal
              view
              returns (uint256)
          {
              return address(this).balance;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/Staking.sol";
      contract TestExchangeManager is
          Staking
      {
          function setValidExchange(address exchange)
              external
          {
              validExchanges[exchange] = true;
          }
          function onlyExchangeFunction()
              external
              view
              onlyExchange
              returns (bool)
          {
              return true;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "../src/libs/LibCobbDouglas.sol";
      import "./TestStakingNoWETH.sol";
      contract TestFinalizer is
          TestStakingNoWETH
      {
          event DepositStakingPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          );
          struct UnfinalizedPoolReward {
              uint256 totalReward;
              uint256 membersStake;
          }
          struct FinalizedPoolRewards {
              uint256 operatorReward;
              uint256 membersReward;
              uint256 membersStake;
          }
          address payable private _operatorRewardsReceiver;
          address payable private _membersRewardsReceiver;
          mapping (bytes32 => uint32) private _operatorSharesByPool;
          /// @param operatorRewardsReceiver The address to transfer rewards into when
          ///        a pool is finalized.
          constructor(
              address payable operatorRewardsReceiver,
              address payable membersRewardsReceiver
          )
              public
          {
              _addAuthorizedAddress(msg.sender);
              init();
              _operatorRewardsReceiver = operatorRewardsReceiver;
              _membersRewardsReceiver = membersRewardsReceiver;
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          // this contract can receive ETH
          // solhint-disable no-empty-blocks
          function ()
              external
              payable
          {}
          /// @dev Activate a pool in the current epoch.
          function addActivePool(
              bytes32 poolId,
              uint32 operatorShare,
              uint256 feesCollected,
              uint256 membersStake,
              uint256 weightedStake
          )
              external
          {
              require(feesCollected > 0, "FEES_MUST_BE_NONZERO");
              uint256 currentEpoch_ = currentEpoch;
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][currentEpoch_];
              require(poolStats.feesCollected == 0, "POOL_ALREADY_ADDED");
              _operatorSharesByPool[poolId] = operatorShare;
              poolStatsByEpoch[poolId][currentEpoch_] = IStructs.PoolStats({
                  feesCollected: feesCollected,
                  membersStake: membersStake,
                  weightedStake: weightedStake
              });
              aggregatedStatsByEpoch[currentEpoch_].totalFeesCollected += feesCollected;
              aggregatedStatsByEpoch[currentEpoch_].totalWeightedStake += weightedStake;
              aggregatedStatsByEpoch[currentEpoch_].numPoolsToFinalize += 1;
          }
          /// @dev Drain the balance of this contract.
          function drainBalance()
              external
          {
              address(0).transfer(address(this).balance);
          }
          /// @dev Compute Cobb-Douglas.
          function cobbDouglas(
              uint256 totalRewards,
              uint256 ownerFees,
              uint256 totalFees,
              uint256 ownerStake,
              uint256 totalStake
          )
              external
              view
              returns (uint256 ownerRewards)
          {
              ownerRewards = LibCobbDouglas.cobbDouglas(
                  totalRewards,
                  ownerFees,
                  totalFees,
                  ownerStake,
                  totalStake,
                  cobbDouglasAlphaNumerator,
                  cobbDouglasAlphaDenominator
              );
          }
          /// @dev Expose `_getUnfinalizedPoolReward()`
          function getUnfinalizedPoolRewards(bytes32 poolId)
              external
              view
              returns (UnfinalizedPoolReward memory reward)
          {
              (reward.totalReward, reward.membersStake) = _getUnfinalizedPoolRewards(
                  poolId
              );
          }
          /// @dev Expose pool stats for the input epoch.
          function getPoolStatsFromEpoch(uint256 epoch, bytes32 poolId)
              external
              view
              returns (IStructs.PoolStats memory)
          {
              return poolStatsByEpoch[poolId][epoch];
          }
          function getAggregatedStatsForPreviousEpoch()
              external
              view
              returns (IStructs.AggregatedStats memory)
          {
              return aggregatedStatsByEpoch[currentEpoch - 1];
          }
          /// @dev Overridden to log and transfer to receivers.
          function _syncPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              internal
              returns (uint256 operatorReward, uint256 membersReward)
          {
              uint32 operatorShare = _operatorSharesByPool[poolId];
              (operatorReward, membersReward) = _computePoolRewardsSplit(
                  operatorShare,
                  reward,
                  membersStake
              );
              address(_operatorRewardsReceiver).transfer(operatorReward);
              address(_membersRewardsReceiver).transfer(membersReward);
              emit DepositStakingPoolRewards(poolId, reward, membersStake);
          }
          /// @dev Overriden to just increase the epoch counter.
          function _goToNextEpoch() internal {
              currentEpoch += 1;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/immutable/MixinStorage.sol";
      contract TestInitTarget is
          MixinStorage
      {
          // We can't store state in this contract before it is attached, so
          // we will grant this predefined address a balance to indicate that
          // `init()`  should revert.
          address public constant SHOULD_REVERT_ADDRESS = 0x5ed6A38c6bEcEd15b0AB58566b6fD7A00463d2F7;
          // Counter that is incremented with every call to `init()`.
          uint256 private _initCounter = 0;
          // `msg.sender` of the last `init()` call.
          address private _initSender = address(0);
          // `address(this)` of the last `init()` call.
          address private _initThisAddress = address(0);
          function init()
              external
          {
              if (SHOULD_REVERT_ADDRESS.balance != 0) {
                  revert("FORCED_INIT_REVERT");
              }
              _initCounter += 1;
              _initSender = msg.sender;
              _initThisAddress = address(this);
          }
          function getInitState()
              external
              view
              returns (
                  address initSender,
                  address initThisAddress
              )
          {
              initSender = _initSender;
              initThisAddress = _initThisAddress;
          }
          function getInitCounter() external view returns (uint256) {
              return _initCounter;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "../src/libs/LibFixedMath.sol";
      contract TestLibFixedMath {
          function one() external pure returns (int256) {
              return LibFixedMath.one();
          }
          function mulDiv(int256 a, int256 n, int256 d) external pure returns (int256) {
              return LibFixedMath.mulDiv(a, n, d);
          }
          function mul(int256 a, int256 b) external pure returns (int256) {
              return LibFixedMath.mul(a, b);
          }
          function div(int256 a, int256 b) external pure returns (int256) {
              return LibFixedMath.div(a, b);
          }
          function add(int256 a, int256 b) external pure returns (int256) {
              return LibFixedMath.add(a, b);
          }
          function sub(int256 a, int256 b) external pure returns (int256) {
              return LibFixedMath.sub(a, b);
          }
          function uintMul(int256 f, uint256 u) external pure returns (uint256) {
              return LibFixedMath.uintMul(f, u);
          }
          function abs(int256 a) external pure returns (int256) {
              return LibFixedMath.abs(a);
          }
          function invert(int256 a) external pure returns (int256) {
              return LibFixedMath.invert(a);
          }
          function toFixedSigned(int256 n, int256 d) external pure returns (int256) {
              return LibFixedMath.toFixed(n, d);
          }
          function toFixedSigned(int256 n) external pure returns (int256) {
              return LibFixedMath.toFixed(n);
          }
          function toFixedUnsigned(uint256 n, uint256 d) external pure returns (int256) {
              return LibFixedMath.toFixed(n, d);
          }
          function toFixedUnsigned(uint256 n) external pure returns (int256) {
              return LibFixedMath.toFixed(n);
          }
          function toInteger(int256 f) external pure returns (int256) {
              return LibFixedMath.toInteger(f);
          }
          function ln(int256 x) external pure returns (int256 r) {
              return LibFixedMath.ln(x);
          }
          function exp(int256 x) external pure returns (int256 r) {
              return LibFixedMath.exp(x);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "../src/libs/LibSafeDowncast.sol";
      contract TestLibSafeDowncast {
          function downcastToUint96(uint256 a)
              external
              pure
              returns (uint96)
          {
              return LibSafeDowncast.downcastToUint96(a);
          }
          function downcastToUint64(uint256 a)
              external
              pure
              returns (uint64)
          {
              return LibSafeDowncast.downcastToUint64(a);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./TestStaking.sol";
      contract TestMixinCumulativeRewards is
          TestStaking
      {
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
              TestStaking(
                  wethAddress,
                  zrxVaultAddress
              )
          {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          /// @dev Exposes `_isCumulativeRewardSet`
          function isCumulativeRewardSet(IStructs.Fraction memory cumulativeReward)
              public
              pure
              returns (bool)
          {
              return _isCumulativeRewardSet(cumulativeReward);
          }
          /// @dev Exposes `_addCumulativeReward`
          function addCumulativeReward(
              bytes32 poolId,
              uint256 reward,
              uint256 stake
          )
              public
          {
              _addCumulativeReward(poolId, reward, stake);
          }
          /// @dev Exposes `_updateCumulativeReward`
          function updateCumulativeReward(bytes32 poolId)
              public
          {
              _updateCumulativeReward(poolId);
          }
          /// @dev Exposes _computeMemberRewardOverInterval
          function computeMemberRewardOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              public
              view
              returns (uint256 reward)
          {
              return _computeMemberRewardOverInterval(poolId, memberStakeOverInterval, beginEpoch, endEpoch);
          }
          /// @dev Increments current epoch by 1
          function incrementEpoch()
              public
          {
              currentEpoch += 1;
          }
          /// @dev Stores an arbitrary cumulative reward for a given epoch.
          ///      Also sets the `_cumulativeRewardsByPoolLastStored` to the input epoch.
          function storeCumulativeReward(
              bytes32 poolId,
              IStructs.Fraction memory cumulativeReward,
              uint256 epoch
          )
              public
          {
              _cumulativeRewardsByPool[poolId][epoch] = cumulativeReward;
              _cumulativeRewardsByPoolLastStored[poolId] = epoch;
          }
          /// @dev Returns the most recent cumulative reward for a given pool.
          function getMostRecentCumulativeReward(bytes32 poolId)
              public
              returns (IStructs.Fraction memory)
          {
              uint256 mostRecentEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              return _cumulativeRewardsByPool[poolId][mostRecentEpoch];
          }
          /// @dev Returns the raw cumulative reward for a given pool in an epoch.
          ///      This is considered "raw" because the internal implementation
          ///      (_getCumulativeRewardAtEpochRaw) will query other state variables
          ///      to determine the most accurate cumulative reward for a given epoch.
          function getCumulativeRewardAtEpochRaw(bytes32 poolId, uint256 epoch)
              public
              returns (IStructs.Fraction memory)
          {
              return  _cumulativeRewardsByPool[poolId][epoch];
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/sys/MixinParams.sol";
      contract TestMixinParams is
          MixinParams
      {
          bool public shouldFailAssertValidStorageParams;
          /// @dev Set `shouldFailAssertValidStorageParams`
          function setShouldFailAssertValidStorageParams(bool shouldFail)
              external
          {
              shouldFailAssertValidStorageParams = shouldFail;
          }
          /// @dev `IStakingProxy.assertValidStorageParams()` that reverts if
          ///      `shouldFailAssertValidStorageParams` is true.
          function assertValidStorageParams()
              public
              view
          {
              if (shouldFailAssertValidStorageParams) {
                  revert("ASSERT_VALID_STORAGE_PARAMS_FAILED");
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./TestStaking.sol";
      contract TestMixinScheduler is
          TestStaking
      {
          uint256 public testDeployedTimestamp;
          event GoToNextEpochTestInfo(
              uint256 oldEpoch,
              uint256 blockTimestamp
          );
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
              TestStaking(
                  wethAddress,
                  zrxVaultAddress
              )
          {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
              // Record time of deployment
              // solhint-disable-next-line not-rely-on-time
              testDeployedTimestamp = block.timestamp;
          }
          /// @dev Tests `_goToNextEpoch`.
          ///      Configures internal variables such taht `epochEndTime` will be
          ///      less-than, equal-to, or greater-than the block timestamp.
          /// @param epochEndTimeDelta Set to desired `epochEndTime - block.timestamp`
          function goToNextEpochTest(int256 epochEndTimeDelta)
              public
          {
              // solhint-disable-next-line not-rely-on-time
              uint256 blockTimestamp = block.timestamp;
              // Emit info used by client-side test code
              emit GoToNextEpochTestInfo(
                  currentEpoch,
                  blockTimestamp
              );
              // (i) In `_goToNextEpoch` we compute:
              //     `epochEndTime = currentEpochStartTimeInSeconds + epochDurationInSeconds`
              // (ii) We want adjust internal state such that:
              //      `epochEndTime - block.timestamp = epochEndTimeDelta`, or
              //      `currentEpochStartTimeInSeconds + epochDurationInSeconds - block.timestamp = epochEndTimeDelta`
              //
              // To do this, we:
              //  (i) Set `epochDurationInSeconds` to a constant value of 1, and
              //  (ii) Rearrange the eqn above to get:
              //      `currentEpochStartTimeInSeconds = epochEndTimeDelta + block.timestamp - epochDurationInSeconds`
              epochDurationInSeconds = 1;
              currentEpochStartTimeInSeconds =
                  uint256(epochEndTimeDelta + int256(blockTimestamp) - int256(epochDurationInSeconds));
              // Test internal function
              _goToNextEpoch();
          }
          /// @dev Tests `_initMixinScheduler`
          /// @param _currentEpochStartTimeInSeconds Sets `currentEpochStartTimeInSeconds` to this value before test.
          function initMixinSchedulerTest(uint256 _currentEpochStartTimeInSeconds)
              public
          {
              currentEpochStartTimeInSeconds = _currentEpochStartTimeInSeconds;
              _initMixinScheduler();
          }
      }/*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStake is
          TestStakingNoWETH
      {
          event ZrxVaultDepositFrom(
              address staker,
              uint256 amount
          );
          event ZrxVaultWithdrawFrom(
              address staker,
              uint256 amount
          );
          event MoveStakeStorage(
              bytes32 fromBalanceSlot,
              bytes32 toBalanceSlot,
              uint256 amount
          );
          event IncreaseCurrentAndNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event DecreaseCurrentAndNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event IncreaseNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event DecreaseNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event WithdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address delegator
          );
          /// @dev Advance the epoch counter.
          function advanceEpoch() external {
              currentEpoch += 1;
          }
          /// @dev `IZrxVault.depositFrom`
          function depositFrom(address staker, uint256 amount) external {
              emit ZrxVaultDepositFrom(staker, amount);
          }
          /// @dev `IZrxVault.withdrawFrom`
          function withdrawFrom(address staker, uint256 amount) external {
              emit ZrxVaultWithdrawFrom(staker, amount);
          }
          function getDelegatedStakeByPoolIdSlot(bytes32 poolId)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_delegatedStakeByPoolId[poolId]);
          }
          function getDelegatedStakeToPoolByOwnerSlot(bytes32 poolId, address staker)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_delegatedStakeToPoolByOwner[staker][poolId]);
          }
          function getGlobalStakeByStatusSlot(IStructs.StakeStatus status)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_globalStakeByStatus[uint8(status)]);
          }
          function getOwnerStakeByStatusSlot(address owner, IStructs.StakeStatus status)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_ownerStakeByStatus[uint8(status)][owner]);
          }
          /// @dev Set `_ownerStakeByStatus`
          function setOwnerStakeByStatus(
              address owner,
              IStructs.StakeStatus status,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _ownerStakeByStatus[uint8(status)][owner] = stake;
          }
          /// @dev Overridden to use this contract as the ZRX vault.
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              return IZrxVault(address(this));
          }
          /// @dev Overridden to only emit an event.
          function _withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              internal
          {
              emit WithdrawAndSyncDelegatorRewards(poolId, member);
          }
          /// @dev Overridden to only emit an event.
          function _moveStake(
              IStructs.StoredBalance storage fromPtr,
              IStructs.StoredBalance storage toPtr,
              uint256 amount
          )
              internal
          {
              emit MoveStakeStorage(
                  _getPtrSlot(fromPtr),
                  _getPtrSlot(toPtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _increaseCurrentAndNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit IncreaseCurrentAndNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _decreaseCurrentAndNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit DecreaseCurrentAndNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _increaseNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit IncreaseNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _decreaseNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit DecreaseNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to just return the input.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
          }
          /// @dev Throws if poolId == 0x0
          function _assertStakingPoolExists(bytes32 poolId)
              internal
              view
          {
              require(poolId != bytes32(0), "INVALID_POOL");
          }
          // solhint-disable-next-line
          function _getPtrSlot(IStructs.StoredBalance storage ptr)
              private
              pure
              returns (bytes32 offset)
          {
              assembly {
                  offset := ptr_slot
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStakeBalances is
          TestStakingNoWETH
      {
          uint256 private _balanceOfZrxVault;
          mapping (address => uint256) private _zrxBalanceOf;
          function setBalanceOfZrxVault(uint256 balance)
              external
          {
              _balanceOfZrxVault = balance;
          }
          function setZrxBalanceOf(address staker, uint256 balance)
              external
          {
              _zrxBalanceOf[staker] = balance;
          }
          /// @dev `IZrxVault.balanceOfZrxVault`
          function balanceOfZrxVault()
              external
              view
              returns (uint256)
          {
              return _balanceOfZrxVault;
          }
          /// @dev `IZrxVault.balanceOf`
          function balanceOf(address staker)
              external
              view
              returns (uint256)
          {
              return _zrxBalanceOf[staker];
          }
          /// @dev Set `_ownerStakeByStatus`
          function setOwnerStakeByStatus(
              address owner,
              IStructs.StakeStatus status,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _ownerStakeByStatus[uint8(status)][owner] = stake;
          }
          /// @dev Set `_delegatedStakeToPoolByOwner`
          function setDelegatedStakeToPoolByOwner(
              address owner,
              bytes32 poolId,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _delegatedStakeToPoolByOwner[owner][poolId] = stake;
          }
          /// @dev Set `_delegatedStakeByPoolId`
          function setDelegatedStakeByPoolId(
              bytes32 poolId,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _delegatedStakeByPoolId[poolId] = stake;
          }
          /// @dev Set `_globalStakeByStatus`
          function setGlobalStakeByStatus(
              IStructs.StakeStatus status,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _globalStakeByStatus[uint8(status)] = stake;
          }
          /// @dev Overridden to use this contract as the ZRX vault.
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              return IZrxVault(address(this));
          }
          /// @dev Overridden to just return the input with the epoch incremented.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
              balance.currentEpoch += 1;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "../src/stake/MixinStakeStorage.sol";
      contract TestMixinStakeStorage is
          MixinStakeStorage
      {
          mapping (uint256 => IStructs.StoredBalance) public testBalances;
          function setCurrentEpoch(uint256 newEpoch)
              external
          {
              currentEpoch = newEpoch;
          }
          function moveStake(
              uint256 fromIndex,
              uint256 toIndex,
              uint256 amount
          )
              external
          {
              return _moveStake(
                  testBalances[fromIndex],
                  testBalances[toIndex],
                  amount
              );
          }
          function increaseCurrentAndNextBalance(uint256 index, uint256 amount)
              external
          {
              return _increaseCurrentAndNextBalance(testBalances[index], amount);
          }
          function decreaseCurrentAndNextBalance(uint256 index, uint256 amount)
              external
          {
              _decreaseCurrentAndNextBalance(testBalances[index], amount);
          }
          function increaseNextBalance(uint256 index, uint256 amount)
              external
          {
              _increaseNextBalance(testBalances[index], amount);
          }
          function decreaseNextBalance(uint256 index, uint256 amount)
              external
          {
              _decreaseNextBalance(testBalances[index], amount);
          }
          function loadCurrentBalance(uint256 index)
              external
              returns (IStructs.StoredBalance memory balance)
          {
              return _loadCurrentBalance(testBalances[index]);
          }
          function loadStaleBalance(uint256 index)
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              return testBalances[index];
          }
          function setStoredBalance(
              IStructs.StoredBalance memory balance,
              uint256 index
          )
              public
          {
              testBalances[index] = balance;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStakingPool is
          TestStakingNoWETH
      {
          function setLastPoolId(bytes32 poolId)
              external
          {
              lastPoolId = poolId;
          }
          function setPoolIdByMaker(bytes32 poolId, address maker)
              external
          {
              poolIdByMaker[maker] = poolId;
          }
          // solhint-disable no-empty-blocks
          function testOnlyStakingPoolOperatorModifier(bytes32 poolId)
              external
              view
              onlyStakingPoolOperator(poolId)
          {}
          function setPoolById(bytes32 poolId, IStructs.Pool memory pool)
              public
          {
              _poolById[poolId] = pool;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStakingPoolRewards is
          TestStakingNoWETH
      {
          // solhint-disable no-simple-event-func-name
          event UpdateCumulativeReward(
              bytes32 poolId
          );
          event WithdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address delegator
          );
          struct UnfinalizedPoolReward {
              uint256 reward;
              uint256 membersStake;
          }
          constructor() public {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          // Rewards returned by `_computeMemberRewardOverInterval()`, indexed
          // by `_getMemberRewardOverIntervalHash()`.
          mapping (bytes32 => uint256) private _memberRewardsOverInterval;
          // Rewards returned by `_getUnfinalizedPoolRewards()`, indexed by pool ID.
          mapping (bytes32 => UnfinalizedPoolReward) private _unfinalizedPoolRewards;
          // Set pool `rewardsByPoolId`.
          function setPoolRewards(
              bytes32 poolId,
              uint256 _rewardsByPoolId
          )
              external
          {
              rewardsByPoolId[poolId] = _rewardsByPoolId;
          }
          // Set `wethReservedForPoolRewards`.
          function setWethReservedForPoolRewards(
              uint256 _wethReservedForPoolRewards
          )
              external
          {
              wethReservedForPoolRewards = _wethReservedForPoolRewards;
          }
          // Set the rewards returned by a call to `_computeMemberRewardOverInterval()`.
          function setMemberRewardsOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch,
              uint256 reward
          )
              external
          {
              bytes32 rewardHash = _getMemberRewardOverIntervalHash(
                  poolId,
                  memberStakeOverInterval,
                  beginEpoch,
                  endEpoch
              );
              _memberRewardsOverInterval[rewardHash] = reward;
          }
          // Set the rewards returned by `_getUnfinalizedPoolRewards()`.
          function setUnfinalizedPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              external
          {
              _unfinalizedPoolRewards[poolId] = UnfinalizedPoolReward(
                  reward,
                  membersStake
              );
          }
          // Set `currentEpoch`.
          function setCurrentEpoch(uint256 epoch) external {
              currentEpoch = epoch;
          }
          // Expose `_syncPoolRewards()` for testing.
          function syncPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              external
              returns (uint256 operatorReward, uint256 membersReward)
          {
              return _syncPoolRewards(poolId, reward, membersStake);
          }
          // Expose `_withdrawAndSyncDelegatorRewards()` for testing.
          function withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              external
          {
              return _withdrawAndSyncDelegatorRewards(
                  poolId,
                  member
              );
          }
          // Expose `_computePoolRewardsSplit()` for testing.
          function computePoolRewardsSplit(
              uint32 operatorShare,
              uint256 totalReward,
              uint256 membersStake
          )
              external
              pure
              returns (uint256 operatorReward, uint256 membersReward)
          {
              return _computePoolRewardsSplit(
                  operatorShare,
                  totalReward,
                  membersStake
              );
          }
          // Access `_delegatedStakeToPoolByOwner`
          function delegatedStakeToPoolByOwner(address member, bytes32 poolId)
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              return _delegatedStakeToPoolByOwner[member][poolId];
          }
          // Set `_delegatedStakeToPoolByOwner`
          function setDelegatedStakeToPoolByOwner(
              address member,
              bytes32 poolId,
              IStructs.StoredBalance memory balance
          )
              public
          {
              _delegatedStakeToPoolByOwner[member][poolId] = balance;
          }
          // Set `_poolById`.
          function setPool(
              bytes32 poolId,
              IStructs.Pool memory pool
          )
              public
          {
              _poolById[poolId] = pool;
          }
          // Overridden to emit an event.
          function _withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              internal
          {
              emit WithdrawAndSyncDelegatorRewards(poolId, member);
              return MixinStakingPoolRewards._withdrawAndSyncDelegatorRewards(
                  poolId,
                  member
              );
          }
          // Overridden to use `_memberRewardsOverInterval`
          function _computeMemberRewardOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              internal
              view
              returns (uint256 reward)
          {
              bytes32 rewardHash = _getMemberRewardOverIntervalHash(
                  poolId,
                  memberStakeOverInterval,
                  beginEpoch,
                  endEpoch
              );
              return _memberRewardsOverInterval[rewardHash];
          }
          // Overridden to use `_unfinalizedPoolRewards`
          function _getUnfinalizedPoolRewards(
              bytes32 poolId
          )
              internal
              view
              returns (uint256 reward, uint256 membersStake)
          {
              (reward, membersStake) = (
                  _unfinalizedPoolRewards[poolId].reward,
                  _unfinalizedPoolRewards[poolId].membersStake
              );
          }
          // Overridden to just increase `currentEpoch`.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
              balance.currentEpoch += 1;
          }
          // Overridden to revert if a pool has unfinalized rewards.
          function _assertPoolFinalizedLastEpoch(bytes32 poolId)
              internal
              view
          {
              require(
                  _unfinalizedPoolRewards[poolId].membersStake == 0,
                  "POOL_NOT_FINALIZED"
              );
          }
          // Overridden to just emit an event.
          function _updateCumulativeReward(bytes32 poolId)
              internal
          {
              emit UpdateCumulativeReward(poolId);
          }
          // Compute a hash to index `_memberRewardsOverInterval`
          function _getMemberRewardOverIntervalHash(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              private
              pure
              returns (bytes32 rewardHash)
          {
              return keccak256(
                  abi.encode(
                      poolId,
                      memberStakeOverInterval,
                      beginEpoch,
                      endEpoch
                  )
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestProtocolFees is
          TestStakingNoWETH
      {
          struct TestPool {
              uint96 operatorStake;
              uint96 membersStake;
              mapping(address => bool) isMaker;
          }
          event ERC20ProxyTransferFrom(
              address from,
              address to,
              uint256 amount
          );
          mapping(bytes32 => TestPool) private _testPools;
          mapping(address => bytes32) private _makersToTestPoolIds;
          constructor(address exchangeAddress) public {
              _addAuthorizedAddress(msg.sender);
              init();
              validExchanges[exchangeAddress] = true;
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          function advanceEpoch()
              external
          {
              currentEpoch += 1;
          }
          /// @dev Create a test pool.
          function createTestPool(
              bytes32 poolId,
              uint96 operatorStake,
              uint96 membersStake,
              address[] calldata makerAddresses
          )
              external
          {
              TestPool storage pool = _testPools[poolId];
              pool.operatorStake = operatorStake;
              pool.membersStake = membersStake;
              for (uint256 i = 0; i < makerAddresses.length; ++i) {
                  pool.isMaker[makerAddresses[i]] = true;
                  _makersToTestPoolIds[makerAddresses[i]] = poolId;
                  poolIdByMaker[makerAddresses[i]] = poolId;
              }
          }
          /// @dev The ERC20Proxy `transferFrom()` function.
          function transferFrom(
              address from,
              address to,
              uint256 amount
          )
              external
              returns (bool)
          {
              emit ERC20ProxyTransferFrom(from, to, amount);
              return true;
          }
          function getAggregatedStatsForCurrentEpoch()
              external
              view
              returns (IStructs.AggregatedStats memory)
          {
              return aggregatedStatsByEpoch[currentEpoch];
          }
          /// @dev Overridden to use test pools.
          function getStakingPoolIdOfMaker(address makerAddress)
              public
              view
              returns (bytes32)
          {
              return _makersToTestPoolIds[makerAddress];
          }
          /// @dev Overridden to use test pools.
          function getTotalStakeDelegatedToPool(bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              TestPool memory pool = _testPools[poolId];
              uint96 stake = pool.operatorStake + pool.membersStake;
              return IStructs.StoredBalance({
                  currentEpoch: currentEpoch.downcastToUint64(),
                  currentEpochBalance: stake,
                  nextEpochBalance: stake
              });
          }
          /// @dev Overridden to use test pools.
          function getStakeDelegatedToPoolByOwner(address, bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              TestPool memory pool = _testPools[poolId];
              return IStructs.StoredBalance({
                  currentEpoch: currentEpoch.downcastToUint64(),
                  currentEpochBalance: pool.operatorStake,
                  nextEpochBalance: pool.operatorStake
              });
          }
          function getWethContract()
              public
              view
              returns (IEtherToken wethContract)
          {
              return IEtherToken(address(this));
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/Staking.sol";
      contract TestProxyDestination is
          Staking
      {
          // Init will revert if this flag is set to `true`
          bool public initFailFlag;
          /// @dev Emitted when `init` is called
          event InitCalled(
              bool initCalled
          );
          /// @dev returns the input string
          function echo(string calldata val)
              external
              returns (string memory)
          {
              return val;
          }
          /// @dev Just a function that'll do some math on input
          function doMath(uint256 a, uint256 b)
              external
              returns (uint256 sum, uint256 difference)
          {
              return (
                  a + b,
                  a - b
              );
          }
          /// @dev reverts with "Goodbye, World!"
          function die()
              external
          {
              revert("Goodbye, World!");
          }
          /// @dev Called when attached to the StakingProxy.
          ///      Reverts if `initFailFlag` is set, otherwise
          ///      sets storage params and emits `InitCalled`.
          function init()
              public
          {
              if (initFailFlag) {
                  revert("INIT_FAIL_FLAG_SET");
              }
              // Set params such that they'll pass `StakingProxy.assertValidStorageParams`
              epochDurationInSeconds = 5 days;
              cobbDouglasAlphaNumerator = 1;
              cobbDouglasAlphaDenominator = 1;
              rewardDelegatedStakeWeight = PPM_DENOMINATOR;
              minimumPoolStake = 100;
              // Emit event to notify that `init` was called
              emit InitCalled(true);
          }
      }/*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/StakingProxy.sol";
      contract TestStakingProxy is
          StakingProxy
      {
          address public constant SHOULD_REVERT_STAKING_ADDRESS = 0x5ed6A38c6bEcEd15b0AB58566b6fD7A00463d2F7;
          // solhint-disable no-empty-blocks
          constructor(address _stakingContract)
              public
              StakingProxy( _stakingContract)
          {}
          function assertValidStorageParams()
              public
              view
          {
              require(
                  stakingContract != SHOULD_REVERT_STAKING_ADDRESS,
                  "FORCED_STORAGE_PARAMS_REVERT"
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/StakingProxy.sol";
      contract TestStakingProxyUnit is
          StakingProxy
      {
          // Storage Params - these are tested by StakingProxy.assertValidStorageParams.
          struct TestStorageParams {
              uint256 epochDurationInSeconds;
              uint32 cobbDouglasAlphaNumerator;
              uint32 cobbDouglasAlphaDenominator;
              uint32 rewardDelegatedStakeWeight;
              uint256 minimumPoolStake;
          }
          // If this is set then the `init` call will revert in the `TestProxyDestination` contract
          bool public initFailFlag;
          // solhint-disable no-empty-blocks
          constructor(address _stakingContract)
              public
              StakingProxy( _stakingContract)
          {}
          // Setters to modify the
          function setInitFailFlag()
              external
          {
              initFailFlag = true;
          }
          /// @dev Sets storage params with test values
          function setTestStorageParams(TestStorageParams calldata params)
              external
          {
              epochDurationInSeconds = params.epochDurationInSeconds;
              cobbDouglasAlphaNumerator = params.cobbDouglasAlphaNumerator;
              cobbDouglasAlphaDenominator = params.cobbDouglasAlphaDenominator;
              rewardDelegatedStakeWeight = params.rewardDelegatedStakeWeight;
              minimumPoolStake = params.minimumPoolStake;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
      import "@0x/contracts-utils/contracts/src/LibBytes.sol";
      import "../src/Staking.sol";
      contract TestStorageLayoutAndConstants is
          Staking
      {
          using LibBytes for bytes;
          /// @dev Construction will fail if the storage layout or the deployment constants are incompatible
          ///      with the V1 staking proxy.
          constructor() public {
              _assertDeploymentConstants();
              _assertStorageLayout();
          }
          /// @dev This function will fail if the deployment constants change to the point where they
          ///      are considered "invalid".
          function _assertDeploymentConstants()
              internal
              view
          {
              require(
                  address(getWethContract()) != address(0),
                  "WETH_MUST_BE_SET"
              );
              require(
                  address(getZrxVault()) != address(0),
                  "ZRX_VAULT_MUST_BE_SET"
              );
          }
          /// @dev This function will fail if the storage layout of this contract deviates from
          ///      the original staking contract's storage. The use of this function provides assurance
          ///      that regressions from the original storage layout will not occur.
          function _assertStorageLayout()
              internal
              pure
          {
              assembly {
                  let slot := 0x0
                  let offset := 0x0
                  /// Ownable
                  assertSlotAndOffset(
                      owner_slot,
                      owner_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  /// Authorizable
                  assertSlotAndOffset(
                      authorized_slot,
                      authorized_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      authorities_slot,
                      authorities_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  /// MixinStorage
                  assertSlotAndOffset(
                      stakingContract_slot,
                      stakingContract_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _globalStakeByStatus_slot,
                      _globalStakeByStatus_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _ownerStakeByStatus_slot,
                      _ownerStakeByStatus_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _delegatedStakeToPoolByOwner_slot,
                      _delegatedStakeToPoolByOwner_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _delegatedStakeByPoolId_slot,
                      _delegatedStakeByPoolId_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      lastPoolId_slot,
                      lastPoolId_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      poolIdByMaker_slot,
                      poolIdByMaker_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _poolById_slot,
                      _poolById_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      rewardsByPoolId_slot,
                      rewardsByPoolId_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      currentEpoch_slot,
                      currentEpoch_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      currentEpochStartTimeInSeconds_slot,
                      currentEpochStartTimeInSeconds_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _cumulativeRewardsByPool_slot,
                      _cumulativeRewardsByPool_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _cumulativeRewardsByPoolLastStored_slot,
                      _cumulativeRewardsByPoolLastStored_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      validExchanges_slot,
                      validExchanges_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      epochDurationInSeconds_slot,
                      epochDurationInSeconds_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      rewardDelegatedStakeWeight_slot,
                      rewardDelegatedStakeWeight_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      minimumPoolStake_slot,
                      minimumPoolStake_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      cobbDouglasAlphaNumerator_slot,
                      cobbDouglasAlphaNumerator_offset,
                      slot,
                      offset
                  )
                  offset := add(offset, 0x4)
                  // This number will be tightly packed into the previous values storage slot since
                  // they are both `uint32`. Because of this tight packing, the offset of this value
                  // must be 4, since the previous value is a 4 byte number.
                  assertSlotAndOffset(
                      cobbDouglasAlphaDenominator_slot,
                      cobbDouglasAlphaDenominator_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  offset := 0x0
                  assertSlotAndOffset(
                      poolStatsByEpoch_slot,
                      poolStatsByEpoch_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      aggregatedStatsByEpoch_slot,
                      aggregatedStatsByEpoch_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      wethReservedForPoolRewards_slot,
                      wethReservedForPoolRewards_offset,
                      slot,
                      offset
                  )
                  // This assembly function will assert that the actual values for `_slot` and `_offset` are
                  // correct and will revert with a rich error if they are different than the expected values.
                  function assertSlotAndOffset(
                      actual_slot,
                      actual_offset,
                      expected_slot,
                      expected_offset
                  ) {
                      // If expected_slot is not equal to actual_slot, revert with a rich error.
                      if iszero(eq(expected_slot, actual_slot)) {
                          mstore(0x0, 0x213eb13400000000000000000000000000000000000000000000000000000000) // Rich error selector
                          mstore(0x4, 0x0)                                                                // Unexpected slot error code
                          mstore(0x24, expected_slot)                                                     // Expected slot
                          mstore(0x44, actual_slot)                                                       // Actual slot
                          revert(0x0, 0x64)
                      }
                      // If expected_offset is not equal to actual_offset, revert with a rich error.
                      if iszero(eq(expected_offset, actual_offset)) {
                          mstore(0x0, 0x213eb13400000000000000000000000000000000000000000000000000000000) // Rich error selector
                          mstore(0x4, 0x1)                                                                // Unexpected offset error code
                          mstore(0x24, expected_offset)                                                   // Expected offset
                          mstore(0x44, actual_offset)                                                     // Actual offset
                          revert(0x0, 0x64)
                      }
                  }
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./LibBytesRichErrors.sol";
      import "./LibRichErrors.sol";
      library LibBytes {
          using LibBytes for bytes;
          /// @dev Gets the memory address for a byte array.
          /// @param input Byte array to lookup.
          /// @return memoryAddress Memory address of byte array. This
          ///         points to the header of the byte array which contains
          ///         the length.
          function rawAddress(bytes memory input)
              internal
              pure
              returns (uint256 memoryAddress)
          {
              assembly {
                  memoryAddress := input
              }
              return memoryAddress;
          }
          /// @dev Gets the memory address for the contents of a byte array.
          /// @param input Byte array to lookup.
          /// @return memoryAddress Memory address of the contents of the byte array.
          function contentAddress(bytes memory input)
              internal
              pure
              returns (uint256 memoryAddress)
          {
              assembly {
                  memoryAddress := add(input, 32)
              }
              return memoryAddress;
          }
          /// @dev Copies `length` bytes from memory location `source` to `dest`.
          /// @param dest memory address to copy bytes to.
          /// @param source memory address to copy bytes from.
          /// @param length number of bytes to copy.
          function memCopy(
              uint256 dest,
              uint256 source,
              uint256 length
          )
              internal
              pure
          {
              if (length < 32) {
                  // Handle a partial word by reading destination and masking
                  // off the bits we are interested in.
                  // This correctly handles overlap, zero lengths and source == dest
                  assembly {
                      let mask := sub(exp(256, sub(32, length)), 1)
                      let s := and(mload(source), not(mask))
                      let d := and(mload(dest), mask)
                      mstore(dest, or(s, d))
                  }
              } else {
                  // Skip the O(length) loop when source == dest.
                  if (source == dest) {
                      return;
                  }
                  // For large copies we copy whole words at a time. The final
                  // word is aligned to the end of the range (instead of after the
                  // previous) to handle partial words. So a copy will look like this:
                  //
                  //  ####
                  //      ####
                  //          ####
                  //            ####
                  //
                  // We handle overlap in the source and destination range by
                  // changing the copying direction. This prevents us from
                  // overwriting parts of source that we still need to copy.
                  //
                  // This correctly handles source == dest
                  //
                  if (source > dest) {
                      assembly {
                          // We subtract 32 from `sEnd` and `dEnd` because it
                          // is easier to compare with in the loop, and these
                          // are also the addresses we need for copying the
                          // last bytes.
                          length := sub(length, 32)
                          let sEnd := add(source, length)
                          let dEnd := add(dest, length)
                          // Remember the last 32 bytes of source
                          // This needs to be done here and not after the loop
                          // because we may have overwritten the last bytes in
                          // source already due to overlap.
                          let last := mload(sEnd)
                          // Copy whole words front to back
                          // Note: the first check is always true,
                          // this could have been a do-while loop.
                          // solhint-disable-next-line no-empty-blocks
                          for {} lt(source, sEnd) {} {
                              mstore(dest, mload(source))
                              source := add(source, 32)
                              dest := add(dest, 32)
                          }
                          // Write the last 32 bytes
                          mstore(dEnd, last)
                      }
                  } else {
                      assembly {
                          // We subtract 32 from `sEnd` and `dEnd` because those
                          // are the starting points when copying a word at the end.
                          length := sub(length, 32)
                          let sEnd := add(source, length)
                          let dEnd := add(dest, length)
                          // Remember the first 32 bytes of source
                          // This needs to be done here and not after the loop
                          // because we may have overwritten the first bytes in
                          // source already due to overlap.
                          let first := mload(source)
                          // Copy whole words back to front
                          // We use a signed comparisson here to allow dEnd to become
                          // negative (happens when source and dest < 32). Valid
                          // addresses in local memory will never be larger than
                          // 2**255, so they can be safely re-interpreted as signed.
                          // Note: the first check is always true,
                          // this could have been a do-while loop.
                          // solhint-disable-next-line no-empty-blocks
                          for {} slt(dest, dEnd) {} {
                              mstore(dEnd, mload(sEnd))
                              sEnd := sub(sEnd, 32)
                              dEnd := sub(dEnd, 32)
                          }
                          // Write the first 32 bytes
                          mstore(dest, first)
                      }
                  }
              }
          }
          /// @dev Returns a slices from a byte array.
          /// @param b The byte array to take a slice from.
          /// @param from The starting index for the slice (inclusive).
          /// @param to The final index for the slice (exclusive).
          /// @return result The slice containing bytes at indices [from, to)
          function slice(
              bytes memory b,
              uint256 from,
              uint256 to
          )
              internal
              pure
              returns (bytes memory result)
          {
              // Ensure that the from and to positions are valid positions for a slice within
              // the byte array that is being used.
              if (from > to) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
                      from,
                      to
                  ));
              }
              if (to > b.length) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
                      to,
                      b.length
                  ));
              }
              // Create a new bytes structure and copy contents
              result = new bytes(to - from);
              memCopy(
                  result.contentAddress(),
                  b.contentAddress() + from,
                  result.length
              );
              return result;
          }
          /// @dev Returns a slice from a byte array without preserving the input.
          /// @param b The byte array to take a slice from. Will be destroyed in the process.
          /// @param from The starting index for the slice (inclusive).
          /// @param to The final index for the slice (exclusive).
          /// @return result The slice containing bytes at indices [from, to)
          /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
          function sliceDestructive(
              bytes memory b,
              uint256 from,
              uint256 to
          )
              internal
              pure
              returns (bytes memory result)
          {
              // Ensure that the from and to positions are valid positions for a slice within
              // the byte array that is being used.
              if (from > to) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
                      from,
                      to
                  ));
              }
              if (to > b.length) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
                      to,
                      b.length
                  ));
              }
              // Create a new bytes structure around [from, to) in-place.
              assembly {
                  result := add(b, from)
                  mstore(result, sub(to, from))
              }
              return result;
          }
          /// @dev Pops the last byte off of a byte array by modifying its length.
          /// @param b Byte array that will be modified.
          /// @return The byte that was popped off.
          function popLastByte(bytes memory b)
              internal
              pure
              returns (bytes1 result)
          {
              if (b.length == 0) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
                      b.length,
                      0
                  ));
              }
              // Store last byte.
              result = b[b.length - 1];
              assembly {
                  // Decrement length of byte array.
                  let newLen := sub(mload(b), 1)
                  mstore(b, newLen)
              }
              return result;
          }
          /// @dev Tests equality of two byte arrays.
          /// @param lhs First byte array to compare.
          /// @param rhs Second byte array to compare.
          /// @return True if arrays are the same. False otherwise.
          function equals(
              bytes memory lhs,
              bytes memory rhs
          )
              internal
              pure
              returns (bool equal)
          {
              // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
              // We early exit on unequal lengths, but keccak would also correctly
              // handle this.
              return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
          }
          /// @dev Reads an address from a position in a byte array.
          /// @param b Byte array containing an address.
          /// @param index Index in byte array of address.
          /// @return address from byte array.
          function readAddress(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (address result)
          {
              if (b.length < index + 20) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
                      b.length,
                      index + 20 // 20 is length of address
                  ));
              }
              // Add offset to index:
              // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
              // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
              index += 20;
              // Read address from array memory
              assembly {
                  // 1. Add index to address of bytes array
                  // 2. Load 32-byte word from memory
                  // 3. Apply 20-byte mask to obtain address
                  result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
              }
              return result;
          }
          /// @dev Writes an address into a specific position in a byte array.
          /// @param b Byte array to insert address into.
          /// @param index Index in byte array of address.
          /// @param input Address to put into byte array.
          function writeAddress(
              bytes memory b,
              uint256 index,
              address input
          )
              internal
              pure
          {
              if (b.length < index + 20) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
                      b.length,
                      index + 20 // 20 is length of address
                  ));
              }
              // Add offset to index:
              // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
              // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
              index += 20;
              // Store address into array memory
              assembly {
                  // The address occupies 20 bytes and mstore stores 32 bytes.
                  // First fetch the 32-byte word where we'll be storing the address, then
                  // apply a mask so we have only the bytes in the word that the address will not occupy.
                  // Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
                  // 1. Add index to address of bytes array
                  // 2. Load 32-byte word from memory
                  // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
                  let neighbors := and(
                      mload(add(b, index)),
                      0xffffffffffffffffffffffff0000000000000000000000000000000000000000
                  )
                  // Make sure input address is clean.
                  // (Solidity does not guarantee this)
                  input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
                  // Store the neighbors and address into memory
                  mstore(add(b, index), xor(input, neighbors))
              }
          }
          /// @dev Reads a bytes32 value from a position in a byte array.
          /// @param b Byte array containing a bytes32 value.
          /// @param index Index in byte array of bytes32 value.
          /// @return bytes32 value from byte array.
          function readBytes32(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (bytes32 result)
          {
              if (b.length < index + 32) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
                      b.length,
                      index + 32
                  ));
              }
              // Arrays are prefixed by a 256 bit length parameter
              index += 32;
              // Read the bytes32 from array memory
              assembly {
                  result := mload(add(b, index))
              }
              return result;
          }
          /// @dev Writes a bytes32 into a specific position in a byte array.
          /// @param b Byte array to insert <input> into.
          /// @param index Index in byte array of <input>.
          /// @param input bytes32 to put into byte array.
          function writeBytes32(
              bytes memory b,
              uint256 index,
              bytes32 input
          )
              internal
              pure
          {
              if (b.length < index + 32) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
                      b.length,
                      index + 32
                  ));
              }
              // Arrays are prefixed by a 256 bit length parameter
              index += 32;
              // Read the bytes32 from array memory
              assembly {
                  mstore(add(b, index), input)
              }
          }
          /// @dev Reads a uint256 value from a position in a byte array.
          /// @param b Byte array containing a uint256 value.
          /// @param index Index in byte array of uint256 value.
          /// @return uint256 value from byte array.
          function readUint256(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (uint256 result)
          {
              result = uint256(readBytes32(b, index));
              return result;
          }
          /// @dev Writes a uint256 into a specific position in a byte array.
          /// @param b Byte array to insert <input> into.
          /// @param index Index in byte array of <input>.
          /// @param input uint256 to put into byte array.
          function writeUint256(
              bytes memory b,
              uint256 index,
              uint256 input
          )
              internal
              pure
          {
              writeBytes32(b, index, bytes32(input));
          }
          /// @dev Reads an unpadded bytes4 value from a position in a byte array.
          /// @param b Byte array containing a bytes4 value.
          /// @param index Index in byte array of bytes4 value.
          /// @return bytes4 value from byte array.
          function readBytes4(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (bytes4 result)
          {
              if (b.length < index + 4) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
                      b.length,
                      index + 4
                  ));
              }
              // Arrays are prefixed by a 32 byte length field
              index += 32;
              // Read the bytes4 from array memory
              assembly {
                  result := mload(add(b, index))
                  // Solidity does not require us to clean the trailing bytes.
                  // We do it anyway
                  result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
              }
              return result;
          }
          /// @dev Writes a new length to a byte array.
          ///      Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
          ///      Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
          /// @param b Bytes array to write new length to.
          /// @param length New length of byte array.
          function writeLength(bytes memory b, uint256 length)
              internal
              pure
          {
              assembly {
                  mstore(b, length)
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      library LibBytesRichErrors {
          enum InvalidByteOperationErrorCodes {
              FromLessThanOrEqualsToRequired,
              ToLessThanOrEqualsLengthRequired,
              LengthGreaterThanZeroRequired,
              LengthGreaterThanOrEqualsFourRequired,
              LengthGreaterThanOrEqualsTwentyRequired,
              LengthGreaterThanOrEqualsThirtyTwoRequired,
              LengthGreaterThanOrEqualsNestedBytesLengthRequired,
              DestinationLengthGreaterThanOrEqualSourceLengthRequired
          }
          // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
          bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
              0x28006595;
          // solhint-disable func-name-mixedcase
          function InvalidByteOperationError(
              InvalidByteOperationErrorCodes errorCode,
              uint256 offset,
              uint256 required
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INVALID_BYTE_OPERATION_ERROR_SELECTOR,
                  errorCode,
                  offset,
                  required
              );
          }
      }
      

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

      File 3 of 3: Staking
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./interfaces/IStaking.sol";
      import "./sys/MixinParams.sol";
      import "./stake/MixinStake.sol";
      import "./fees/MixinExchangeFees.sol";
      contract Staking is
          IStaking,
          MixinParams,
          MixinStake,
          MixinExchangeFees
      {
          /// @dev Initialize storage owned by this contract.
          ///      This function should not be called directly.
          ///      The StakingProxy contract will call it in `attachStakingContract()`.
          function init()
              public
              onlyAuthorized
          {
              // DANGER! When performing upgrades, take care to modify this logic
              // to prevent accidentally clearing prior state.
              _initMixinScheduler();
              _initMixinParams();
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
      import "./IStructs.sol";
      import "./IZrxVault.sol";
      interface IStaking {
          /// @dev Adds a new exchange address
          /// @param addr Address of exchange contract to add
          function addExchangeAddress(address addr)
              external;
          /// @dev Create a new staking pool. The sender will be the operator of this pool.
          /// Note that an operator must be payable.
          /// @param operatorShare Portion of rewards owned by the operator, in ppm.
          /// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true.
          /// @return poolId The unique pool id generated for this pool.
          function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker)
              external
              returns (bytes32 poolId);
          /// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
          /// @param poolId Unique Id of pool.
          /// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
          function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
              external;
          /// @dev Begins a new epoch, preparing the prior one for finalization.
          ///      Throws if not enough time has passed between epochs or if the
          ///      previous epoch was not fully finalized.
          /// @return numPoolsToFinalize The number of unfinalized pools.
          function endEpoch()
              external
              returns (uint256);
          /// @dev Instantly finalizes a single pool that earned rewards in the previous
          ///      epoch, crediting it rewards for members and withdrawing operator's
          ///      rewards as WETH. This can be called by internal functions that need
          ///      to finalize a pool immediately. Does nothing if the pool is already
          ///      finalized or did not earn rewards in the previous epoch.
          /// @param poolId The pool ID to finalize.
          function finalizePool(bytes32 poolId)
              external;
          /// @dev Initialize storage owned by this contract.
          ///      This function should not be called directly.
          ///      The StakingProxy contract will call it in `attachStakingContract()`.
          function init()
              external;
          /// @dev Allows caller to join a staking pool as a maker.
          /// @param poolId Unique id of pool.
          function joinStakingPoolAsMaker(bytes32 poolId)
              external;
          /// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
          ///      Delegated stake can also be moved between pools.
          ///      This change comes into effect next epoch.
          /// @param from status to move stake out of.
          /// @param to status to move stake into.
          /// @param amount of stake to move.
          function moveStake(
              IStructs.StakeInfo calldata from,
              IStructs.StakeInfo calldata to,
              uint256 amount
          )
              external;
          /// @dev Pays a protocol fee in ETH.
          /// @param makerAddress The address of the order's maker.
          /// @param payerAddress The address that is responsible for paying the protocol fee.
          /// @param protocolFee The amount of protocol fees that should be paid.
          function payProtocolFee(
              address makerAddress,
              address payerAddress,
              uint256 protocolFee
          )
              external
              payable;
          /// @dev Removes an existing exchange address
          /// @param addr Address of exchange contract to remove
          function removeExchangeAddress(address addr)
              external;
          /// @dev Set all configurable parameters at once.
          /// @param _epochDurationInSeconds Minimum seconds between epochs.
          /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function setParams(
              uint256 _epochDurationInSeconds,
              uint32 _rewardDelegatedStakeWeight,
              uint256 _minimumPoolStake,
              uint32 _cobbDouglasAlphaNumerator,
              uint32 _cobbDouglasAlphaDenominator
          )
              external;
          /// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
          ///      Unstake to retrieve the ZRX. Stake is in the 'Active' status.
          /// @param amount of ZRX to stake.
          function stake(uint256 amount)
              external;
          /// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
          ///      the staker. Stake must be in the 'undelegated' status in both the
          ///      current and next epoch in order to be unstaked.
          /// @param amount of ZRX to unstake.
          function unstake(uint256 amount)
              external;
          /// @dev Withdraws the caller's WETH rewards that have accumulated
          ///      until the last epoch.
          /// @param poolId Unique id of pool.
          function withdrawDelegatorRewards(bytes32 poolId)
              external;
          /// @dev Computes the reward balance in ETH of a specific member of a pool.
          /// @param poolId Unique id of pool.
          /// @param member The member of the pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfDelegator(bytes32 poolId, address member)
              external
              view
              returns (uint256 reward);
          /// @dev Computes the reward balance in ETH of the operator of a pool.
          /// @param poolId Unique id of pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfOperator(bytes32 poolId)
              external
              view
              returns (uint256 reward);
          /// @dev Returns the earliest end time in seconds of this epoch.
          ///      The next epoch can begin once this time is reached.
          ///      Epoch period = [startTimeInSeconds..endTimeInSeconds)
          /// @return Time in seconds.
          function getCurrentEpochEarliestEndTimeInSeconds()
              external
              view
              returns (uint256);
          /// @dev Gets global stake for a given status.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Global stake for given status.
          function getGlobalStakeByStatus(IStructs.StakeStatus stakeStatus)
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev Gets an owner's stake balances by status.
          /// @param staker Owner of stake.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Owner's stake balances for given status.
          function getOwnerStakeByStatus(
              address staker,
              IStructs.StakeStatus stakeStatus
          )
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev Retrieves all configurable parameter values.
          /// @return _epochDurationInSeconds Minimum seconds between epochs.
          /// @return _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @return _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @return _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @return _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function getParams()
              external
              view
              returns (
                  uint256 _epochDurationInSeconds,
                  uint32 _rewardDelegatedStakeWeight,
                  uint256 _minimumPoolStake,
                  uint32 _cobbDouglasAlphaNumerator,
                  uint32 _cobbDouglasAlphaDenominator
              );
          /// @param staker of stake.
          /// @param poolId Unique Id of pool.
          /// @return Stake delegated to pool by staker.
          function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId)
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev Returns a staking pool
          /// @param poolId Unique id of pool.
          function getStakingPool(bytes32 poolId)
              external
              view
              returns (IStructs.Pool memory);
          /// @dev Get stats on a staking pool in this epoch.
          /// @param poolId Pool Id to query.
          /// @return PoolStats struct for pool id.
          function getStakingPoolStatsThisEpoch(bytes32 poolId)
              external
              view
              returns (IStructs.PoolStats memory);
          /// @dev Returns the total stake delegated to a specific staking pool,
          ///      across all members.
          /// @param poolId Unique Id of pool.
          /// @return Total stake delegated to pool.
          function getTotalStakeDelegatedToPool(bytes32 poolId)
              external
              view
              returns (IStructs.StoredBalance memory balance);
          /// @dev An overridable way to access the deployed WETH contract.
          ///      Must be view to allow overrides to access state.
          /// @return wethContract The WETH contract instance.
          function getWethContract()
              external
              view
              returns (IEtherToken wethContract);
          /// @dev An overridable way to access the deployed zrxVault.
          ///      Must be view to allow overrides to access state.
          /// @return zrxVault The zrxVault contract.
          function getZrxVault()
              external
              view
              returns (IZrxVault zrxVault);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./IERC20Token.sol";
      contract IEtherToken is
          IERC20Token
      {
          function deposit()
              public
              payable;
          
          function withdraw(uint256 amount)
              public;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract IERC20Token {
          // solhint-disable no-simple-event-func-name
          event Transfer(
              address indexed _from,
              address indexed _to,
              uint256 _value
          );
          event Approval(
              address indexed _owner,
              address indexed _spender,
              uint256 _value
          );
          /// @dev send `value` token to `to` from `msg.sender`
          /// @param _to The address of the recipient
          /// @param _value The amount of token to be transferred
          /// @return True if transfer was successful
          function transfer(address _to, uint256 _value)
              external
              returns (bool);
          /// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
          /// @param _from The address of the sender
          /// @param _to The address of the recipient
          /// @param _value The amount of token to be transferred
          /// @return True if transfer was successful
          function transferFrom(
              address _from,
              address _to,
              uint256 _value
          )
              external
              returns (bool);
          /// @dev `msg.sender` approves `_spender` to spend `_value` tokens
          /// @param _spender The address of the account able to transfer the tokens
          /// @param _value The amount of wei to be approved for transfer
          /// @return Always true if the call has enough gas to complete execution
          function approve(address _spender, uint256 _value)
              external
              returns (bool);
          /// @dev Query total supply of token
          /// @return Total supply of token
          function totalSupply()
              external
              view
              returns (uint256);
          /// @param _owner The address from which the balance will be retrieved
          /// @return Balance of owner
          function balanceOf(address _owner)
              external
              view
              returns (uint256);
          /// @param _owner The address of the account owning tokens
          /// @param _spender The address of the account able to transfer the tokens
          /// @return Amount of remaining tokens allowed to spent
          function allowance(address _owner, address _spender)
              external
              view
              returns (uint256);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      interface IStructs {
          /// @dev Stats for a pool that earned rewards.
          /// @param feesCollected Fees collected in ETH by this pool.
          /// @param weightedStake Amount of weighted stake in the pool.
          /// @param membersStake Amount of non-operator stake in the pool.
          struct PoolStats {
              uint256 feesCollected;
              uint256 weightedStake;
              uint256 membersStake;
          }
          /// @dev Holds stats aggregated across a set of pools.
          /// @param rewardsAvailable Rewards (ETH) available to the epoch
          ///        being finalized (the previous epoch). This is simply the balance
          ///        of the contract at the end of the epoch.
          /// @param numPoolsToFinalize The number of pools that have yet to be finalized through `finalizePools()`.
          /// @param totalFeesCollected The total fees collected for the epoch being finalized.
          /// @param totalWeightedStake The total fees collected for the epoch being finalized.
          /// @param totalRewardsFinalized Amount of rewards that have been paid during finalization.
          struct AggregatedStats {
              uint256 rewardsAvailable;
              uint256 numPoolsToFinalize;
              uint256 totalFeesCollected;
              uint256 totalWeightedStake;
              uint256 totalRewardsFinalized;
          }
          /// @dev Encapsulates a balance for the current and next epochs.
          /// Note that these balances may be stale if the current epoch
          /// is greater than `currentEpoch`.
          /// @param currentEpoch the current epoch
          /// @param currentEpochBalance balance in the current epoch.
          /// @param nextEpochBalance balance in `currentEpoch+1`.
          struct StoredBalance {
              uint64 currentEpoch;
              uint96 currentEpochBalance;
              uint96 nextEpochBalance;
          }
          /// @dev Statuses that stake can exist in.
          ///      Any stake can be (re)delegated effective at the next epoch
          ///      Undelegated stake can be withdrawn if it is available in both the current and next epoch
          enum StakeStatus {
              UNDELEGATED,
              DELEGATED
          }
          /// @dev Info used to describe a status.
          /// @param status of the stake.
          /// @param poolId Unique Id of pool. This is set when status=DELEGATED.
          struct StakeInfo {
              StakeStatus status;
              bytes32 poolId;
          }
          /// @dev Struct to represent a fraction.
          /// @param numerator of fraction.
          /// @param denominator of fraction.
          struct Fraction {
              uint256 numerator;
              uint256 denominator;
          }
          /// @dev Holds the metadata for a staking pool.
          /// @param operator of the pool.
          /// @param operatorShare Fraction of the total balance owned by the operator, in ppm.
          struct Pool {
              address operator;
              uint32 operatorShare;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      interface IZrxVault {
          /// @dev Emmitted whenever a StakingProxy is set in a vault.
          event StakingProxySet(address stakingProxyAddress);
          /// @dev Emitted when the Staking contract is put into Catastrophic Failure Mode
          /// @param sender Address of sender (`msg.sender`)
          event InCatastrophicFailureMode(address sender);
          /// @dev Emitted when Zrx Tokens are deposited into the vault.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens deposited.
          event Deposit(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted when Zrx Tokens are withdrawn from the vault.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens withdrawn.
          event Withdraw(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted whenever the ZRX AssetProxy is set.
          event ZrxProxySet(address zrxProxyAddress);
          /// @dev Sets the address of the StakingProxy contract.
          /// Note that only the contract staker can call this function.
          /// @param _stakingProxyAddress Address of Staking proxy contract.
          function setStakingProxy(address _stakingProxyAddress)
              external;
          /// @dev Vault enters into Catastrophic Failure Mode.
          /// *** WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! ***
          /// Note that only the contract staker can call this function.
          function enterCatastrophicFailure()
              external;
          /// @dev Sets the Zrx proxy.
          /// Note that only the contract staker can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param zrxProxyAddress Address of the 0x Zrx Proxy.
          function setZrxProxy(address zrxProxyAddress)
              external;
          /// @dev Deposit an `amount` of Zrx Tokens from `staker` into the vault.
          /// Note that only the Staking contract can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to deposit.
          function depositFrom(address staker, uint256 amount)
              external;
          /// @dev Withdraw an `amount` of Zrx Tokens to `staker` from the vault.
          /// Note that only the Staking contract can call this.
          /// Note that this can only be called when *not* in Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          /// @param amount of Zrx Tokens to withdraw.
          function withdrawFrom(address staker, uint256 amount)
              external;
          /// @dev Withdraw ALL Zrx Tokens to `staker` from the vault.
          /// Note that this can only be called when *in* Catastrophic Failure mode.
          /// @param staker of Zrx Tokens.
          function withdrawAllFrom(address staker)
              external
              returns (uint256);
          /// @dev Returns the balance in Zrx Tokens of the `staker`
          /// @return Balance in Zrx.
          function balanceOf(address staker)
              external
              view
              returns (uint256);
          /// @dev Returns the entire balance of Zrx tokens in the vault.
          function balanceOfZrxVault()
              external
              view
              returns (uint256);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "../immutable/MixinStorage.sol";
      import "../immutable/MixinConstants.sol";
      import "../interfaces/IStakingEvents.sol";
      import "../interfaces/IStakingProxy.sol";
      import "../libs/LibStakingRichErrors.sol";
      contract MixinParams is
          IStakingEvents,
          MixinStorage,
          MixinConstants
      {
          /// @dev Set all configurable parameters at once.
          /// @param _epochDurationInSeconds Minimum seconds between epochs.
          /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function setParams(
              uint256 _epochDurationInSeconds,
              uint32 _rewardDelegatedStakeWeight,
              uint256 _minimumPoolStake,
              uint32 _cobbDouglasAlphaNumerator,
              uint32 _cobbDouglasAlphaDenominator
          )
              external
              onlyAuthorized
          {
              _setParams(
                  _epochDurationInSeconds,
                  _rewardDelegatedStakeWeight,
                  _minimumPoolStake,
                  _cobbDouglasAlphaNumerator,
                  _cobbDouglasAlphaDenominator
              );
              // Let the staking proxy enforce that these parameters are within
              // acceptable ranges.
              IStakingProxy(address(this)).assertValidStorageParams();
          }
          /// @dev Retrieves all configurable parameter values.
          /// @return _epochDurationInSeconds Minimum seconds between epochs.
          /// @return _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @return _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @return _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @return _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function getParams()
              external
              view
              returns (
                  uint256 _epochDurationInSeconds,
                  uint32 _rewardDelegatedStakeWeight,
                  uint256 _minimumPoolStake,
                  uint32 _cobbDouglasAlphaNumerator,
                  uint32 _cobbDouglasAlphaDenominator
              )
          {
              _epochDurationInSeconds = epochDurationInSeconds;
              _rewardDelegatedStakeWeight = rewardDelegatedStakeWeight;
              _minimumPoolStake = minimumPoolStake;
              _cobbDouglasAlphaNumerator = cobbDouglasAlphaNumerator;
              _cobbDouglasAlphaDenominator = cobbDouglasAlphaDenominator;
          }
          /// @dev Initialize storage belonging to this mixin.
          function _initMixinParams()
              internal
          {
              // Ensure state is uninitialized.
              _assertParamsNotInitialized();
              // Set up defaults.
              uint256 _epochDurationInSeconds = 10 days;
              uint32 _rewardDelegatedStakeWeight = (90 * PPM_DENOMINATOR) / 100;
              uint256 _minimumPoolStake = 100 * MIN_TOKEN_VALUE;
              uint32 _cobbDouglasAlphaNumerator = 2;
              uint32 _cobbDouglasAlphaDenominator = 3;
              _setParams(
                  _epochDurationInSeconds,
                  _rewardDelegatedStakeWeight,
                  _minimumPoolStake,
                  _cobbDouglasAlphaNumerator,
                  _cobbDouglasAlphaDenominator
              );
          }
          /// @dev Asserts that upgradable storage has not yet been initialized.
          function _assertParamsNotInitialized()
              internal
              view
          {
              if (epochDurationInSeconds != 0 &&
                  rewardDelegatedStakeWeight != 0 &&
                  minimumPoolStake != 0 &&
                  cobbDouglasAlphaNumerator != 0 &&
                  cobbDouglasAlphaDenominator != 0
              ) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InitializationError(
                          LibStakingRichErrors.InitializationErrorCodes.MixinParamsAlreadyInitialized
                      )
                  );
              }
          }
          /// @dev Set all configurable parameters at once.
          /// @param _epochDurationInSeconds Minimum seconds between epochs.
          /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          function _setParams(
              uint256 _epochDurationInSeconds,
              uint32 _rewardDelegatedStakeWeight,
              uint256 _minimumPoolStake,
              uint32 _cobbDouglasAlphaNumerator,
              uint32 _cobbDouglasAlphaDenominator
          )
              private
          {
              epochDurationInSeconds = _epochDurationInSeconds;
              rewardDelegatedStakeWeight = _rewardDelegatedStakeWeight;
              minimumPoolStake = _minimumPoolStake;
              cobbDouglasAlphaNumerator = _cobbDouglasAlphaNumerator;
              cobbDouglasAlphaDenominator = _cobbDouglasAlphaDenominator;
              emit ParamsSet(
                  _epochDurationInSeconds,
                  _rewardDelegatedStakeWeight,
                  _minimumPoolStake,
                  _cobbDouglasAlphaNumerator,
                  _cobbDouglasAlphaDenominator
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      library LibRichErrors {
          // bytes4(keccak256("Error(string)"))
          bytes4 internal constant STANDARD_ERROR_SELECTOR =
              0x08c379a0;
          // solhint-disable func-name-mixedcase
          /// @dev ABI encode a standard, string revert error payload.
          ///      This is the same payload that would be included by a `revert(string)`
          ///      solidity statement. It has the function signature `Error(string)`.
          /// @param message The error string.
          /// @return The ABI encoded error.
          function StandardError(
              string memory message
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  STANDARD_ERROR_SELECTOR,
                  bytes(message)
              );
          }
          // solhint-enable func-name-mixedcase
          /// @dev Reverts an encoded rich revert reason `errorData`.
          /// @param errorData ABI encoded error data.
          function rrevert(bytes memory errorData)
              internal
              pure
          {
              assembly {
                  revert(add(errorData, 0x20), mload(errorData))
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/Authorizable.sol";
      import "./MixinConstants.sol";
      import "../interfaces/IZrxVault.sol";
      import "../interfaces/IStructs.sol";
      import "../libs/LibStakingRichErrors.sol";
      // solhint-disable max-states-count, no-empty-blocks
      contract MixinStorage is
          Authorizable
      {
          // address of staking contract
          address public stakingContract;
          // mapping from StakeStatus to global stored balance
          // NOTE: only Status.DELEGATED is used to access this mapping, but this format
          // is used for extensibility
          mapping (uint8 => IStructs.StoredBalance) internal _globalStakeByStatus;
          // mapping from StakeStatus to address of staker to stored balance
          mapping (uint8 => mapping (address => IStructs.StoredBalance)) internal _ownerStakeByStatus;
          // Mapping from Owner to Pool Id to Amount Delegated
          mapping (address => mapping (bytes32 => IStructs.StoredBalance)) internal _delegatedStakeToPoolByOwner;
          // Mapping from Pool Id to Amount Delegated
          mapping (bytes32 => IStructs.StoredBalance) internal _delegatedStakeByPoolId;
          // tracking Pool Id, a unique identifier for each staking pool.
          bytes32 public lastPoolId;
          // mapping from Maker Address to Pool Id of maker
          mapping (address => bytes32) public poolIdByMaker;
          // mapping from Pool Id to Pool
          mapping (bytes32 => IStructs.Pool) internal _poolById;
          // mapping from PoolId to balance of members
          mapping (bytes32 => uint256) public rewardsByPoolId;
          // current epoch
          uint256 public currentEpoch;
          // current epoch start time
          uint256 public currentEpochStartTimeInSeconds;
          // mapping from Pool Id to Epoch to Reward Ratio
          mapping (bytes32 => mapping (uint256 => IStructs.Fraction)) internal _cumulativeRewardsByPool;
          // mapping from Pool Id to Epoch
          mapping (bytes32 => uint256) internal _cumulativeRewardsByPoolLastStored;
          // registered 0x Exchange contracts
          mapping (address => bool) public validExchanges;
          /* Tweakable parameters */
          // Minimum seconds between epochs.
          uint256 public epochDurationInSeconds;
          // How much delegated stake is weighted vs operator stake, in ppm.
          uint32 public rewardDelegatedStakeWeight;
          // Minimum amount of stake required in a pool to collect rewards.
          uint256 public minimumPoolStake;
          // Numerator for cobb douglas alpha factor.
          uint32 public cobbDouglasAlphaNumerator;
          // Denominator for cobb douglas alpha factor.
          uint32 public cobbDouglasAlphaDenominator;
          /* State for finalization */
          /// @dev Stats for each pool that generated fees with sufficient stake to earn rewards.
          ///      See `_minimumPoolStake` in MixinParams.
          mapping (bytes32 => mapping (uint256 => IStructs.PoolStats)) public poolStatsByEpoch;
          /// @dev Aggregated stats across all pools that generated fees with sufficient stake to earn rewards.
          ///      See `_minimumPoolStake` in MixinParams.
          mapping (uint256 => IStructs.AggregatedStats) public aggregatedStatsByEpoch;
          /// @dev The WETH balance of this contract that is reserved for pool reward payouts.
          uint256 public wethReservedForPoolRewards;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./interfaces/IAuthorizable.sol";
      import "./LibAuthorizableRichErrors.sol";
      import "./LibRichErrors.sol";
      import "./Ownable.sol";
      // solhint-disable no-empty-blocks
      contract Authorizable is
          Ownable,
          IAuthorizable
      {
          /// @dev Only authorized addresses can invoke functions with this modifier.
          modifier onlyAuthorized {
              _assertSenderIsAuthorized();
              _;
          }
          mapping (address => bool) public authorized;
          address[] public authorities;
          /// @dev Initializes the `owner` address.
          constructor()
              public
              Ownable()
          {}
          /// @dev Authorizes an address.
          /// @param target Address to authorize.
          function addAuthorizedAddress(address target)
              external
              onlyOwner
          {
              _addAuthorizedAddress(target);
          }
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          function removeAuthorizedAddress(address target)
              external
              onlyOwner
          {
              if (!authorized[target]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetNotAuthorizedError(target));
              }
              for (uint256 i = 0; i < authorities.length; i++) {
                  if (authorities[i] == target) {
                      _removeAuthorizedAddressAtIndex(target, i);
                      break;
                  }
              }
          }
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          /// @param index Index of target in authorities array.
          function removeAuthorizedAddressAtIndex(
              address target,
              uint256 index
          )
              external
              onlyOwner
          {
              _removeAuthorizedAddressAtIndex(target, index);
          }
          /// @dev Gets all authorized addresses.
          /// @return Array of authorized addresses.
          function getAuthorizedAddresses()
              external
              view
              returns (address[] memory)
          {
              return authorities;
          }
          /// @dev Reverts if msg.sender is not authorized.
          function _assertSenderIsAuthorized()
              internal
              view
          {
              if (!authorized[msg.sender]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.SenderNotAuthorizedError(msg.sender));
              }
          }
          /// @dev Authorizes an address.
          /// @param target Address to authorize.
          function _addAuthorizedAddress(address target)
              internal
          {
              // Ensure that the target is not the zero address.
              if (target == address(0)) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.ZeroCantBeAuthorizedError());
              }
              // Ensure that the target is not already authorized.
              if (authorized[target]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetAlreadyAuthorizedError(target));
              }
              authorized[target] = true;
              authorities.push(target);
              emit AuthorizedAddressAdded(target, msg.sender);
          }
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          /// @param index Index of target in authorities array.
          function _removeAuthorizedAddressAtIndex(
              address target,
              uint256 index
          )
              internal
          {
              if (!authorized[target]) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.TargetNotAuthorizedError(target));
              }
              if (index >= authorities.length) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.IndexOutOfBoundsError(
                      index,
                      authorities.length
                  ));
              }
              if (authorities[index] != target) {
                  LibRichErrors.rrevert(LibAuthorizableRichErrors.AuthorizedAddressMismatchError(
                      authorities[index],
                      target
                  ));
              }
              delete authorized[target];
              authorities[index] = authorities[authorities.length - 1];
              authorities.length -= 1;
              emit AuthorizedAddressRemoved(target, msg.sender);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./IOwnable.sol";
      contract IAuthorizable is
          IOwnable
      {
          // Event logged when a new address is authorized.
          event AuthorizedAddressAdded(
              address indexed target,
              address indexed caller
          );
          // Event logged when a currently authorized address is unauthorized.
          event AuthorizedAddressRemoved(
              address indexed target,
              address indexed caller
          );
          /// @dev Authorizes an address.
          /// @param target Address to authorize.
          function addAuthorizedAddress(address target)
              external;
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          function removeAuthorizedAddress(address target)
              external;
          /// @dev Removes authorizion of an address.
          /// @param target Address to remove authorization from.
          /// @param index Index of target in authorities array.
          function removeAuthorizedAddressAtIndex(
              address target,
              uint256 index
          )
              external;
          /// @dev Gets all authorized addresses.
          /// @return Array of authorized addresses.
          function getAuthorizedAddresses()
              external
              view
              returns (address[] memory);
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract IOwnable {
          /// @dev Emitted by Ownable when ownership is transferred.
          /// @param previousOwner The previous owner of the contract.
          /// @param newOwner The new owner of the contract.
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /// @dev Transfers ownership of the contract to a new address.
          /// @param newOwner The address that will become the owner.
          function transferOwnership(address newOwner)
              public;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      library LibAuthorizableRichErrors {
          // bytes4(keccak256("AuthorizedAddressMismatchError(address,address)"))
          bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR =
              0x140a84db;
          // bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)"))
          bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR =
              0xe9f83771;
          // bytes4(keccak256("SenderNotAuthorizedError(address)"))
          bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR =
              0xb65a25b9;
          // bytes4(keccak256("TargetAlreadyAuthorizedError(address)"))
          bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR =
              0xde16f1a0;
          // bytes4(keccak256("TargetNotAuthorizedError(address)"))
          bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR =
              0xeb5108a2;
          // bytes4(keccak256("ZeroCantBeAuthorizedError()"))
          bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES =
              hex"57654fe4";
          // solhint-disable func-name-mixedcase
          function AuthorizedAddressMismatchError(
              address authorized,
              address target
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR,
                  authorized,
                  target
              );
          }
          function IndexOutOfBoundsError(
              uint256 index,
              uint256 length
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR,
                  index,
                  length
              );
          }
          function SenderNotAuthorizedError(address sender)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  SENDER_NOT_AUTHORIZED_ERROR_SELECTOR,
                  sender
              );
          }
          function TargetAlreadyAuthorizedError(address target)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR,
                  target
              );
          }
          function TargetNotAuthorizedError(address target)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  TARGET_NOT_AUTHORIZED_ERROR_SELECTOR,
                  target
              );
          }
          function ZeroCantBeAuthorizedError()
              internal
              pure
              returns (bytes memory)
          {
              return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./interfaces/IOwnable.sol";
      import "./LibOwnableRichErrors.sol";
      import "./LibRichErrors.sol";
      contract Ownable is
          IOwnable
      {
          address public owner;
          constructor ()
              public
          {
              owner = msg.sender;
          }
          modifier onlyOwner() {
              _assertSenderIsOwner();
              _;
          }
          function transferOwnership(address newOwner)
              public
              onlyOwner
          {
              if (newOwner == address(0)) {
                  LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError());
              } else {
                  owner = newOwner;
                  emit OwnershipTransferred(msg.sender, newOwner);
              }
          }
          function _assertSenderIsOwner()
              internal
              view
          {
              if (msg.sender != owner) {
                  LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError(
                      msg.sender,
                      owner
                  ));
              }
          }
      }
      pragma solidity ^0.5.9;
      library LibOwnableRichErrors {
          // bytes4(keccak256("OnlyOwnerError(address,address)"))
          bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
              0x1de45ad1;
          // bytes4(keccak256("TransferOwnerToZeroError()"))
          bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
              hex"e69edc3e";
          // solhint-disable func-name-mixedcase
          function OnlyOwnerError(
              address sender,
              address owner
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_OWNER_ERROR_SELECTOR,
                  sender,
                  owner
              );
          }
          function TransferOwnerToZeroError()
              internal
              pure
              returns (bytes memory)
          {
              return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      contract MixinConstants {
          // 100% in parts-per-million.
          uint32 constant internal PPM_DENOMINATOR = 10**6;
          bytes32 constant internal NIL_POOL_ID = 0x0000000000000000000000000000000000000000000000000000000000000000;
          address constant internal NIL_ADDRESS = 0x0000000000000000000000000000000000000000;
          uint256 constant internal MIN_TOKEN_VALUE = 10**18;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "../interfaces/IStructs.sol";
      library LibStakingRichErrors {
          enum OperatorShareErrorCodes {
              OperatorShareTooLarge,
              CanOnlyDecreaseOperatorShare
          }
          enum InitializationErrorCodes {
              MixinSchedulerAlreadyInitialized,
              MixinParamsAlreadyInitialized
          }
          enum InvalidParamValueErrorCodes {
              InvalidCobbDouglasAlpha,
              InvalidRewardDelegatedStakeWeight,
              InvalidMaximumMakersInPool,
              InvalidMinimumPoolStake,
              InvalidEpochDuration
          }
          enum ExchangeManagerErrorCodes {
              ExchangeAlreadyRegistered,
              ExchangeNotRegistered
          }
          // bytes4(keccak256("OnlyCallableByExchangeError(address)"))
          bytes4 internal constant ONLY_CALLABLE_BY_EXCHANGE_ERROR_SELECTOR =
              0xb56d2df0;
          // bytes4(keccak256("ExchangeManagerError(uint8,address)"))
          bytes4 internal constant EXCHANGE_MANAGER_ERROR_SELECTOR =
              0xb9588e43;
          // bytes4(keccak256("InsufficientBalanceError(uint256,uint256)"))
          bytes4 internal constant INSUFFICIENT_BALANCE_ERROR_SELECTOR =
              0x84c8b7c9;
          // bytes4(keccak256("OnlyCallableByPoolOperatorError(address,bytes32)"))
          bytes4 internal constant ONLY_CALLABLE_BY_POOL_OPERATOR_ERROR_SELECTOR =
              0x82ded785;
          // bytes4(keccak256("BlockTimestampTooLowError(uint256,uint256)"))
          bytes4 internal constant BLOCK_TIMESTAMP_TOO_LOW_ERROR_SELECTOR =
              0xa6bcde47;
          // bytes4(keccak256("OnlyCallableByStakingContractError(address)"))
          bytes4 internal constant ONLY_CALLABLE_BY_STAKING_CONTRACT_ERROR_SELECTOR =
              0xca1d07a2;
          // bytes4(keccak256("OnlyCallableIfInCatastrophicFailureError()"))
          bytes internal constant ONLY_CALLABLE_IF_IN_CATASTROPHIC_FAILURE_ERROR =
              hex"3ef081cc";
          // bytes4(keccak256("OnlyCallableIfNotInCatastrophicFailureError()"))
          bytes internal constant ONLY_CALLABLE_IF_NOT_IN_CATASTROPHIC_FAILURE_ERROR =
              hex"7dd020ce";
          // bytes4(keccak256("OperatorShareError(uint8,bytes32,uint32)"))
          bytes4 internal constant OPERATOR_SHARE_ERROR_SELECTOR =
              0x22df9597;
          // bytes4(keccak256("PoolExistenceError(bytes32,bool)"))
          bytes4 internal constant POOL_EXISTENCE_ERROR_SELECTOR =
              0x9ae94f01;
          // bytes4(keccak256("ProxyDestinationCannotBeNilError()"))
          bytes internal constant PROXY_DESTINATION_CANNOT_BE_NIL_ERROR =
              hex"6eff8285";
          // bytes4(keccak256("InitializationError(uint8)"))
          bytes4 internal constant INITIALIZATION_ERROR_SELECTOR =
              0x0b02d773;
          // bytes4(keccak256("InvalidParamValueError(uint8)"))
          bytes4 internal constant INVALID_PARAM_VALUE_ERROR_SELECTOR =
              0xfc45bd11;
          // bytes4(keccak256("InvalidProtocolFeePaymentError(uint256,uint256)"))
          bytes4 internal constant INVALID_PROTOCOL_FEE_PAYMENT_ERROR_SELECTOR =
              0x31d7a505;
          // bytes4(keccak256("PreviousEpochNotFinalizedError(uint256,uint256)"))
          bytes4 internal constant PREVIOUS_EPOCH_NOT_FINALIZED_ERROR_SELECTOR =
              0x614b800a;
          // bytes4(keccak256("PoolNotFinalizedError(bytes32,uint256)"))
          bytes4 internal constant POOL_NOT_FINALIZED_ERROR_SELECTOR =
              0x5caa0b05;
          // solhint-disable func-name-mixedcase
          function OnlyCallableByExchangeError(
              address senderAddress
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_CALLABLE_BY_EXCHANGE_ERROR_SELECTOR,
                  senderAddress
              );
          }
          function ExchangeManagerError(
              ExchangeManagerErrorCodes errorCodes,
              address exchangeAddress
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  EXCHANGE_MANAGER_ERROR_SELECTOR,
                  errorCodes,
                  exchangeAddress
              );
          }
          function InsufficientBalanceError(
              uint256 amount,
              uint256 balance
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INSUFFICIENT_BALANCE_ERROR_SELECTOR,
                  amount,
                  balance
              );
          }
          function OnlyCallableByPoolOperatorError(
              address senderAddress,
              bytes32 poolId
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_CALLABLE_BY_POOL_OPERATOR_ERROR_SELECTOR,
                  senderAddress,
                  poolId
              );
          }
          function BlockTimestampTooLowError(
              uint256 epochEndTime,
              uint256 currentBlockTimestamp
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  BLOCK_TIMESTAMP_TOO_LOW_ERROR_SELECTOR,
                  epochEndTime,
                  currentBlockTimestamp
              );
          }
          function OnlyCallableByStakingContractError(
              address senderAddress
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ONLY_CALLABLE_BY_STAKING_CONTRACT_ERROR_SELECTOR,
                  senderAddress
              );
          }
          function OnlyCallableIfInCatastrophicFailureError()
              internal
              pure
              returns (bytes memory)
          {
              return ONLY_CALLABLE_IF_IN_CATASTROPHIC_FAILURE_ERROR;
          }
          function OnlyCallableIfNotInCatastrophicFailureError()
              internal
              pure
              returns (bytes memory)
          {
              return ONLY_CALLABLE_IF_NOT_IN_CATASTROPHIC_FAILURE_ERROR;
          }
          function OperatorShareError(
              OperatorShareErrorCodes errorCodes,
              bytes32 poolId,
              uint32 operatorShare
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  OPERATOR_SHARE_ERROR_SELECTOR,
                  errorCodes,
                  poolId,
                  operatorShare
              );
          }
          function PoolExistenceError(
              bytes32 poolId,
              bool alreadyExists
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  POOL_EXISTENCE_ERROR_SELECTOR,
                  poolId,
                  alreadyExists
              );
          }
          function InvalidProtocolFeePaymentError(
              uint256 expectedProtocolFeePaid,
              uint256 actualProtocolFeePaid
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INVALID_PROTOCOL_FEE_PAYMENT_ERROR_SELECTOR,
                  expectedProtocolFeePaid,
                  actualProtocolFeePaid
              );
          }
          function InitializationError(InitializationErrorCodes code)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INITIALIZATION_ERROR_SELECTOR,
                  uint8(code)
              );
          }
          function InvalidParamValueError(InvalidParamValueErrorCodes code)
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INVALID_PARAM_VALUE_ERROR_SELECTOR,
                  uint8(code)
              );
          }
          function ProxyDestinationCannotBeNilError()
              internal
              pure
              returns (bytes memory)
          {
              return PROXY_DESTINATION_CANNOT_BE_NIL_ERROR;
          }
          function PreviousEpochNotFinalizedError(
              uint256 unfinalizedEpoch,
              uint256 unfinalizedPoolsRemaining
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  PREVIOUS_EPOCH_NOT_FINALIZED_ERROR_SELECTOR,
                  unfinalizedEpoch,
                  unfinalizedPoolsRemaining
              );
          }
          function PoolNotFinalizedError(
              bytes32 poolId,
              uint256 epoch
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  POOL_NOT_FINALIZED_ERROR_SELECTOR,
                  poolId,
                  epoch
              );
          }
      }
      pragma solidity ^0.5.9;
      interface IStakingEvents {
          /// @dev Emitted by MixinStake when ZRX is staked.
          /// @param staker of ZRX.
          /// @param amount of ZRX staked.
          event Stake(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted by MixinStake when ZRX is unstaked.
          /// @param staker of ZRX.
          /// @param amount of ZRX unstaked.
          event Unstake(
              address indexed staker,
              uint256 amount
          );
          /// @dev Emitted by MixinStake when ZRX is unstaked.
          /// @param staker of ZRX.
          /// @param amount of ZRX unstaked.
          event MoveStake(
              address indexed staker,
              uint256 amount,
              uint8 fromStatus,
              bytes32 indexed fromPool,
              uint8 toStatus,
              bytes32 indexed toPool
          );
          /// @dev Emitted by MixinExchangeManager when an exchange is added.
          /// @param exchangeAddress Address of new exchange.
          event ExchangeAdded(
              address exchangeAddress
          );
          /// @dev Emitted by MixinExchangeManager when an exchange is removed.
          /// @param exchangeAddress Address of removed exchange.
          event ExchangeRemoved(
              address exchangeAddress
          );
          /// @dev Emitted by MixinExchangeFees when a pool starts earning rewards in an epoch.
          /// @param epoch The epoch in which the pool earned rewards.
          /// @param poolId The ID of the pool.
          event StakingPoolEarnedRewardsInEpoch(
              uint256 indexed epoch,
              bytes32 indexed poolId
          );
          /// @dev Emitted by MixinFinalizer when an epoch has ended.
          /// @param epoch The epoch that ended.
          /// @param numPoolsToFinalize Number of pools that earned rewards during `epoch` and must be finalized.
          /// @param rewardsAvailable Rewards available to all pools that earned rewards during `epoch`.
          /// @param totalWeightedStake Total weighted stake across all pools that earned rewards during `epoch`.
          /// @param totalFeesCollected Total fees collected across all pools that earned rewards during `epoch`.
          event EpochEnded(
              uint256 indexed epoch,
              uint256 numPoolsToFinalize,
              uint256 rewardsAvailable,
              uint256 totalFeesCollected,
              uint256 totalWeightedStake
          );
          /// @dev Emitted by MixinFinalizer when an epoch is fully finalized.
          /// @param epoch The epoch being finalized.
          /// @param rewardsPaid Total amount of rewards paid out.
          /// @param rewardsRemaining Rewards left over.
          event EpochFinalized(
              uint256 indexed epoch,
              uint256 rewardsPaid,
              uint256 rewardsRemaining
          );
          /// @dev Emitted by MixinFinalizer when rewards are paid out to a pool.
          /// @param epoch The epoch when the rewards were paid out.
          /// @param poolId The pool's ID.
          /// @param operatorReward Amount of reward paid to pool operator.
          /// @param membersReward Amount of reward paid to pool members.
          event RewardsPaid(
              uint256 indexed epoch,
              bytes32 indexed poolId,
              uint256 operatorReward,
              uint256 membersReward
          );
          /// @dev Emitted whenever staking parameters are changed via the `setParams()` function.
          /// @param epochDurationInSeconds Minimum seconds between epochs.
          /// @param rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
          /// @param minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
          /// @param cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
          /// @param cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
          event ParamsSet(
              uint256 epochDurationInSeconds,
              uint32 rewardDelegatedStakeWeight,
              uint256 minimumPoolStake,
              uint256 cobbDouglasAlphaNumerator,
              uint256 cobbDouglasAlphaDenominator
          );
          /// @dev Emitted by MixinStakingPool when a new pool is created.
          /// @param poolId Unique id generated for pool.
          /// @param operator The operator (creator) of pool.
          /// @param operatorShare The share of rewards given to the operator, in ppm.
          event StakingPoolCreated(
              bytes32 poolId,
              address operator,
              uint32 operatorShare
          );
          /// @dev Emitted by MixinStakingPool when a maker sets their pool.
          /// @param makerAddress Adress of maker added to pool.
          /// @param poolId Unique id of pool.
          event MakerStakingPoolSet(
              address indexed makerAddress,
              bytes32 indexed poolId
          );
          /// @dev Emitted when a staking pool's operator share is decreased.
          /// @param poolId Unique Id of pool.
          /// @param oldOperatorShare Previous share of rewards owned by operator.
          /// @param newOperatorShare Newly decreased share of rewards owned by operator.
          event OperatorShareDecreased(
              bytes32 indexed poolId,
              uint32 oldOperatorShare,
              uint32 newOperatorShare
          );
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./IStructs.sol";
      contract IStakingProxy {
          /// @dev Emitted by StakingProxy when a staking contract is attached.
          /// @param newStakingContractAddress Address of newly attached staking contract.
          event StakingContractAttachedToProxy(
              address newStakingContractAddress
          );
          /// @dev Emitted by StakingProxy when a staking contract is detached.
          event StakingContractDetachedFromProxy();
          /// @dev Attach a staking contract; future calls will be delegated to the staking contract.
          /// Note that this is callable only by an authorized address.
          /// @param _stakingContract Address of staking contract.
          function attachStakingContract(address _stakingContract)
              external;
          /// @dev Detach the current staking contract.
          /// Note that this is callable only by an authorized address.
          function detachStakingContract()
              external;
          /// @dev Asserts that an epoch is between 5 and 30 days long.
          //       Asserts that 0 < cobb douglas alpha value <= 1.
          //       Asserts that a stake weight is <= 100%.
          //       Asserts that pools allow >= 1 maker.
          //       Asserts that all addresses are initialized.
          function assertValidStorageParams()
              external
              view;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../staking_pools/MixinStakingPool.sol";
      import "../libs/LibStakingRichErrors.sol";
      contract MixinStake is
          MixinStakingPool
      {
          using LibSafeMath for uint256;
          /// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
          ///      Unstake to retrieve the ZRX. Stake is in the 'Active' status.
          /// @param amount of ZRX to stake.
          function stake(uint256 amount)
              external
          {
              address staker = msg.sender;
              // deposit equivalent amount of ZRX into vault
              getZrxVault().depositFrom(staker, amount);
              // mint stake
              _increaseCurrentAndNextBalance(
                  _ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker],
                  amount
              );
              // notify
              emit Stake(
                  staker,
                  amount
              );
          }
          /// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
          ///      the staker. Stake must be in the 'undelegated' status in both the
          ///      current and next epoch in order to be unstaked.
          /// @param amount of ZRX to unstake.
          function unstake(uint256 amount)
              external
          {
              address staker = msg.sender;
              IStructs.StoredBalance memory undelegatedBalance =
                  _loadCurrentBalance(_ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker]);
              // stake must be undelegated in current and next epoch to be withdrawn
              uint256 currentWithdrawableStake = LibSafeMath.min256(
                  undelegatedBalance.currentEpochBalance,
                  undelegatedBalance.nextEpochBalance
              );
              if (amount > currentWithdrawableStake) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InsufficientBalanceError(
                          amount,
                          currentWithdrawableStake
                      )
                  );
              }
              // burn undelegated stake
              _decreaseCurrentAndNextBalance(
                  _ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker],
                  amount
              );
              // withdraw equivalent amount of ZRX from vault
              getZrxVault().withdrawFrom(staker, amount);
              // emit stake event
              emit Unstake(
                  staker,
                  amount
              );
          }
          /// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
          ///      Delegated stake can also be moved between pools.
          ///      This change comes into effect next epoch.
          /// @param from status to move stake out of.
          /// @param to status to move stake into.
          /// @param amount of stake to move.
          function moveStake(
              IStructs.StakeInfo calldata from,
              IStructs.StakeInfo calldata to,
              uint256 amount
          )
              external
          {
              address staker = msg.sender;
              // Sanity check: no-op if no stake is being moved.
              if (amount == 0) {
                  return;
              }
              // Sanity check: no-op if moving stake from undelegated to undelegated.
              if (from.status == IStructs.StakeStatus.UNDELEGATED &&
                  to.status == IStructs.StakeStatus.UNDELEGATED) {
                  return;
              }
              // handle delegation
              if (from.status == IStructs.StakeStatus.DELEGATED) {
                  _undelegateStake(
                      from.poolId,
                      staker,
                      amount
                  );
              }
              if (to.status == IStructs.StakeStatus.DELEGATED) {
                  _delegateStake(
                      to.poolId,
                      staker,
                      amount
                  );
              }
              // execute move
              IStructs.StoredBalance storage fromPtr = _ownerStakeByStatus[uint8(from.status)][staker];
              IStructs.StoredBalance storage toPtr = _ownerStakeByStatus[uint8(to.status)][staker];
              _moveStake(
                  fromPtr,
                  toPtr,
                  amount
              );
              // notify
              emit MoveStake(
                  staker,
                  amount,
                  uint8(from.status),
                  from.poolId,
                  uint8(to.status),
                  to.poolId
              );
          }
          /// @dev Delegates a owners stake to a staking pool.
          /// @param poolId Id of pool to delegate to.
          /// @param staker Owner who wants to delegate.
          /// @param amount Amount of stake to delegate.
          function _delegateStake(
              bytes32 poolId,
              address staker,
              uint256 amount
          )
              private
          {
              // Sanity check the pool we're delegating to exists.
              _assertStakingPoolExists(poolId);
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  staker
              );
              // Increase how much stake the staker has delegated to the input pool.
              _increaseNextBalance(
                  _delegatedStakeToPoolByOwner[staker][poolId],
                  amount
              );
              // Increase how much stake has been delegated to pool.
              _increaseNextBalance(
                  _delegatedStakeByPoolId[poolId],
                  amount
              );
              // Increase next balance of global delegated stake.
              _increaseNextBalance(
                  _globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)],
                  amount
              );
          }
          /// @dev Un-Delegates a owners stake from a staking pool.
          /// @param poolId Id of pool to un-delegate from.
          /// @param staker Owner who wants to un-delegate.
          /// @param amount Amount of stake to un-delegate.
          function _undelegateStake(
              bytes32 poolId,
              address staker,
              uint256 amount
          )
              private
          {
              // sanity check the pool we're undelegating from exists
              _assertStakingPoolExists(poolId);
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  staker
              );
              // Decrease how much stake the staker has delegated to the input pool.
              _decreaseNextBalance(
                  _delegatedStakeToPoolByOwner[staker][poolId],
                  amount
              );
              // Decrease how much stake has been delegated to pool.
              _decreaseNextBalance(
                  _delegatedStakeByPoolId[poolId],
                  amount
              );
              // Decrease next balance of global delegated stake (aggregated across all stakers).
              _decreaseNextBalance(
                  _globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)],
                  amount
              );
          }
      }
      pragma solidity ^0.5.9;
      import "./LibRichErrors.sol";
      import "./LibSafeMathRichErrors.sol";
      library LibSafeMath {
          function safeMul(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              if (a == 0) {
                  return 0;
              }
              uint256 c = a * b;
              if (c / a != b) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
                      a,
                      b
                  ));
              }
              return c;
          }
          function safeDiv(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              if (b == 0) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
                      a,
                      b
                  ));
              }
              uint256 c = a / b;
              return c;
          }
          function safeSub(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              if (b > a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
                      a,
                      b
                  ));
              }
              return a - b;
          }
          function safeAdd(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              uint256 c = a + b;
              if (c < a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
                      LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
                      a,
                      b
                  ));
              }
              return c;
          }
          function max256(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              return a >= b ? a : b;
          }
          function min256(uint256 a, uint256 b)
              internal
              pure
              returns (uint256)
          {
              return a < b ? a : b;
          }
      }
      pragma solidity ^0.5.9;
      library LibSafeMathRichErrors {
          // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
          bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
              0xe946c1bb;
          // bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
          bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
              0xc996af7b;
          enum BinOpErrorCodes {
              ADDITION_OVERFLOW,
              MULTIPLICATION_OVERFLOW,
              SUBTRACTION_UNDERFLOW,
              DIVISION_BY_ZERO
          }
          enum DowncastErrorCodes {
              VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
              VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
              VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
          }
          // solhint-disable func-name-mixedcase
          function Uint256BinOpError(
              BinOpErrorCodes errorCode,
              uint256 a,
              uint256 b
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  UINT256_BINOP_ERROR_SELECTOR,
                  errorCode,
                  a,
                  b
              );
          }
          function Uint256DowncastError(
              DowncastErrorCodes errorCode,
              uint256 a
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  UINT256_DOWNCAST_ERROR_SELECTOR,
                  errorCode,
                  a
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStructs.sol";
      import "../sys/MixinAbstract.sol";
      import "./MixinStakingPoolRewards.sol";
      contract MixinStakingPool is
          MixinAbstract,
          MixinStakingPoolRewards
      {
          using LibSafeMath for uint256;
          using LibSafeDowncast for uint256;
          /// @dev Asserts that the sender is the operator of the input pool.
          /// @param poolId Pool sender must be operator of.
          modifier onlyStakingPoolOperator(bytes32 poolId) {
              _assertSenderIsPoolOperator(poolId);
              _;
          }
          /// @dev Create a new staking pool. The sender will be the operator of this pool.
          /// Note that an operator must be payable.
          /// @param operatorShare Portion of rewards owned by the operator, in ppm.
          /// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true.
          /// @return poolId The unique pool id generated for this pool.
          function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker)
              external
              returns (bytes32 poolId)
          {
              // note that an operator must be payable
              address operator = msg.sender;
              // compute unique id for this pool
              poolId = lastPoolId = bytes32(uint256(lastPoolId).safeAdd(1));
              // sanity check on operator share
              _assertNewOperatorShare(
                  poolId,
                  PPM_DENOMINATOR,    // max operator share
                  operatorShare
              );
              // create and store pool
              IStructs.Pool memory pool = IStructs.Pool({
                  operator: operator,
                  operatorShare: operatorShare
              });
              _poolById[poolId] = pool;
              // Staking pool has been created
              emit StakingPoolCreated(poolId, operator, operatorShare);
              if (addOperatorAsMaker) {
                  joinStakingPoolAsMaker(poolId);
              }
              return poolId;
          }
          /// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
          /// @param poolId Unique Id of pool.
          /// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
          function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
              external
              onlyStakingPoolOperator(poolId)
          {
              // load pool and assert that we can decrease
              uint32 currentOperatorShare = _poolById[poolId].operatorShare;
              _assertNewOperatorShare(
                  poolId,
                  currentOperatorShare,
                  newOperatorShare
              );
              // decrease operator share
              _poolById[poolId].operatorShare = newOperatorShare;
              emit OperatorShareDecreased(
                  poolId,
                  currentOperatorShare,
                  newOperatorShare
              );
          }
          /// @dev Allows caller to join a staking pool as a maker.
          /// @param poolId Unique id of pool.
          function joinStakingPoolAsMaker(bytes32 poolId)
              public
          {
              address maker = msg.sender;
              poolIdByMaker[maker] = poolId;
              emit MakerStakingPoolSet(
                  maker,
                  poolId
              );
          }
          /// @dev Returns a staking pool
          /// @param poolId Unique id of pool.
          function getStakingPool(bytes32 poolId)
              public
              view
              returns (IStructs.Pool memory)
          {
              return _poolById[poolId];
          }
          /// @dev Reverts iff a staking pool does not exist.
          /// @param poolId Unique id of pool.
          function _assertStakingPoolExists(bytes32 poolId)
              internal
              view
          {
              if (_poolById[poolId].operator == NIL_ADDRESS) {
                  // we use the pool's operator as a proxy for its existence
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.PoolExistenceError(
                          poolId,
                          false
                      )
                  );
              }
          }
          /// @dev Reverts iff the new operator share is invalid.
          /// @param poolId Unique id of pool.
          /// @param currentOperatorShare Current operator share.
          /// @param newOperatorShare New operator share.
          function _assertNewOperatorShare(
              bytes32 poolId,
              uint32 currentOperatorShare,
              uint32 newOperatorShare
          )
              private
              pure
          {
              // sanity checks
              if (newOperatorShare > PPM_DENOMINATOR) {
                  // operator share must be a valid fraction
                  LibRichErrors.rrevert(LibStakingRichErrors.OperatorShareError(
                      LibStakingRichErrors.OperatorShareErrorCodes.OperatorShareTooLarge,
                      poolId,
                      newOperatorShare
                  ));
              } else if (newOperatorShare > currentOperatorShare) {
                  // new share must be less than or equal to the current share
                  LibRichErrors.rrevert(LibStakingRichErrors.OperatorShareError(
                      LibStakingRichErrors.OperatorShareErrorCodes.CanOnlyDecreaseOperatorShare,
                      poolId,
                      newOperatorShare
                  ));
              }
          }
          /// @dev Asserts that the sender is the operator of the input pool.
          /// @param poolId Pool sender must be operator of.
          function _assertSenderIsPoolOperator(bytes32 poolId)
              private
              view
          {
              address operator = _poolById[poolId].operator;
              if (msg.sender != operator) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.OnlyCallableByPoolOperatorError(
                          msg.sender,
                          poolId
                      )
                  );
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      /// @dev Exposes some internal functions from various contracts to avoid
      ///      cyclical dependencies.
      contract MixinAbstract {
          /// @dev Computes the reward owed to a pool during finalization.
          ///      Does nothing if the pool is already finalized.
          /// @param poolId The pool's ID.
          /// @return totalReward The total reward owed to a pool.
          /// @return membersStake The total stake for all non-operator members in
          ///         this pool.
          function _getUnfinalizedPoolRewards(bytes32 poolId)
              internal
              view
              returns (
                  uint256 totalReward,
                  uint256 membersStake
              );
          /// @dev Asserts that a pool has been finalized last epoch.
          /// @param poolId The id of the pool that should have been finalized.
          function _assertPoolFinalizedLastEpoch(bytes32 poolId)
              internal
              view;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "./MixinCumulativeRewards.sol";
      import "../sys/MixinAbstract.sol";
      contract MixinStakingPoolRewards is
          MixinAbstract,
          MixinCumulativeRewards
      {
          using LibSafeMath for uint256;
          /// @dev Withdraws the caller's WETH rewards that have accumulated
          ///      until the last epoch.
          /// @param poolId Unique id of pool.
          function withdrawDelegatorRewards(bytes32 poolId)
              external
          {
              _withdrawAndSyncDelegatorRewards(poolId, msg.sender);
          }
          /// @dev Computes the reward balance in ETH of the operator of a pool.
          /// @param poolId Unique id of pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfOperator(bytes32 poolId)
              external
              view
              returns (uint256 reward)
          {
              // Because operator rewards are immediately withdrawn as WETH
              // on finalization, the only factor in this function are unfinalized
              // rewards.
              IStructs.Pool memory pool = _poolById[poolId];
              // Get any unfinalized rewards.
              (uint256 unfinalizedTotalRewards, uint256 unfinalizedMembersStake) =
                  _getUnfinalizedPoolRewards(poolId);
              // Get the operators' portion.
              (reward,) = _computePoolRewardsSplit(
                  pool.operatorShare,
                  unfinalizedTotalRewards,
                  unfinalizedMembersStake
              );
              return reward;
          }
          /// @dev Computes the reward balance in ETH of a specific member of a pool.
          /// @param poolId Unique id of pool.
          /// @param member The member of the pool.
          /// @return totalReward Balance in ETH.
          function computeRewardBalanceOfDelegator(bytes32 poolId, address member)
              external
              view
              returns (uint256 reward)
          {
              IStructs.Pool memory pool = _poolById[poolId];
              // Get any unfinalized rewards.
              (uint256 unfinalizedTotalRewards, uint256 unfinalizedMembersStake) =
                  _getUnfinalizedPoolRewards(poolId);
              // Get the members' portion.
              (, uint256 unfinalizedMembersReward) = _computePoolRewardsSplit(
                  pool.operatorShare,
                  unfinalizedTotalRewards,
                  unfinalizedMembersStake
              );
              return _computeDelegatorReward(
                  poolId,
                  member,
                  unfinalizedMembersReward,
                  unfinalizedMembersStake
              );
          }
          /// @dev Syncs rewards for a delegator. This includes withdrawing rewards
          ///      rewards and adding/removing dependencies on cumulative rewards.
          /// @param poolId Unique id of pool.
          /// @param member of the pool.
          function _withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              internal
          {
              // Ensure the pool is finalized.
              _assertPoolFinalizedLastEpoch(poolId);
              // Compute balance owed to delegator
              uint256 balance = _computeDelegatorReward(
                  poolId,
                  member,
                  // No unfinalized values because we ensured the pool is already
                  // finalized.
                  0,
                  0
              );
              // Sync the delegated stake balance. This will ensure future calls of
              // `_computeDelegatorReward` during this epoch will return 0, 
              // preventing a delegator from withdrawing more than once an epoch.
              _delegatedStakeToPoolByOwner[member][poolId] =
                  _loadCurrentBalance(_delegatedStakeToPoolByOwner[member][poolId]);
              // Withdraw non-0 balance
              if (balance != 0) {
                  // Decrease the balance of the pool
                  _decreasePoolRewards(poolId, balance);
                  // Withdraw the member's WETH balance
                  getWethContract().transfer(member, balance);
              }
              // Ensure a cumulative reward entry exists for this epoch,
              // copying the previous epoch's CR if one doesn't exist already.
              _updateCumulativeReward(poolId);
          }
          /// @dev Handles a pool's reward at the current epoch.
          ///      This will split the reward between the operator and members,
          ///      depositing them into their respective vaults, and update the
          ///      accounting needed to allow members to withdraw their individual
          ///      rewards.
          /// @param poolId Unique Id of pool.
          /// @param reward received by the pool.
          /// @param membersStake the amount of non-operator delegated stake that
          ///        will split the  reward.
          /// @return operatorReward Portion of `reward` given to the pool operator.
          /// @return membersReward Portion of `reward` given to the pool members.
          function _syncPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              internal
              returns (uint256 operatorReward, uint256 membersReward)
          {
              IStructs.Pool memory pool = _poolById[poolId];
              // Split the reward between operator and members
              (operatorReward, membersReward) = _computePoolRewardsSplit(
                  pool.operatorShare,
                  reward,
                  membersStake
              );
              if (operatorReward > 0) {
                  // Transfer the operator's weth reward to the operator
                  getWethContract().transfer(pool.operator, operatorReward);
              }
              if (membersReward > 0) {
                  // Increase the balance of the pool
                  _increasePoolRewards(poolId, membersReward);
                  // Create a cumulative reward entry at the current epoch.
                  _addCumulativeReward(poolId, membersReward, membersStake);
              }
              return (operatorReward, membersReward);
          }
          /// @dev Compute the split of a pool reward between the operator and members
          ///      based on the `operatorShare` and `membersStake`.
          /// @param operatorShare The fraction of rewards owed to the operator,
          ///        in PPM.
          /// @param totalReward The pool reward.
          /// @param membersStake The amount of member (non-operator) stake delegated
          ///        to the pool in the epoch the rewards were earned.
          /// @return operatorReward Portion of `totalReward` given to the pool operator.
          /// @return membersReward Portion of `totalReward` given to the pool members.
          function _computePoolRewardsSplit(
              uint32 operatorShare,
              uint256 totalReward,
              uint256 membersStake
          )
              internal
              pure
              returns (uint256 operatorReward, uint256 membersReward)
          {
              if (membersStake == 0) {
                  operatorReward = totalReward;
              } else {
                  operatorReward = LibMath.getPartialAmountCeil(
                      uint256(operatorShare),
                      PPM_DENOMINATOR,
                      totalReward
                  );
                  membersReward = totalReward.safeSub(operatorReward);
              }
              return (operatorReward, membersReward);
          }
          /// @dev Computes the reward balance in ETH of a specific member of a pool.
          /// @param poolId Unique id of pool.
          /// @param member of the pool.
          /// @param unfinalizedMembersReward Unfinalized total members reward (if any).
          /// @param unfinalizedMembersStake Unfinalized total members stake (if any).
          /// @return reward Balance in WETH.
          function _computeDelegatorReward(
              bytes32 poolId,
              address member,
              uint256 unfinalizedMembersReward,
              uint256 unfinalizedMembersStake
          )
              private
              view
              returns (uint256 reward)
          {
              uint256 currentEpoch_ = currentEpoch;
              IStructs.StoredBalance memory delegatedStake = _delegatedStakeToPoolByOwner[member][poolId];
              // There can be no rewards if the last epoch when stake was stored is
              // equal to the current epoch, because all prior rewards, including
              // rewards finalized this epoch have been claimed.
              if (delegatedStake.currentEpoch == currentEpoch_) {
                  return 0;
              }
              // We account for rewards over 3 intervals, below.
              // 1/3 Unfinalized rewards earned in `currentEpoch - 1`.
              reward = _computeUnfinalizedDelegatorReward(
                  delegatedStake,
                  currentEpoch_,
                  unfinalizedMembersReward,
                  unfinalizedMembersStake
              );
              // 2/3 Finalized rewards earned in epochs [`delegatedStake.currentEpoch + 1` .. `currentEpoch - 1`]
              uint256 delegatedStakeNextEpoch = uint256(delegatedStake.currentEpoch).safeAdd(1);
              reward = reward.safeAdd(
                  _computeMemberRewardOverInterval(
                      poolId,
                      delegatedStake.currentEpochBalance,
                      delegatedStake.currentEpoch,
                      delegatedStakeNextEpoch
                  )
              );
              // 3/3 Finalized rewards earned in epoch `delegatedStake.currentEpoch`.
              reward = reward.safeAdd(
                  _computeMemberRewardOverInterval(
                      poolId,
                      delegatedStake.nextEpochBalance,
                      delegatedStakeNextEpoch,
                      currentEpoch_
                  )
              );
              return reward;
          }
          /// @dev Computes the unfinalized rewards earned by a delegator in the last epoch.
          /// @param delegatedStake Amount of stake delegated to pool by a specific staker
          /// @param currentEpoch_ The epoch in which this call is executing
          /// @param unfinalizedMembersReward Unfinalized total members reward (if any).
          /// @param unfinalizedMembersStake Unfinalized total members stake (if any).
          /// @return reward Balance in WETH.
          function _computeUnfinalizedDelegatorReward(
              IStructs.StoredBalance memory delegatedStake,
              uint256 currentEpoch_,
              uint256 unfinalizedMembersReward,
              uint256 unfinalizedMembersStake
          )
              private
              pure
              returns (uint256)
          {
              // If there are unfinalized rewards this epoch, compute the member's
              // share.
              if (unfinalizedMembersReward == 0 || unfinalizedMembersStake == 0) {
                  return 0;
              }
              // Unfinalized rewards are always earned from stake in
              // the prior epoch so we want the stake at `currentEpoch_-1`.
              uint256 unfinalizedStakeBalance = delegatedStake.currentEpoch >= currentEpoch_.safeSub(1) ?
                  delegatedStake.currentEpochBalance :
                  delegatedStake.nextEpochBalance;
              // Sanity check to save gas on computation
              if (unfinalizedStakeBalance == 0) {
                  return 0;
              }
              // Compute unfinalized reward
              return LibMath.getPartialAmountFloor(
                  unfinalizedMembersReward,
                  unfinalizedMembersStake,
                  unfinalizedStakeBalance
              );
          }
          /// @dev Increases rewards for a pool.
          /// @param poolId Unique id of pool.
          /// @param amount Amount to increment rewards by.
          function _increasePoolRewards(bytes32 poolId, uint256 amount)
              private
          {
              rewardsByPoolId[poolId] = rewardsByPoolId[poolId].safeAdd(amount);
              wethReservedForPoolRewards = wethReservedForPoolRewards.safeAdd(amount);
          }
          /// @dev Decreases rewards for a pool.
          /// @param poolId Unique id of pool.
          /// @param amount Amount to decrement rewards by.
          function _decreasePoolRewards(bytes32 poolId, uint256 amount)
              private
          {
              rewardsByPoolId[poolId] = rewardsByPoolId[poolId].safeSub(amount);
              wethReservedForPoolRewards = wethReservedForPoolRewards.safeSub(amount);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "./LibMathRichErrors.sol";
      library LibMath {
          using LibSafeMath for uint256;
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          ///      Reverts if rounding error is >= 0.1%
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded down.
          function safeGetPartialAmountFloor(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              if (isRoundingErrorFloor(
                      numerator,
                      denominator,
                      target
              )) {
                  LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
                      numerator,
                      denominator,
                      target
                  ));
              }
              partialAmount = numerator.safeMul(target).safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          ///      Reverts if rounding error is >= 0.1%
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded up.
          function safeGetPartialAmountCeil(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              if (isRoundingErrorCeil(
                      numerator,
                      denominator,
                      target
              )) {
                  LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
                      numerator,
                      denominator,
                      target
                  ));
              }
              // safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
              //       ceil(a / b) = floor((a + b - 1) / b)
              // To implement `ceil(a / b)` using safeDiv.
              partialAmount = numerator.safeMul(target)
                  .safeAdd(denominator.safeSub(1))
                  .safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded down.
          function getPartialAmountFloor(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              partialAmount = numerator.safeMul(target).safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Calculates partial value given a numerator and denominator rounded down.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to calculate partial of.
          /// @return Partial value of target rounded up.
          function getPartialAmountCeil(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (uint256 partialAmount)
          {
              // safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
              //       ceil(a / b) = floor((a + b - 1) / b)
              // To implement `ceil(a / b)` using safeDiv.
              partialAmount = numerator.safeMul(target)
                  .safeAdd(denominator.safeSub(1))
                  .safeDiv(denominator);
              return partialAmount;
          }
          /// @dev Checks if rounding error >= 0.1% when rounding down.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to multiply with numerator/denominator.
          /// @return Rounding error is present.
          function isRoundingErrorFloor(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (bool isError)
          {
              if (denominator == 0) {
                  LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
              }
              // The absolute rounding error is the difference between the rounded
              // value and the ideal value. The relative rounding error is the
              // absolute rounding error divided by the absolute value of the
              // ideal value. This is undefined when the ideal value is zero.
              //
              // The ideal value is `numerator * target / denominator`.
              // Let's call `numerator * target % denominator` the remainder.
              // The absolute error is `remainder / denominator`.
              //
              // When the ideal value is zero, we require the absolute error to
              // be zero. Fortunately, this is always the case. The ideal value is
              // zero iff `numerator == 0` and/or `target == 0`. In this case the
              // remainder and absolute error are also zero.
              if (target == 0 || numerator == 0) {
                  return false;
              }
              // Otherwise, we want the relative rounding error to be strictly
              // less than 0.1%.
              // The relative error is `remainder / (numerator * target)`.
              // We want the relative error less than 1 / 1000:
              //        remainder / (numerator * denominator)  <  1 / 1000
              // or equivalently:
              //        1000 * remainder  <  numerator * target
              // so we have a rounding error iff:
              //        1000 * remainder  >=  numerator * target
              uint256 remainder = mulmod(
                  target,
                  numerator,
                  denominator
              );
              isError = remainder.safeMul(1000) >= numerator.safeMul(target);
              return isError;
          }
          /// @dev Checks if rounding error >= 0.1% when rounding up.
          /// @param numerator Numerator.
          /// @param denominator Denominator.
          /// @param target Value to multiply with numerator/denominator.
          /// @return Rounding error is present.
          function isRoundingErrorCeil(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (bool isError)
          {
              if (denominator == 0) {
                  LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
              }
              // See the comments in `isRoundingError`.
              if (target == 0 || numerator == 0) {
                  // When either is zero, the ideal value and rounded value are zero
                  // and there is no rounding error. (Although the relative error
                  // is undefined.)
                  return false;
              }
              // Compute remainder as before
              uint256 remainder = mulmod(
                  target,
                  numerator,
                  denominator
              );
              remainder = denominator.safeSub(remainder) % denominator;
              isError = remainder.safeMul(1000) >= numerator.safeMul(target);
              return isError;
          }
      }
      pragma solidity ^0.5.9;
      library LibMathRichErrors {
          // bytes4(keccak256("DivisionByZeroError()"))
          bytes internal constant DIVISION_BY_ZERO_ERROR =
              hex"a791837c";
          // bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
          bytes4 internal constant ROUNDING_ERROR_SELECTOR =
              0x339f3de2;
          // solhint-disable func-name-mixedcase
          function DivisionByZeroError()
              internal
              pure
              returns (bytes memory)
          {
              return DIVISION_BY_ZERO_ERROR;
          }
          function RoundingError(
              uint256 numerator,
              uint256 denominator,
              uint256 target
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  ROUNDING_ERROR_SELECTOR,
                  numerator,
                  denominator,
                  target
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibFractions.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../stake/MixinStakeBalances.sol";
      import "../immutable/MixinConstants.sol";
      contract MixinCumulativeRewards is
          MixinStakeBalances,
          MixinConstants
      {
          using LibSafeMath for uint256;
          /// @dev returns true iff Cumulative Rewards are set
          function _isCumulativeRewardSet(IStructs.Fraction memory cumulativeReward)
              internal
              pure
              returns (bool)
          {
              // We use the denominator as a proxy for whether the cumulative
              // reward is set, as setting the cumulative reward always sets this
              // field to at least 1.
              return cumulativeReward.denominator != 0;
          }
          /// @dev Sets a pool's cumulative delegator rewards for the current epoch,
          ///      given the rewards earned and stake from the last epoch, which will
          ///      be summed with the previous cumulative rewards for this pool.
          ///      If the last cumulative reward epoch is the current epoch, this is a
          ///      no-op.
          /// @param poolId The pool ID.
          /// @param reward The total reward earned by pool delegators from the last epoch.
          /// @param stake The total delegated stake in the pool in the last epoch.
          function _addCumulativeReward(
              bytes32 poolId,
              uint256 reward,
              uint256 stake
          )
              internal
          {
              // Fetch the last epoch at which we stored an entry for this pool;
              // this is the most up-to-date cumulative rewards for this pool.
              uint256 lastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              uint256 currentEpoch_ = currentEpoch;
              // If we already have a record for this epoch, don't overwrite it.
              if (lastStoredEpoch == currentEpoch_) {
                  return;
              }
              IStructs.Fraction memory mostRecentCumulativeReward =
                  _cumulativeRewardsByPool[poolId][lastStoredEpoch];
              // Compute new cumulative reward
              IStructs.Fraction memory cumulativeReward;
              if (_isCumulativeRewardSet(mostRecentCumulativeReward)) {
                  // If we have a prior cumulative reward entry, we sum them as fractions.
                  (cumulativeReward.numerator, cumulativeReward.denominator) = LibFractions.add(
                      mostRecentCumulativeReward.numerator,
                      mostRecentCumulativeReward.denominator,
                      reward,
                      stake
                  );
                  // Normalize to prevent overflows in future operations.
                  (cumulativeReward.numerator, cumulativeReward.denominator) = LibFractions.normalize(
                      cumulativeReward.numerator,
                      cumulativeReward.denominator
                  );
              } else {
                  (cumulativeReward.numerator, cumulativeReward.denominator) = (reward, stake);
              }
              // Store cumulative rewards for this epoch.
              _cumulativeRewardsByPool[poolId][currentEpoch_] = cumulativeReward;
              _cumulativeRewardsByPoolLastStored[poolId] = currentEpoch_;
          }
          /// @dev Sets a pool's cumulative delegator rewards for the current epoch,
          ///      using the last stored cumulative rewards. If we've already set
          ///      a CR for this epoch, this is a no-op.
          /// @param poolId The pool ID.
          function _updateCumulativeReward(bytes32 poolId)
              internal
          {
              // Just add empty rewards for this epoch, which will be added to
              // the previous CR, so we end up with the previous CR being set for
              // this epoch.
              _addCumulativeReward(poolId, 0, 1);
          }
          /// @dev Computes a member's reward over a given epoch interval.
          /// @param poolId Uniqud Id of pool.
          /// @param memberStakeOverInterval Stake delegated to pool by member over
          ///        the interval.
          /// @param beginEpoch Beginning of interval.
          /// @param endEpoch End of interval.
          /// @return rewards Reward accumulated over interval [beginEpoch, endEpoch]
          function _computeMemberRewardOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              internal
              view
              returns (uint256 reward)
          {
              // Sanity check if we can skip computation, as it will result in zero.
              if (memberStakeOverInterval == 0 || beginEpoch == endEpoch) {
                  return 0;
              }
              // Sanity check interval
              require(beginEpoch < endEpoch, "CR_INTERVAL_INVALID");
              // Sanity check begin reward
              IStructs.Fraction memory beginReward = _getCumulativeRewardAtEpoch(poolId, beginEpoch);
              IStructs.Fraction memory endReward = _getCumulativeRewardAtEpoch(poolId, endEpoch);
              // Compute reward
              reward = LibFractions.scaleDifference(
                  endReward.numerator,
                  endReward.denominator,
                  beginReward.numerator,
                  beginReward.denominator,
                  memberStakeOverInterval
              );
          }
          /// @dev Fetch the most recent cumulative reward entry for a pool.
          /// @param poolId Unique ID of pool.
          /// @return cumulativeReward The most recent cumulative reward `poolId`.
          function _getMostRecentCumulativeReward(bytes32 poolId)
              private
              view
              returns (IStructs.Fraction memory cumulativeReward)
          {
              uint256 lastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              return _cumulativeRewardsByPool[poolId][lastStoredEpoch];
          }
          /// @dev Fetch the cumulative reward for a given epoch.
          ///      If the corresponding CR does not exist in state, then we backtrack
          ///      to find its value by querying `epoch-1` and then most recent CR.
          /// @param poolId Unique ID of pool.
          /// @param epoch The epoch to find the
          /// @return cumulativeReward The cumulative reward for `poolId` at `epoch`.
          /// @return cumulativeRewardStoredAt Epoch that the `cumulativeReward` is stored at.
          function _getCumulativeRewardAtEpoch(bytes32 poolId, uint256 epoch)
              private
              view
              returns (IStructs.Fraction memory cumulativeReward)
          {
              // Return CR at `epoch`, given it's set.
              cumulativeReward = _cumulativeRewardsByPool[poolId][epoch];
              if (_isCumulativeRewardSet(cumulativeReward)) {
                  return cumulativeReward;
              }
              // Return CR at `epoch-1`, given it's set.
              uint256 lastEpoch = epoch.safeSub(1);
              cumulativeReward = _cumulativeRewardsByPool[poolId][lastEpoch];
              if (_isCumulativeRewardSet(cumulativeReward)) {
                  return cumulativeReward;
              }
              // Return the most recent CR, given it's less than `epoch`.
              uint256 mostRecentEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              if (mostRecentEpoch < epoch) {
                  cumulativeReward = _cumulativeRewardsByPool[poolId][mostRecentEpoch];
                  if (_isCumulativeRewardSet(cumulativeReward)) {
                      return cumulativeReward;
                  }
              }
              // Otherwise return an empty CR.
              return IStructs.Fraction(0, 1);
          }
      }
      pragma solidity ^0.5.9;
      import "./LibSafeMath.sol";
      library LibFractions {
          using LibSafeMath for uint256;
          /// @dev Safely adds two fractions `n1/d1 + n2/d2`
          /// @param n1 numerator of `1`
          /// @param d1 denominator of `1`
          /// @param n2 numerator of `2`
          /// @param d2 denominator of `2`
          /// @return numerator Numerator of sum
          /// @return denominator Denominator of sum
          function add(
              uint256 n1,
              uint256 d1,
              uint256 n2,
              uint256 d2
          )
              internal
              pure
              returns (
                  uint256 numerator,
                  uint256 denominator
              )
          {
              if (n1 == 0) {
                  return (numerator = n2, denominator = d2);
              }
              if (n2 == 0) {
                  return (numerator = n1, denominator = d1);
              }
              numerator = n1
                  .safeMul(d2)
                  .safeAdd(n2.safeMul(d1));
              denominator = d1.safeMul(d2);
              return (numerator, denominator);
          }
          /// @dev Rescales a fraction to prevent overflows during addition if either
          ///      the numerator or the denominator are > `maxValue`.
          /// @param numerator The numerator.
          /// @param denominator The denominator.
          /// @param maxValue The maximum value allowed for both the numerator and
          ///        denominator.
          /// @return scaledNumerator The rescaled numerator.
          /// @return scaledDenominator The rescaled denominator.
          function normalize(
              uint256 numerator,
              uint256 denominator,
              uint256 maxValue
          )
              internal
              pure
              returns (
                  uint256 scaledNumerator,
                  uint256 scaledDenominator
              )
          {
              // If either the numerator or the denominator are > `maxValue`,
              // re-scale them by `maxValue` to prevent overflows in future operations.
              if (numerator > maxValue || denominator > maxValue) {
                  uint256 rescaleBase = numerator >= denominator ? numerator : denominator;
                  rescaleBase = rescaleBase.safeDiv(maxValue);
                  scaledNumerator = numerator.safeDiv(rescaleBase);
                  scaledDenominator = denominator.safeDiv(rescaleBase);
              } else {
                  scaledNumerator = numerator;
                  scaledDenominator = denominator;
              }
              return (scaledNumerator, scaledDenominator);
          }
          /// @dev Rescales a fraction to prevent overflows during addition if either
          ///      the numerator or the denominator are > 2 ** 127.
          /// @param numerator The numerator.
          /// @param denominator The denominator.
          /// @return scaledNumerator The rescaled numerator.
          /// @return scaledDenominator The rescaled denominator.
          function normalize(
              uint256 numerator,
              uint256 denominator
          )
              internal
              pure
              returns (
                  uint256 scaledNumerator,
                  uint256 scaledDenominator
              )
          {
              return normalize(numerator, denominator, 2 ** 127);
          }
          /// @dev Safely scales the difference between two fractions.
          /// @param n1 numerator of `1`
          /// @param d1 denominator of `1`
          /// @param n2 numerator of `2`
          /// @param d2 denominator of `2`
          /// @param s scalar to multiply by difference.
          /// @return result `s * (n1/d1 - n2/d2)`.
          function scaleDifference(
              uint256 n1,
              uint256 d1,
              uint256 n2,
              uint256 d2,
              uint256 s
          )
              internal
              pure
              returns (uint256 result)
          {
              if (s == 0) {
                  return 0;
              }
              if (n2 == 0) {
                  return result = s
                      .safeMul(n1)
                      .safeDiv(d1);
              }
              uint256 numerator = n1
                  .safeMul(d2)
                  .safeSub(n2.safeMul(d1));
              uint256 tmp = numerator.safeDiv(d2);
              return s
                  .safeMul(tmp)
                  .safeDiv(d1);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../interfaces/IStructs.sol";
      import "../immutable/MixinDeploymentConstants.sol";
      import "./MixinStakeStorage.sol";
      contract MixinStakeBalances is
          MixinStakeStorage,
          MixinDeploymentConstants
      {
          using LibSafeMath for uint256;
          /// @dev Gets global stake for a given status.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Global stake for given status.
          function getGlobalStakeByStatus(IStructs.StakeStatus stakeStatus)
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(
                  _globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)]
              );
              if (stakeStatus == IStructs.StakeStatus.UNDELEGATED) {
                  // Undelegated stake is the difference between total stake and delegated stake
                  // Note that any ZRX erroneously sent to the vault will be counted as undelegated stake
                  uint256 totalStake = getZrxVault().balanceOfZrxVault();
                  balance.currentEpochBalance = totalStake.safeSub(balance.currentEpochBalance).downcastToUint96();
                  balance.nextEpochBalance = totalStake.safeSub(balance.nextEpochBalance).downcastToUint96();
              }
              return balance;
          }
          /// @dev Gets an owner's stake balances by status.
          /// @param staker Owner of stake.
          /// @param stakeStatus UNDELEGATED or DELEGATED
          /// @return Owner's stake balances for given status.
          function getOwnerStakeByStatus(
              address staker,
              IStructs.StakeStatus stakeStatus
          )
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(
                  _ownerStakeByStatus[uint8(stakeStatus)][staker]
              );
              return balance;
          }
          /// @dev Returns the total stake for a given staker.
          /// @param staker of stake.
          /// @return Total ZRX staked by `staker`.
          function getTotalStake(address staker)
              public
              view
              returns (uint256)
          {
              return getZrxVault().balanceOf(staker);
          }
          /// @dev Returns the stake delegated to a specific staking pool, by a given staker.
          /// @param staker of stake.
          /// @param poolId Unique Id of pool.
          /// @return Stake delegated to pool by staker.
          function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(_delegatedStakeToPoolByOwner[staker][poolId]);
              return balance;
          }
          /// @dev Returns the total stake delegated to a specific staking pool,
          ///      across all members.
          /// @param poolId Unique Id of pool.
          /// @return Total stake delegated to pool.
          function getTotalStakeDelegatedToPool(bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = _loadCurrentBalance(_delegatedStakeByPoolId[poolId]);
              return balance;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
      import "../interfaces/IZrxVault.sol";
      // solhint-disable separate-by-one-line-in-contract
      contract MixinDeploymentConstants {
          // @TODO SET THESE VALUES FOR DEPLOYMENT
          // Mainnet WETH9 Address
          address constant private WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
          // Kovan WETH9 Address
          // address constant private WETH_ADDRESS = address(0xd0A1E359811322d97991E03f863a0C30C2cF029C);
          // Ropsten & Rinkeby WETH9 Address
          // address constant private WETH_ADDRESS = address(0xc778417E063141139Fce010982780140Aa0cD5Ab);
          // @TODO SET THESE VALUES FOR DEPLOYMENT
          // Mainnet ZrxVault address
          address constant private ZRX_VAULT_ADDRESS = address(0xBa7f8b5fB1b19c1211c5d49550fcD149177A5Eaf);
          // Kovan ZrxVault address
          // address constant private ZRX_VAULT_ADDRESS = address(0xf36eabdFE986B35b62c8FD5a98A7f2aEBB79B291);
          // Ropsten ZrxVault address
          // address constant private ZRX_VAULT_ADDRESS = address(0xffD161026865Ad8B4aB28a76840474935eEc4DfA);
          // Rinkeby ZrxVault address
          // address constant private ZRX_VAULT_ADDRESS = address(0xA5Bf6aC73bC40790FC6Ffc9DBbbCE76c9176e224);
          /// @dev An overridable way to access the deployed WETH contract.
          ///      Must be view to allow overrides to access state.
          /// @return wethContract The WETH contract instance.
          function getWethContract()
              public
              view
              returns (IEtherToken wethContract)
          {
              wethContract = IEtherToken(WETH_ADDRESS);
              return wethContract;
          }
          /// @dev An overridable way to access the deployed zrxVault.
          ///      Must be view to allow overrides to access state.
          /// @return zrxVault The zrxVault contract.
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              zrxVault = IZrxVault(ZRX_VAULT_ADDRESS);
              return zrxVault;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "../libs/LibSafeDowncast.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../interfaces/IStructs.sol";
      import "../sys/MixinScheduler.sol";
      /// @dev This mixin contains logic for managing stake storage.
      contract MixinStakeStorage is
          MixinScheduler
      {
          using LibSafeMath for uint256;
          using LibSafeDowncast for uint256;
          /// @dev Moves stake between states: 'undelegated' or 'delegated'.
          ///      This change comes into effect next epoch.
          /// @param fromPtr pointer to storage location of `from` stake.
          /// @param toPtr pointer to storage location of `to` stake.
          /// @param amount of stake to move.
          function _moveStake(
              IStructs.StoredBalance storage fromPtr,
              IStructs.StoredBalance storage toPtr,
              uint256 amount
          )
              internal
          {
              // do nothing if pointers are equal
              if (_arePointersEqual(fromPtr, toPtr)) {
                  return;
              }
              // load current balances from storage
              IStructs.StoredBalance memory from = _loadCurrentBalance(fromPtr);
              IStructs.StoredBalance memory to = _loadCurrentBalance(toPtr);
              // sanity check on balance
              if (amount > from.nextEpochBalance) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InsufficientBalanceError(
                          amount,
                          from.nextEpochBalance
                      )
                  );
              }
              // move stake for next epoch
              from.nextEpochBalance = uint256(from.nextEpochBalance).safeSub(amount).downcastToUint96();
              to.nextEpochBalance = uint256(to.nextEpochBalance).safeAdd(amount).downcastToUint96();
              // update state in storage
              _storeBalance(fromPtr, from);
              _storeBalance(toPtr, to);
          }
          /// @dev Loads a balance from storage and updates its fields to reflect values for the current epoch.
          /// @param balancePtr to load.
          /// @return current balance.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
              uint256 currentEpoch_ = currentEpoch;
              if (currentEpoch_ > balance.currentEpoch) {
                  balance.currentEpoch = currentEpoch_.downcastToUint64();
                  balance.currentEpochBalance = balance.nextEpochBalance;
              }
              return balance;
          }
          /// @dev Increments both the `current` and `next` fields.
          /// @param balancePtr storage pointer to balance.
          /// @param amount to mint.
          function _increaseCurrentAndNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Remove stake from balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeAdd(amount).downcastToUint96();
              balance.currentEpochBalance = uint256(balance.currentEpochBalance).safeAdd(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Decrements both the `current` and `next` fields.
          /// @param balancePtr storage pointer to balance.
          /// @param amount to mint.
          function _decreaseCurrentAndNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Remove stake from balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeSub(amount).downcastToUint96();
              balance.currentEpochBalance = uint256(balance.currentEpochBalance).safeSub(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Increments the `next` field (but not the `current` field).
          /// @param balancePtr storage pointer to balance.
          /// @param amount to increment by.
          function _increaseNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Add stake to balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeAdd(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Decrements the `next` field (but not the `current` field).
          /// @param balancePtr storage pointer to balance.
          /// @param amount to decrement by.
          function _decreaseNextBalance(IStructs.StoredBalance storage balancePtr, uint256 amount)
              internal
          {
              // Remove stake from balance
              IStructs.StoredBalance memory balance = _loadCurrentBalance(balancePtr);
              balance.nextEpochBalance = uint256(balance.nextEpochBalance).safeSub(amount).downcastToUint96();
              // update state
              _storeBalance(balancePtr, balance);
          }
          /// @dev Stores a balance in storage.
          /// @param balancePtr points to where `balance` will be stored.
          /// @param balance to save to storage.
          function _storeBalance(
              IStructs.StoredBalance storage balancePtr,
              IStructs.StoredBalance memory balance
          )
              private
          {
              // note - this compresses into a single `sstore` when optimizations are enabled,
              // since the StoredBalance struct occupies a single word of storage.
              balancePtr.currentEpoch = balance.currentEpoch;
              balancePtr.nextEpochBalance = balance.nextEpochBalance;
              balancePtr.currentEpochBalance = balance.currentEpochBalance;
          }
          /// @dev Returns true iff storage pointers resolve to same storage location.
          /// @param balancePtrA first storage pointer.
          /// @param balancePtrB second storage pointer.
          /// @return true iff pointers are equal.
          function _arePointersEqual(
              // solhint-disable-next-line no-unused-vars
              IStructs.StoredBalance storage balancePtrA,
              // solhint-disable-next-line no-unused-vars
              IStructs.StoredBalance storage balancePtrB
          )
              private
              pure
              returns (bool areEqual)
          {
              assembly {
                  areEqual := and(
                      eq(balancePtrA_slot, balancePtrB_slot),
                      eq(balancePtrA_offset, balancePtrB_offset)
                  )
              }
              return areEqual;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMathRichErrors.sol";
      library LibSafeDowncast {
          /// @dev Safely downcasts to a uint96
          /// Note that this reverts if the input value is too large.
          function downcastToUint96(uint256 a)
              internal
              pure
              returns (uint96 b)
          {
              b = uint96(a);
              if (uint256(b) != a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256DowncastError(
                      LibSafeMathRichErrors.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96,
                      a
                  ));
              }
              return b;
          }
          /// @dev Safely downcasts to a uint64
          /// Note that this reverts if the input value is too large.
          function downcastToUint64(uint256 a)
              internal
              pure
              returns (uint64 b)
          {
              b = uint64(a);
              if (uint256(b) != a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256DowncastError(
                      LibSafeMathRichErrors.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
                      a
                  ));
              }
              return b;
          }
          /// @dev Safely downcasts to a uint32
          /// Note that this reverts if the input value is too large.
          function downcastToUint32(uint256 a)
              internal
              pure
              returns (uint32 b)
          {
              b = uint32(a);
              if (uint256(b) != a) {
                  LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256DowncastError(
                      LibSafeMathRichErrors.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
                      a
                  ));
              }
              return b;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../immutable/MixinStorage.sol";
      import "../interfaces/IStakingEvents.sol";
      contract MixinScheduler is
          IStakingEvents,
          MixinStorage
      {
          using LibSafeMath for uint256;
          /// @dev Returns the earliest end time in seconds of this epoch.
          ///      The next epoch can begin once this time is reached.
          ///      Epoch period = [startTimeInSeconds..endTimeInSeconds)
          /// @return Time in seconds.
          function getCurrentEpochEarliestEndTimeInSeconds()
              public
              view
              returns (uint256)
          {
              return currentEpochStartTimeInSeconds.safeAdd(epochDurationInSeconds);
          }
          /// @dev Initializes state owned by this mixin.
          ///      Fails if state was already initialized.
          function _initMixinScheduler()
              internal
          {
              // assert the current values before overwriting them.
              _assertSchedulerNotInitialized();
              // solhint-disable-next-line
              currentEpochStartTimeInSeconds = block.timestamp;
              currentEpoch = 1;
          }
          /// @dev Moves to the next epoch, given the current epoch period has ended.
          ///      Time intervals that are measured in epochs (like timeLocks) are also incremented, given
          ///      their periods have ended.
          function _goToNextEpoch()
              internal
          {
              // get current timestamp
              // solhint-disable-next-line not-rely-on-time
              uint256 currentBlockTimestamp = block.timestamp;
              // validate that we can increment the current epoch
              uint256 epochEndTime = getCurrentEpochEarliestEndTimeInSeconds();
              if (epochEndTime > currentBlockTimestamp) {
                  LibRichErrors.rrevert(LibStakingRichErrors.BlockTimestampTooLowError(
                      epochEndTime,
                      currentBlockTimestamp
                  ));
              }
              // incremment epoch
              uint256 nextEpoch = currentEpoch.safeAdd(1);
              currentEpoch = nextEpoch;
              currentEpochStartTimeInSeconds = currentBlockTimestamp;
          }
          /// @dev Assert scheduler state before initializing it.
          /// This must be updated for each migration.
          function _assertSchedulerNotInitialized()
              internal
              view
          {
              if (currentEpochStartTimeInSeconds != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InitializationError(
                          LibStakingRichErrors.InitializationErrorCodes.MixinSchedulerAlreadyInitialized
                      )
                  );
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStructs.sol";
      import "../sys/MixinFinalizer.sol";
      import "../staking_pools/MixinStakingPool.sol";
      import "./MixinExchangeManager.sol";
      contract MixinExchangeFees is
          MixinExchangeManager,
          MixinStakingPool,
          MixinFinalizer
      {
          using LibSafeMath for uint256;
          /// @dev Pays a protocol fee in ETH or WETH.
          ///      Only a known 0x exchange can call this method. See
          ///      (MixinExchangeManager).
          /// @param makerAddress The address of the order's maker.
          /// @param payerAddress The address of the protocol fee payer.
          /// @param protocolFee The protocol fee amount. This is either passed as ETH or transferred as WETH.
          function payProtocolFee(
              address makerAddress,
              address payerAddress,
              uint256 protocolFee
          )
              external
              payable
              onlyExchange
          {
              _assertValidProtocolFee(protocolFee);
              // Transfer the protocol fee to this address if it should be paid in
              // WETH.
              if (msg.value == 0) {
                  require(
                      getWethContract().transferFrom(
                          payerAddress,
                          address(this),
                          protocolFee
                      ),
                      "WETH_TRANSFER_FAILED"
                  );
              }
              // Get the pool id of the maker address.
              bytes32 poolId = poolIdByMaker[makerAddress];
              // Only attribute the protocol fee payment to a pool if the maker is
              // registered to a pool.
              if (poolId == NIL_POOL_ID) {
                  return;
              }
              uint256 poolStake = getTotalStakeDelegatedToPool(poolId).currentEpochBalance;
              // Ignore pools with dust stake.
              if (poolStake < minimumPoolStake) {
                  return;
              }
              // Look up the pool stats and aggregated stats for this epoch.
              uint256 currentEpoch_ = currentEpoch;
              IStructs.PoolStats storage poolStatsPtr = poolStatsByEpoch[poolId][currentEpoch_];
              IStructs.AggregatedStats storage aggregatedStatsPtr = aggregatedStatsByEpoch[currentEpoch_];
              // Perform some initialization if this is the pool's first protocol fee in this epoch.
              uint256 feesCollectedByPool = poolStatsPtr.feesCollected;
              if (feesCollectedByPool == 0) {
                  // Compute member and total weighted stake.
                  (uint256 membersStakeInPool, uint256 weightedStakeInPool) = _computeMembersAndWeightedStake(poolId, poolStake);
                  poolStatsPtr.membersStake = membersStakeInPool;
                  poolStatsPtr.weightedStake = weightedStakeInPool;
                  // Increase the total weighted stake.
                  aggregatedStatsPtr.totalWeightedStake = aggregatedStatsPtr.totalWeightedStake.safeAdd(weightedStakeInPool);
                  // Increase the number of pools to finalize.
                  aggregatedStatsPtr.numPoolsToFinalize = aggregatedStatsPtr.numPoolsToFinalize.safeAdd(1);
                  // Emit an event so keepers know what pools earned rewards this epoch.
                  emit StakingPoolEarnedRewardsInEpoch(currentEpoch_, poolId);
              }
              // Credit the fees to the pool.
              poolStatsPtr.feesCollected = feesCollectedByPool.safeAdd(protocolFee);
              // Increase the total fees collected this epoch.
              aggregatedStatsPtr.totalFeesCollected = aggregatedStatsPtr.totalFeesCollected.safeAdd(protocolFee);
          }
          /// @dev Get stats on a staking pool in this epoch.
          /// @param poolId Pool Id to query.
          /// @return PoolStats struct for pool id.
          function getStakingPoolStatsThisEpoch(bytes32 poolId)
              external
              view
              returns (IStructs.PoolStats memory)
          {
              return poolStatsByEpoch[poolId][currentEpoch];
          }
          /// @dev Computes the members and weighted stake for a pool at the current
          ///      epoch.
          /// @param poolId ID of the pool.
          /// @param totalStake Total (unweighted) stake in the pool.
          /// @return membersStake Non-operator stake in the pool.
          /// @return weightedStake Weighted stake of the pool.
          function _computeMembersAndWeightedStake(
              bytes32 poolId,
              uint256 totalStake
          )
              private
              view
              returns (uint256 membersStake, uint256 weightedStake)
          {
              uint256 operatorStake = getStakeDelegatedToPoolByOwner(
                  _poolById[poolId].operator,
                  poolId
              ).currentEpochBalance;
              membersStake = totalStake.safeSub(operatorStake);
              weightedStake = operatorStake.safeAdd(
                  LibMath.getPartialAmountFloor(
                      rewardDelegatedStakeWeight,
                      PPM_DENOMINATOR,
                      membersStake
                  )
              );
              return (membersStake, weightedStake);
          }
          /// @dev Checks that the protocol fee passed into `payProtocolFee()` is
          ///      valid.
          /// @param protocolFee The `protocolFee` parameter to
          ///        `payProtocolFee.`
          function _assertValidProtocolFee(uint256 protocolFee)
              private
              view
          {
              // The protocol fee must equal the value passed to the contract; unless
              // the value is zero, in which case the fee is taken in WETH.
              if (msg.value != protocolFee && msg.value != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.InvalidProtocolFeePaymentError(
                          protocolFee,
                          msg.value
                      )
                  );
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
      import "../libs/LibCobbDouglas.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStructs.sol";
      import "../staking_pools/MixinStakingPoolRewards.sol";
      contract MixinFinalizer is
          MixinStakingPoolRewards
      {
          using LibSafeMath for uint256;
          /// @dev Begins a new epoch, preparing the prior one for finalization.
          ///      Throws if not enough time has passed between epochs or if the
          ///      previous epoch was not fully finalized.
          /// @return numPoolsToFinalize The number of unfinalized pools.
          function endEpoch()
              external
              returns (uint256)
          {
              uint256 currentEpoch_ = currentEpoch;
              uint256 prevEpoch = currentEpoch_.safeSub(1);
              // Make sure the previous epoch has been fully finalized.
              uint256 numPoolsToFinalizeFromPrevEpoch = aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize;
              if (numPoolsToFinalizeFromPrevEpoch != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.PreviousEpochNotFinalizedError(
                          prevEpoch,
                          numPoolsToFinalizeFromPrevEpoch
                      )
                  );
              }
              // Convert all ETH to WETH; the WETH balance of this contract is the total rewards.
              _wrapEth();
              // Load aggregated stats for the epoch we're ending.
              aggregatedStatsByEpoch[currentEpoch_].rewardsAvailable = _getAvailableWethBalance();
              IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[currentEpoch_];
              // Emit an event.
              emit EpochEnded(
                  currentEpoch_,
                  aggregatedStats.numPoolsToFinalize,
                  aggregatedStats.rewardsAvailable,
                  aggregatedStats.totalFeesCollected,
                  aggregatedStats.totalWeightedStake
              );
              // Advance the epoch. This will revert if not enough time has passed.
              _goToNextEpoch();
              // If there are no pools to finalize then the epoch is finalized.
              if (aggregatedStats.numPoolsToFinalize == 0) {
                  emit EpochFinalized(currentEpoch_, 0, aggregatedStats.rewardsAvailable);
              }
              return aggregatedStats.numPoolsToFinalize;
          }
          /// @dev Instantly finalizes a single pool that earned rewards in the previous
          ///      epoch, crediting it rewards for members and withdrawing operator's
          ///      rewards as WETH. This can be called by internal functions that need
          ///      to finalize a pool immediately. Does nothing if the pool is already
          ///      finalized or did not earn rewards in the previous epoch.
          /// @param poolId The pool ID to finalize.
          function finalizePool(bytes32 poolId)
              external
          {
              // Compute relevant epochs
              uint256 currentEpoch_ = currentEpoch;
              uint256 prevEpoch = currentEpoch_.safeSub(1);
              // Load the aggregated stats into memory; noop if no pools to finalize.
              IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[prevEpoch];
              if (aggregatedStats.numPoolsToFinalize == 0) {
                  return;
              }
              // Noop if the pool did not earn rewards or already finalized (has no fees).
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
              if (poolStats.feesCollected == 0) {
                  return;
              }
              // Clear the pool stats so we don't finalize it again, and to recoup
              // some gas.
              delete poolStatsByEpoch[poolId][prevEpoch];
              // Compute the rewards.
              uint256 rewards = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStats);
              // Pay the operator and update rewards for the pool.
              // Note that we credit at the CURRENT epoch even though these rewards
              // were earned in the previous epoch.
              (uint256 operatorReward, uint256 membersReward) = _syncPoolRewards(
                  poolId,
                  rewards,
                  poolStats.membersStake
              );
              // Emit an event.
              emit RewardsPaid(
                  currentEpoch_,
                  poolId,
                  operatorReward,
                  membersReward
              );
              uint256 totalReward = operatorReward.safeAdd(membersReward);
              // Increase `totalRewardsFinalized`.
              aggregatedStatsByEpoch[prevEpoch].totalRewardsFinalized =
                  aggregatedStats.totalRewardsFinalized =
                  aggregatedStats.totalRewardsFinalized.safeAdd(totalReward);
              // Decrease the number of unfinalized pools left.
              aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize =
                  aggregatedStats.numPoolsToFinalize =
                  aggregatedStats.numPoolsToFinalize.safeSub(1);
              // If there are no more unfinalized pools remaining, the epoch is
              // finalized.
              if (aggregatedStats.numPoolsToFinalize == 0) {
                  emit EpochFinalized(
                      prevEpoch,
                      aggregatedStats.totalRewardsFinalized,
                      aggregatedStats.rewardsAvailable.safeSub(aggregatedStats.totalRewardsFinalized)
                  );
              }
          }
          /// @dev Computes the reward owed to a pool during finalization.
          ///      Does nothing if the pool is already finalized.
          /// @param poolId The pool's ID.
          /// @return totalReward The total reward owed to a pool.
          /// @return membersStake The total stake for all non-operator members in
          ///         this pool.
          function _getUnfinalizedPoolRewards(bytes32 poolId)
              internal
              view
              returns (
                  uint256 reward,
                  uint256 membersStake
              )
          {
              uint256 prevEpoch = currentEpoch.safeSub(1);
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
              reward = _getUnfinalizedPoolRewardsFromPoolStats(poolStats, aggregatedStatsByEpoch[prevEpoch]);
              membersStake = poolStats.membersStake;
          }
          /// @dev Converts the entire ETH balance of this contract into WETH.
          function _wrapEth()
              internal
          {
              uint256 ethBalance = address(this).balance;
              if (ethBalance != 0) {
                  getWethContract().deposit.value(ethBalance)();
              }
          }
          /// @dev Returns the WETH balance of this contract, minus
          ///      any WETH that has already been reserved for rewards.
          function _getAvailableWethBalance()
              internal
              view
              returns (uint256 wethBalance)
          {
              wethBalance = getWethContract().balanceOf(address(this))
                  .safeSub(wethReservedForPoolRewards);
              return wethBalance;
          }
          /// @dev Asserts that a pool has been finalized last epoch.
          /// @param poolId The id of the pool that should have been finalized.
          function _assertPoolFinalizedLastEpoch(bytes32 poolId)
              internal
              view
          {
              uint256 prevEpoch = currentEpoch.safeSub(1);
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][prevEpoch];
              // A pool that has any fees remaining has not been finalized
              if (poolStats.feesCollected != 0) {
                  LibRichErrors.rrevert(
                      LibStakingRichErrors.PoolNotFinalizedError(
                          poolId,
                          prevEpoch
                      )
                  );
              }
          }
          /// @dev Computes the reward owed to a pool during finalization.
          /// @param poolStats Stats for a specific pool.
          /// @param aggregatedStats Stats aggregated across all pools.
          /// @return rewards Unfinalized rewards for the input pool.
          function _getUnfinalizedPoolRewardsFromPoolStats(
              IStructs.PoolStats memory poolStats,
              IStructs.AggregatedStats memory aggregatedStats
          )
              private
              view
              returns (uint256 rewards)
          {
              // There can't be any rewards if the pool did not collect any fees.
              if (poolStats.feesCollected == 0) {
                  return rewards;
              }
              // Use the cobb-douglas function to compute the total reward.
              rewards = LibCobbDouglas.cobbDouglas(
                  aggregatedStats.rewardsAvailable,
                  poolStats.feesCollected,
                  aggregatedStats.totalFeesCollected,
                  poolStats.weightedStake,
                  aggregatedStats.totalWeightedStake,
                  cobbDouglasAlphaNumerator,
                  cobbDouglasAlphaDenominator
              );
              // Clip the reward to always be under
              // `rewardsAvailable - totalRewardsPaid`,
              // in case cobb-douglas overflows, which should be unlikely.
              uint256 rewardsRemaining = aggregatedStats.rewardsAvailable.safeSub(aggregatedStats.totalRewardsFinalized);
              if (rewardsRemaining < rewards) {
                  rewards = rewardsRemaining;
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./LibFixedMath.sol";
      library LibCobbDouglas {
          /// @dev The cobb-douglas function used to compute fee-based rewards for
          ///      staking pools in a given epoch. This function does not perform
          ///      bounds checking on the inputs, but the following conditions
          ///      need to be true:
          ///         0 <= fees / totalFees <= 1
          ///         0 <= stake / totalStake <= 1
          ///         0 <= alphaNumerator / alphaDenominator <= 1
          /// @param totalRewards collected over an epoch.
          /// @param fees Fees attributed to the the staking pool.
          /// @param totalFees Total fees collected across all pools that earned rewards.
          /// @param stake Stake attributed to the staking pool.
          /// @param totalStake Total stake across all pools that earned rewards.
          /// @param alphaNumerator Numerator of `alpha` in the cobb-douglas function.
          /// @param alphaDenominator Denominator of `alpha` in the cobb-douglas
          ///        function.
          /// @return rewards Rewards owed to the staking pool.
          function cobbDouglas(
              uint256 totalRewards,
              uint256 fees,
              uint256 totalFees,
              uint256 stake,
              uint256 totalStake,
              uint32 alphaNumerator,
              uint32 alphaDenominator
          )
              internal
              pure
              returns (uint256 rewards)
          {
              int256 feeRatio = LibFixedMath.toFixed(fees, totalFees);
              int256 stakeRatio = LibFixedMath.toFixed(stake, totalStake);
              if (feeRatio == 0 || stakeRatio == 0) {
                  return rewards = 0;
              }
              // The cobb-doublas function has the form:
              // `totalRewards * feeRatio ^ alpha * stakeRatio ^ (1-alpha)`
              // This is equivalent to:
              // `totalRewards * stakeRatio * e^(alpha * (ln(feeRatio / stakeRatio)))`
              // However, because `ln(x)` has the domain of `0 < x < 1`
              // and `exp(x)` has the domain of `x < 0`,
              // and fixed-point math easily overflows with multiplication,
              // we will choose the following if `stakeRatio > feeRatio`:
              // `totalRewards * stakeRatio / e^(alpha * (ln(stakeRatio / feeRatio)))`
              // Compute
              // `e^(alpha * ln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio
              // or
              // `e^(alpa * ln(stakeRatio/feeRatio))` if feeRatio > stakeRatio
              int256 n = feeRatio <= stakeRatio ?
                  LibFixedMath.div(feeRatio, stakeRatio) :
                  LibFixedMath.div(stakeRatio, feeRatio);
              n = LibFixedMath.exp(
                  LibFixedMath.mulDiv(
                      LibFixedMath.ln(n),
                      int256(alphaNumerator),
                      int256(alphaDenominator)
                  )
              );
              // Compute
              // `totalRewards * n` if feeRatio <= stakeRatio
              // or
              // `totalRewards / n` if stakeRatio > feeRatio
              // depending on the choice we made earlier.
              n = feeRatio <= stakeRatio ?
                  LibFixedMath.mul(stakeRatio, n) :
                  LibFixedMath.div(stakeRatio, n);
              // Multiply the above with totalRewards.
              rewards = LibFixedMath.uintMul(n, totalRewards);
          }
      }
      /*
        Copyright 2017 Bprotocol Foundation, 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./LibFixedMathRichErrors.sol";
      // solhint-disable indent
      /// @dev Signed, fixed-point, 127-bit precision math library.
      library LibFixedMath {
          // 1
          int256 private constant FIXED_1 = int256(0x0000000000000000000000000000000080000000000000000000000000000000);
          // 2**255
          int256 private constant MIN_FIXED_VAL = int256(0x8000000000000000000000000000000000000000000000000000000000000000);
          // 1^2 (in fixed-point)
          int256 private constant FIXED_1_SQUARED = int256(0x4000000000000000000000000000000000000000000000000000000000000000);
          // 1
          int256 private constant LN_MAX_VAL = FIXED_1;
          // e ^ -63.875
          int256 private constant LN_MIN_VAL = int256(0x0000000000000000000000000000000000000000000000000000000733048c5a);
          // 0
          int256 private constant EXP_MAX_VAL = 0;
          // -63.875
          int256 private constant EXP_MIN_VAL = -int256(0x0000000000000000000000000000001ff0000000000000000000000000000000);
          /// @dev Get one as a fixed-point number.
          function one() internal pure returns (int256 f) {
              f = FIXED_1;
          }
          /// @dev Returns the addition of two fixed point numbers, reverting on overflow.
          function add(int256 a, int256 b) internal pure returns (int256 c) {
              c = _add(a, b);
          }
          /// @dev Returns the addition of two fixed point numbers, reverting on overflow.
          function sub(int256 a, int256 b) internal pure returns (int256 c) {
              if (b == MIN_FIXED_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_SMALL,
                      b
                  ));
              }
              c = _add(a, -b);
          }
          /// @dev Returns the multiplication of two fixed point numbers, reverting on overflow.
          function mul(int256 a, int256 b) internal pure returns (int256 c) {
              c = _mul(a, b) / FIXED_1;
          }
          /// @dev Returns the division of two fixed point numbers.
          function div(int256 a, int256 b) internal pure returns (int256 c) {
              c = _div(_mul(a, FIXED_1), b);
          }
          /// @dev Performs (a * n) / d, without scaling for precision.
          function mulDiv(int256 a, int256 n, int256 d) internal pure returns (int256 c) {
              c = _div(_mul(a, n), d);
          }
          /// @dev Returns the unsigned integer result of multiplying a fixed-point
          ///      number with an integer, reverting if the multiplication overflows.
          ///      Negative results are clamped to zero.
          function uintMul(int256 f, uint256 u) internal pure returns (uint256) {
              if (int256(u) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      u
                  ));
              }
              int256 c = _mul(f, int256(u));
              if (c <= 0) {
                  return 0;
              }
              return uint256(uint256(c) >> 127);
          }
          /// @dev Returns the absolute value of a fixed point number.
          function abs(int256 f) internal pure returns (int256 c) {
              if (f == MIN_FIXED_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_SMALL,
                      f
                  ));
              }
              if (f >= 0) {
                  c = f;
              } else {
                  c = -f;
              }
          }
          /// @dev Returns 1 / `x`, where `x` is a fixed-point number.
          function invert(int256 f) internal pure returns (int256 c) {
              c = _div(FIXED_1_SQUARED, f);
          }
          /// @dev Convert signed `n` / 1 to a fixed-point number.
          function toFixed(int256 n) internal pure returns (int256 f) {
              f = _mul(n, FIXED_1);
          }
          /// @dev Convert signed `n` / `d` to a fixed-point number.
          function toFixed(int256 n, int256 d) internal pure returns (int256 f) {
              f = _div(_mul(n, FIXED_1), d);
          }
          /// @dev Convert unsigned `n` / 1 to a fixed-point number.
          ///      Reverts if `n` is too large to fit in a fixed-point number.
          function toFixed(uint256 n) internal pure returns (int256 f) {
              if (int256(n) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      n
                  ));
              }
              f = _mul(int256(n), FIXED_1);
          }
          /// @dev Convert unsigned `n` / `d` to a fixed-point number.
          ///      Reverts if `n` / `d` is too large to fit in a fixed-point number.
          function toFixed(uint256 n, uint256 d) internal pure returns (int256 f) {
              if (int256(n) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      n
                  ));
              }
              if (int256(d) < int256(0)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.UnsignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      d
                  ));
              }
              f = _div(_mul(int256(n), FIXED_1), int256(d));
          }
          /// @dev Convert a fixed-point number to an integer.
          function toInteger(int256 f) internal pure returns (int256 n) {
              return f / FIXED_1;
          }
          /// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL
          function ln(int256 x) internal pure returns (int256 r) {
              if (x > LN_MAX_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      x
                  ));
              }
              if (x <= 0) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_SMALL,
                      x
                  ));
              }
              if (x == FIXED_1) {
                  return 0;
              }
              if (x <= LN_MIN_VAL) {
                  return EXP_MIN_VAL;
              }
              int256 y;
              int256 z;
              int256 w;
              // Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2
              // For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522)
              //              = 1 - 0.25 - log(1 + 0.0471028872385522)
              // e ^ -32
              if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) {
                  r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32
                  x = x * FIXED_1 / int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32
              }
              // e ^ -16
              if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) {
                  r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16
                  x = x * FIXED_1 / int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16
              }
              // e ^ -8
              if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8
                  x = x * FIXED_1 / int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8
              }
              // e ^ -4
              if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4
                  x = x * FIXED_1 / int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4
              }
              // e ^ -2
              if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2
                  x = x * FIXED_1 / int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2
              }
              // e ^ -1
              if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1
                  x = x * FIXED_1 / int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1
              }
              // e ^ -0.5
              if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5
                  x = x * FIXED_1 / int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5
              }
              // e ^ -0.25
              if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) {
                  r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25
                  x = x * FIXED_1 / int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25
              }
              // e ^ -0.125
              if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) {
                  r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125
                  x = x * FIXED_1 / int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125
              }
              // `x` is now our residual in the range of 1 <= x <= 2 (or close enough).
              // Add the taylor series for log(1 + z), where z = x - 1
              z = y = x - FIXED_1;
              w = y * y / FIXED_1;
              r += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
              r += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
              r += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
              r += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
              r += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
              r += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
              r += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
              r += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000;                      // add y^15 / 15 - y^16 / 16
          }
          /// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1
          function exp(int256 x) internal pure returns (int256 r) {
              if (x < EXP_MIN_VAL) {
                  // Saturate to zero below EXP_MIN_VAL.
                  return 0;
              }
              if (x == 0) {
                  return FIXED_1;
              }
              if (x > EXP_MAX_VAL) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
                      LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
                      x
                  ));
              }
              // Rewrite the input as a product of natural exponents and a
              // single residual q, where q is a number of small magnitude.
              // For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044)
              //              = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044
              //              -> q = -0.044
              // Multiply with the taylor series for e^q
              int256 y;
              int256 z;
              // q = x % 0.125 (the residual)
              z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000;
              z = z * y / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
              z = z * y / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
              z = z * y / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
              z = z * y / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
              z = z * y / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
              z = z * y / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
              z = z * y / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
              z = z * y / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
              z = z * y / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
              z = z * y / FIXED_1; r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
              z = z * y / FIXED_1; r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
              z = z * y / FIXED_1; r += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
              z = z * y / FIXED_1; r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
              z = z * y / FIXED_1; r += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
              z = z * y / FIXED_1; r += z * 0x000000000001c638; // add y^16 * (20! / 16!)
              z = z * y / FIXED_1; r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
              z = z * y / FIXED_1; r += z * 0x000000000000017c; // add y^18 * (20! / 18!)
              z = z * y / FIXED_1; r += z * 0x0000000000000014; // add y^19 * (20! / 19!)
              z = z * y / FIXED_1; r += z * 0x0000000000000001; // add y^20 * (20! / 20!)
              r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
              // Multiply with the non-residual terms.
              x = -x;
              // e ^ -32
              if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) {
                  r = r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)
                      / int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32
              }
              // e ^ -16
              if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) {
                  r = r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)
                      / int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16
              }
              // e ^ -8
              if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) {
                  r = r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)
                      / int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8
              }
              // e ^ -4
              if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) {
                  r = r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)
                      / int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4
              }
              // e ^ -2
              if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) {
                  r = r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)
                      / int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2
              }
              // e ^ -1
              if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) {
                  r = r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)
                      / int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1
              }
              // e ^ -0.5
              if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) {
                  r = r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)
                      / int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5
              }
              // e ^ -0.25
              if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) {
                  r = r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)
                      / int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25
              }
              // e ^ -0.125
              if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) {
                  r = r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)
                      / int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125
              }
          }
          /// @dev Returns the multiplication two numbers, reverting on overflow.
          function _mul(int256 a, int256 b) private pure returns (int256 c) {
              if (a == 0) {
                  return 0;
              }
              c = a * b;
              if (c / a != b || c / b != a) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
                      a,
                      b
                  ));
              }
          }
          /// @dev Returns the division of two numbers, reverting on division by zero.
          function _div(int256 a, int256 b) private pure returns (int256 c) {
              if (b == 0) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
                      a,
                      b
                  ));
              }
              if (a == MIN_FIXED_VAL && b == -1) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.DIVISION_OVERFLOW,
                      a,
                      b
                  ));
              }
              c = a / b;
          }
          /// @dev Adds two numbers, reverting on overflow.
          function _add(int256 a, int256 b) private pure returns (int256 c) {
              c = a + b;
              if ((a < 0 && b < 0 && c > a) || (a > 0 && b > 0 && c < a)) {
                  LibRichErrors.rrevert(LibFixedMathRichErrors.BinOpError(
                      LibFixedMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
                      a,
                      b
                  ));
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      library LibFixedMathRichErrors {
          enum ValueErrorCodes {
              TOO_SMALL,
              TOO_LARGE
          }
          enum BinOpErrorCodes {
              ADDITION_OVERFLOW,
              MULTIPLICATION_OVERFLOW,
              DIVISION_BY_ZERO,
              DIVISION_OVERFLOW
          }
          // bytes4(keccak256("SignedValueError(uint8,int256)"))
          bytes4 internal constant SIGNED_VALUE_ERROR_SELECTOR =
              0xed2f26a1;
          // bytes4(keccak256("UnsignedValueError(uint8,uint256)"))
          bytes4 internal constant UNSIGNED_VALUE_ERROR_SELECTOR =
              0xbd79545f;
          // bytes4(keccak256("BinOpError(uint8,int256,int256)"))
          bytes4 internal constant BIN_OP_ERROR_SELECTOR =
              0x8c12dfe7;
          // solhint-disable func-name-mixedcase
          function SignedValueError(
              ValueErrorCodes error,
              int256 n
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  SIGNED_VALUE_ERROR_SELECTOR,
                  uint8(error),
                  n
              );
          }
          function UnsignedValueError(
              ValueErrorCodes error,
              uint256 n
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  UNSIGNED_VALUE_ERROR_SELECTOR,
                  uint8(error),
                  n
              );
          }
          function BinOpError(
              BinOpErrorCodes error,
              int256 a,
              int256 b
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  BIN_OP_ERROR_SELECTOR,
                  uint8(error),
                  a,
                  b
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
      import "../libs/LibStakingRichErrors.sol";
      import "../interfaces/IStakingEvents.sol";
      import "../immutable/MixinStorage.sol";
      contract MixinExchangeManager is
          IStakingEvents,
          MixinStorage
      {
          /// @dev Asserts that the call is coming from a valid exchange.
          modifier onlyExchange() {
              if (!validExchanges[msg.sender]) {
                  LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableByExchangeError(
                      msg.sender
                  ));
              }
              _;
          }
          /// @dev Adds a new exchange address
          /// @param addr Address of exchange contract to add
          function addExchangeAddress(address addr)
              external
              onlyAuthorized
          {
              if (validExchanges[addr]) {
                  LibRichErrors.rrevert(LibStakingRichErrors.ExchangeManagerError(
                      LibStakingRichErrors.ExchangeManagerErrorCodes.ExchangeAlreadyRegistered,
                      addr
                  ));
              }
              validExchanges[addr] = true;
              emit ExchangeAdded(addr);
          }
          /// @dev Removes an existing exchange address
          /// @param addr Address of exchange contract to remove
          function removeExchangeAddress(address addr)
              external
              onlyAuthorized
          {
              if (!validExchanges[addr]) {
                  LibRichErrors.rrevert(LibStakingRichErrors.ExchangeManagerError(
                      LibStakingRichErrors.ExchangeManagerErrorCodes.ExchangeNotRegistered,
                      addr
                  ));
              }
              validExchanges[addr] = false;
              emit ExchangeRemoved(addr);
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./TestStaking.sol";
      // solhint-disable no-empty-blocks
      contract TestCumulativeRewardTracking is
          TestStaking
      {
          event SetCumulativeReward(
              bytes32 poolId,
              uint256 epoch
          );
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
              TestStaking(
                  wethAddress,
                  zrxVaultAddress
              )
          {}
          function init() public {}
          function _addCumulativeReward(
              bytes32 poolId,
              uint256 reward,
              uint256 stake
          )
              internal
          {
              uint256 lastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              MixinCumulativeRewards._addCumulativeReward(
                  poolId,
                  reward,
                  stake
              );
              uint256 newLastStoredEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              if (newLastStoredEpoch != lastStoredEpoch) {
                  emit SetCumulativeReward(poolId, currentEpoch);
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
      import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
      import "../src/Staking.sol";
      contract TestStaking is
          Staking
      {
          address public testWethAddress;
          address public testZrxVaultAddress;
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
          {
              testWethAddress = wethAddress;
              testZrxVaultAddress = zrxVaultAddress;
          }
          /// @dev Sets the weth contract address.
          /// @param wethAddress The address of the weth contract.
          function setWethContract(address wethAddress)
              external
          {
              testWethAddress = wethAddress;
          }
          /// @dev Sets the zrx vault address.
          /// @param zrxVaultAddress The address of a zrx vault.
          function setZrxVault(address zrxVaultAddress)
              external
          {
              testZrxVaultAddress = zrxVaultAddress;
          }
          /// @dev Overridden to use testWethAddress;
          function getWethContract()
              public
              view
              returns (IEtherToken)
          {
              // `testWethAddress` will not be set on the proxy this contract is
              // attached to, so we need to access the storage of the deployed
              // instance of this contract.
              address wethAddress = TestStaking(address(uint160(stakingContract))).testWethAddress();
              return IEtherToken(wethAddress);
          }
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              address zrxVaultAddress = TestStaking(address(uint160(stakingContract))).testZrxVaultAddress();
              zrxVault = IZrxVault(zrxVaultAddress);
              return zrxVault;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      // solhint-disable
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      // @dev Interface of the asset proxy's assetData.
      // The asset proxies take an ABI encoded `bytes assetData` as argument.
      // This argument is ABI encoded as one of the methods of this interface.
      interface IAssetData {
          /// @dev Function signature for encoding ERC20 assetData.
          /// @param tokenAddress Address of ERC20Token contract.
          function ERC20Token(address tokenAddress)
              external;
          /// @dev Function signature for encoding ERC721 assetData.
          /// @param tokenAddress Address of ERC721 token contract.
          /// @param tokenId Id of ERC721 token to be transferred.
          function ERC721Token(
              address tokenAddress,
              uint256 tokenId
          )
              external;
          /// @dev Function signature for encoding ERC1155 assetData.
          /// @param tokenAddress Address of ERC1155 token contract.
          /// @param tokenIds Array of ids of tokens to be transferred.
          /// @param values Array of values that correspond to each token id to be transferred.
          ///        Note that each value will be multiplied by the amount being filled in the order before transferring.
          /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function.
          function ERC1155Assets(
              address tokenAddress,
              uint256[] calldata tokenIds,
              uint256[] calldata values,
              bytes calldata callbackData
          )
              external;
          /// @dev Function signature for encoding MultiAsset assetData.
          /// @param values Array of amounts that correspond to each asset to be transferred.
          ///        Note that each value will be multiplied by the amount being filled in the order before transferring.
          /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract.
          function MultiAsset(
              uint256[] calldata values,
              bytes[] calldata nestedAssetData
          )
              external;
          /// @dev Function signature for encoding StaticCall assetData.
          /// @param staticCallTargetAddress Address that will execute the staticcall.
          /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress.
          /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data.
          function StaticCall(
              address staticCallTargetAddress,
              bytes calldata staticCallData,
              bytes32 expectedReturnDataHash
          )
              external;
          /// @dev Function signature for encoding ERC20Bridge assetData.
          /// @param tokenAddress Address of token to transfer.
          /// @param bridgeAddress Address of the bridge contract.
          /// @param bridgeData Arbitrary data to be passed to the bridge contract.
          function ERC20Bridge(
              address tokenAddress,
              address bridgeAddress,
              bytes calldata bridgeData
          )
              external;
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestDelegatorRewards is
          TestStakingNoWETH
      {
          event FinalizePool(
              bytes32 poolId,
              uint256 operatorReward,
              uint256 membersReward,
              uint256 membersStake
          );
          struct UnfinalizedPoolReward {
              uint256 operatorReward;
              uint256 membersReward;
              uint256 membersStake;
          }
          constructor() public {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          mapping (uint256 => mapping (bytes32 => UnfinalizedPoolReward)) private
              unfinalizedPoolRewardsByEpoch;
          /// @dev Set unfinalized rewards for a pool in the current epoch.
          function setUnfinalizedPoolReward(
              bytes32 poolId,
              address payable operatorAddress,
              uint256 operatorReward,
              uint256 membersReward,
              uint256 membersStake
          )
              external
          {
              unfinalizedPoolRewardsByEpoch[currentEpoch][poolId] = UnfinalizedPoolReward({
                  operatorReward: operatorReward,
                  membersReward: membersReward,
                  membersStake: membersStake
              });
              // Lazily initialize this pool.
              _poolById[poolId].operator = operatorAddress;
              _setOperatorShare(poolId, operatorReward, membersReward);
          }
          /// @dev Expose/wrap `_syncPoolRewards`.
          function syncPoolRewards(
              bytes32 poolId,
              address payable operatorAddress,
              uint256 operatorReward,
              uint256 membersReward,
              uint256 membersStake
          )
              external
          {
              // Lazily initialize this pool.
              _poolById[poolId].operator = operatorAddress;
              _setOperatorShare(poolId, operatorReward, membersReward);
              _syncPoolRewards(
                  poolId,
                  operatorReward + membersReward,
                  membersStake
              );
          }
          /// @dev Advance the epoch.
          function advanceEpoch() external {
              currentEpoch += 1;
          }
          /// @dev Create and delegate stake to the current epoch.
          ///      Only used to test purportedly unreachable states.
          ///      Also withdraws pending rewards.
          function delegateStakeNow(
              address delegator,
              bytes32 poolId,
              uint256 stake
          )
              external
          {
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
              IStructs.StoredBalance storage _stake = _delegatedStakeToPoolByOwner[delegator][poolId];
              _stake.currentEpochBalance += uint96(stake);
              _stake.nextEpochBalance += uint96(stake);
              _stake.currentEpoch = uint32(currentEpoch);
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
          }
          /// @dev Create and delegate stake that will occur in the next epoch
          ///      (normal behavior).
          ///      Also withdraws pending rewards.
          function delegateStake(
              address delegator,
              bytes32 poolId,
              uint256 stake
          )
              external
          {
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
              IStructs.StoredBalance storage _stake = _delegatedStakeToPoolByOwner[delegator][poolId];
              if (_stake.currentEpoch < currentEpoch) {
                  _stake.currentEpochBalance = _stake.nextEpochBalance;
              }
              _stake.nextEpochBalance += uint96(stake);
              _stake.currentEpoch = uint32(currentEpoch);
          }
          /// @dev Clear stake that will occur in the next epoch
          ///      (normal behavior).
          ///      Also withdraws pending rewards.
          function undelegateStake(
              address delegator,
              bytes32 poolId,
              uint256 stake
          )
              external
          {
              _withdrawAndSyncDelegatorRewards(
                  poolId,
                  delegator
              );
              IStructs.StoredBalance storage _stake = _delegatedStakeToPoolByOwner[delegator][poolId];
              if (_stake.currentEpoch < currentEpoch) {
                  _stake.currentEpochBalance = _stake.nextEpochBalance;
              }
              _stake.nextEpochBalance -= uint96(stake);
              _stake.currentEpoch = uint32(currentEpoch);
          }
          // solhint-disable no-simple-event-func-name
          /// @dev Overridden to realize `unfinalizedPoolRewardsByEpoch` in
          ///      the current epoch and emit a event,
          function finalizePool(bytes32 poolId)
              external
          {
              UnfinalizedPoolReward memory reward = unfinalizedPoolRewardsByEpoch[currentEpoch][poolId];
              delete unfinalizedPoolRewardsByEpoch[currentEpoch][poolId];
              _setOperatorShare(poolId, reward.operatorReward, reward.membersReward);
              uint256 totalRewards = reward.operatorReward + reward.membersReward;
              uint256 membersStake = reward.membersStake;
              (uint256 operatorReward, uint256 membersReward) =
                  _syncPoolRewards(poolId, totalRewards, membersStake);
              emit FinalizePool(poolId, operatorReward, membersReward, membersStake);
          }
          /// @dev Overridden to use unfinalizedPoolRewardsByEpoch.
          function _getUnfinalizedPoolRewards(bytes32 poolId)
              internal
              view
              returns (
                  uint256 totalReward,
                  uint256 membersStake
              )
          {
              UnfinalizedPoolReward storage reward = unfinalizedPoolRewardsByEpoch[currentEpoch][poolId];
              totalReward = reward.operatorReward + reward.membersReward;
              membersStake = reward.membersStake;
          }
          /// @dev Set the operator share of a pool based on reward ratios.
          function _setOperatorShare(
              bytes32 poolId,
              uint256 operatorReward,
              uint256 membersReward
          )
              private
          {
              uint32 operatorShare = 0;
              uint256 totalReward = operatorReward + membersReward;
              if (totalReward != 0) {
                  operatorShare = uint32(
                      operatorReward * PPM_DENOMINATOR / totalReward
                  );
              }
              _poolById[poolId].operatorShare = operatorShare;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/Staking.sol";
      // solhint-disable no-empty-blocks,no-simple-event-func-name
      /// @dev A version of the staking contract with WETH-related functions
      ///      overridden to do nothing.
      contract TestStakingNoWETH is
          Staking
      {
          event Transfer(
              address indexed _from,
              address indexed _to,
              uint256 _value
          );
          function transfer(address to, uint256 amount)
              external
              returns (bool)
          {
              emit Transfer(address(this), to, amount);
              return true;
          }
          function getWethContract()
              public
              view
              returns (IEtherToken)
          {
              return IEtherToken(address(this));
          }
          function _wrapEth()
              internal
          {}
          function _getAvailableWethBalance()
              internal
              view
              returns (uint256)
          {
              return address(this).balance;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/Staking.sol";
      contract TestExchangeManager is
          Staking
      {
          function setValidExchange(address exchange)
              external
          {
              validExchanges[exchange] = true;
          }
          function onlyExchangeFunction()
              external
              view
              onlyExchange
              returns (bool)
          {
              return true;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "../src/libs/LibCobbDouglas.sol";
      import "./TestStakingNoWETH.sol";
      contract TestFinalizer is
          TestStakingNoWETH
      {
          event DepositStakingPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          );
          struct UnfinalizedPoolReward {
              uint256 totalReward;
              uint256 membersStake;
          }
          struct FinalizedPoolRewards {
              uint256 operatorReward;
              uint256 membersReward;
              uint256 membersStake;
          }
          address payable private _operatorRewardsReceiver;
          address payable private _membersRewardsReceiver;
          mapping (bytes32 => uint32) private _operatorSharesByPool;
          /// @param operatorRewardsReceiver The address to transfer rewards into when
          ///        a pool is finalized.
          constructor(
              address payable operatorRewardsReceiver,
              address payable membersRewardsReceiver
          )
              public
          {
              _addAuthorizedAddress(msg.sender);
              init();
              _operatorRewardsReceiver = operatorRewardsReceiver;
              _membersRewardsReceiver = membersRewardsReceiver;
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          // this contract can receive ETH
          // solhint-disable no-empty-blocks
          function ()
              external
              payable
          {}
          /// @dev Activate a pool in the current epoch.
          function addActivePool(
              bytes32 poolId,
              uint32 operatorShare,
              uint256 feesCollected,
              uint256 membersStake,
              uint256 weightedStake
          )
              external
          {
              require(feesCollected > 0, "FEES_MUST_BE_NONZERO");
              uint256 currentEpoch_ = currentEpoch;
              IStructs.PoolStats memory poolStats = poolStatsByEpoch[poolId][currentEpoch_];
              require(poolStats.feesCollected == 0, "POOL_ALREADY_ADDED");
              _operatorSharesByPool[poolId] = operatorShare;
              poolStatsByEpoch[poolId][currentEpoch_] = IStructs.PoolStats({
                  feesCollected: feesCollected,
                  membersStake: membersStake,
                  weightedStake: weightedStake
              });
              aggregatedStatsByEpoch[currentEpoch_].totalFeesCollected += feesCollected;
              aggregatedStatsByEpoch[currentEpoch_].totalWeightedStake += weightedStake;
              aggregatedStatsByEpoch[currentEpoch_].numPoolsToFinalize += 1;
          }
          /// @dev Drain the balance of this contract.
          function drainBalance()
              external
          {
              address(0).transfer(address(this).balance);
          }
          /// @dev Compute Cobb-Douglas.
          function cobbDouglas(
              uint256 totalRewards,
              uint256 ownerFees,
              uint256 totalFees,
              uint256 ownerStake,
              uint256 totalStake
          )
              external
              view
              returns (uint256 ownerRewards)
          {
              ownerRewards = LibCobbDouglas.cobbDouglas(
                  totalRewards,
                  ownerFees,
                  totalFees,
                  ownerStake,
                  totalStake,
                  cobbDouglasAlphaNumerator,
                  cobbDouglasAlphaDenominator
              );
          }
          /// @dev Expose `_getUnfinalizedPoolReward()`
          function getUnfinalizedPoolRewards(bytes32 poolId)
              external
              view
              returns (UnfinalizedPoolReward memory reward)
          {
              (reward.totalReward, reward.membersStake) = _getUnfinalizedPoolRewards(
                  poolId
              );
          }
          /// @dev Expose pool stats for the input epoch.
          function getPoolStatsFromEpoch(uint256 epoch, bytes32 poolId)
              external
              view
              returns (IStructs.PoolStats memory)
          {
              return poolStatsByEpoch[poolId][epoch];
          }
          function getAggregatedStatsForPreviousEpoch()
              external
              view
              returns (IStructs.AggregatedStats memory)
          {
              return aggregatedStatsByEpoch[currentEpoch - 1];
          }
          /// @dev Overridden to log and transfer to receivers.
          function _syncPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              internal
              returns (uint256 operatorReward, uint256 membersReward)
          {
              uint32 operatorShare = _operatorSharesByPool[poolId];
              (operatorReward, membersReward) = _computePoolRewardsSplit(
                  operatorShare,
                  reward,
                  membersStake
              );
              address(_operatorRewardsReceiver).transfer(operatorReward);
              address(_membersRewardsReceiver).transfer(membersReward);
              emit DepositStakingPoolRewards(poolId, reward, membersStake);
          }
          /// @dev Overriden to just increase the epoch counter.
          function _goToNextEpoch() internal {
              currentEpoch += 1;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./TestStaking.sol";
      contract TestMixinCumulativeRewards is
          TestStaking
      {
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
              TestStaking(
                  wethAddress,
                  zrxVaultAddress
              )
          {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          /// @dev Exposes `_isCumulativeRewardSet`
          function isCumulativeRewardSet(IStructs.Fraction memory cumulativeReward)
              public
              pure
              returns (bool)
          {
              return _isCumulativeRewardSet(cumulativeReward);
          }
          /// @dev Exposes `_addCumulativeReward`
          function addCumulativeReward(
              bytes32 poolId,
              uint256 reward,
              uint256 stake
          )
              public
          {
              _addCumulativeReward(poolId, reward, stake);
          }
          /// @dev Exposes `_updateCumulativeReward`
          function updateCumulativeReward(bytes32 poolId)
              public
          {
              _updateCumulativeReward(poolId);
          }
          /// @dev Exposes _computeMemberRewardOverInterval
          function computeMemberRewardOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              public
              view
              returns (uint256 reward)
          {
              return _computeMemberRewardOverInterval(poolId, memberStakeOverInterval, beginEpoch, endEpoch);
          }
          /// @dev Increments current epoch by 1
          function incrementEpoch()
              public
          {
              currentEpoch += 1;
          }
          /// @dev Stores an arbitrary cumulative reward for a given epoch.
          ///      Also sets the `_cumulativeRewardsByPoolLastStored` to the input epoch.
          function storeCumulativeReward(
              bytes32 poolId,
              IStructs.Fraction memory cumulativeReward,
              uint256 epoch
          )
              public
          {
              _cumulativeRewardsByPool[poolId][epoch] = cumulativeReward;
              _cumulativeRewardsByPoolLastStored[poolId] = epoch;
          }
          /// @dev Returns the most recent cumulative reward for a given pool.
          function getMostRecentCumulativeReward(bytes32 poolId)
              public
              returns (IStructs.Fraction memory)
          {
              uint256 mostRecentEpoch = _cumulativeRewardsByPoolLastStored[poolId];
              return _cumulativeRewardsByPool[poolId][mostRecentEpoch];
          }
          /// @dev Returns the raw cumulative reward for a given pool in an epoch.
          ///      This is considered "raw" because the internal implementation
          ///      (_getCumulativeRewardAtEpochRaw) will query other state variables
          ///      to determine the most accurate cumulative reward for a given epoch.
          function getCumulativeRewardAtEpochRaw(bytes32 poolId, uint256 epoch)
              public
              returns (IStructs.Fraction memory)
          {
              return  _cumulativeRewardsByPool[poolId][epoch];
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "./TestStaking.sol";
      contract TestMixinScheduler is
          TestStaking
      {
          uint256 public testDeployedTimestamp;
          event GoToNextEpochTestInfo(
              uint256 oldEpoch,
              uint256 blockTimestamp
          );
          constructor(
              address wethAddress,
              address zrxVaultAddress
          )
              public
              TestStaking(
                  wethAddress,
                  zrxVaultAddress
              )
          {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
              // Record time of deployment
              // solhint-disable-next-line not-rely-on-time
              testDeployedTimestamp = block.timestamp;
          }
          /// @dev Tests `_goToNextEpoch`.
          ///      Configures internal variables such taht `epochEndTime` will be
          ///      less-than, equal-to, or greater-than the block timestamp.
          /// @param epochEndTimeDelta Set to desired `epochEndTime - block.timestamp`
          function goToNextEpochTest(int256 epochEndTimeDelta)
              public
          {
              // solhint-disable-next-line not-rely-on-time
              uint256 blockTimestamp = block.timestamp;
              // Emit info used by client-side test code
              emit GoToNextEpochTestInfo(
                  currentEpoch,
                  blockTimestamp
              );
              // (i) In `_goToNextEpoch` we compute:
              //     `epochEndTime = currentEpochStartTimeInSeconds + epochDurationInSeconds`
              // (ii) We want adjust internal state such that:
              //      `epochEndTime - block.timestamp = epochEndTimeDelta`, or
              //      `currentEpochStartTimeInSeconds + epochDurationInSeconds - block.timestamp = epochEndTimeDelta`
              //
              // To do this, we:
              //  (i) Set `epochDurationInSeconds` to a constant value of 1, and
              //  (ii) Rearrange the eqn above to get:
              //      `currentEpochStartTimeInSeconds = epochEndTimeDelta + block.timestamp - epochDurationInSeconds`
              epochDurationInSeconds = 1;
              currentEpochStartTimeInSeconds =
                  uint256(epochEndTimeDelta + int256(blockTimestamp) - int256(epochDurationInSeconds));
              // Test internal function
              _goToNextEpoch();
          }
          /// @dev Tests `_initMixinScheduler`
          /// @param _currentEpochStartTimeInSeconds Sets `currentEpochStartTimeInSeconds` to this value before test.
          function initMixinSchedulerTest(uint256 _currentEpochStartTimeInSeconds)
              public
          {
              currentEpochStartTimeInSeconds = _currentEpochStartTimeInSeconds;
              _initMixinScheduler();
          }
      }/*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStake is
          TestStakingNoWETH
      {
          event ZrxVaultDepositFrom(
              address staker,
              uint256 amount
          );
          event ZrxVaultWithdrawFrom(
              address staker,
              uint256 amount
          );
          event MoveStakeStorage(
              bytes32 fromBalanceSlot,
              bytes32 toBalanceSlot,
              uint256 amount
          );
          event IncreaseCurrentAndNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event DecreaseCurrentAndNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event IncreaseNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event DecreaseNextBalance(
              bytes32 balanceSlot,
              uint256 amount
          );
          event WithdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address delegator
          );
          /// @dev Advance the epoch counter.
          function advanceEpoch() external {
              currentEpoch += 1;
          }
          /// @dev `IZrxVault.depositFrom`
          function depositFrom(address staker, uint256 amount) external {
              emit ZrxVaultDepositFrom(staker, amount);
          }
          /// @dev `IZrxVault.withdrawFrom`
          function withdrawFrom(address staker, uint256 amount) external {
              emit ZrxVaultWithdrawFrom(staker, amount);
          }
          function getDelegatedStakeByPoolIdSlot(bytes32 poolId)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_delegatedStakeByPoolId[poolId]);
          }
          function getDelegatedStakeToPoolByOwnerSlot(bytes32 poolId, address staker)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_delegatedStakeToPoolByOwner[staker][poolId]);
          }
          function getGlobalStakeByStatusSlot(IStructs.StakeStatus status)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_globalStakeByStatus[uint8(status)]);
          }
          function getOwnerStakeByStatusSlot(address owner, IStructs.StakeStatus status)
              external
              view
              returns (bytes32 slot)
          {
              return _getPtrSlot(_ownerStakeByStatus[uint8(status)][owner]);
          }
          /// @dev Set `_ownerStakeByStatus`
          function setOwnerStakeByStatus(
              address owner,
              IStructs.StakeStatus status,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _ownerStakeByStatus[uint8(status)][owner] = stake;
          }
          /// @dev Overridden to use this contract as the ZRX vault.
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              return IZrxVault(address(this));
          }
          /// @dev Overridden to only emit an event.
          function _withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              internal
          {
              emit WithdrawAndSyncDelegatorRewards(poolId, member);
          }
          /// @dev Overridden to only emit an event.
          function _moveStake(
              IStructs.StoredBalance storage fromPtr,
              IStructs.StoredBalance storage toPtr,
              uint256 amount
          )
              internal
          {
              emit MoveStakeStorage(
                  _getPtrSlot(fromPtr),
                  _getPtrSlot(toPtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _increaseCurrentAndNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit IncreaseCurrentAndNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _decreaseCurrentAndNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit DecreaseCurrentAndNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _increaseNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit IncreaseNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to only emit an event.
          function _decreaseNextBalance(
              IStructs.StoredBalance storage balancePtr,
              uint256 amount
          )
              internal
          {
              emit DecreaseNextBalance(
                  _getPtrSlot(balancePtr),
                  amount
              );
          }
          /// @dev Overridden to just return the input.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
          }
          /// @dev Throws if poolId == 0x0
          function _assertStakingPoolExists(bytes32 poolId)
              internal
              view
          {
              require(poolId != bytes32(0), "INVALID_POOL");
          }
          // solhint-disable-next-line
          function _getPtrSlot(IStructs.StoredBalance storage ptr)
              private
              pure
              returns (bytes32 offset)
          {
              assembly {
                  offset := ptr_slot
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStakeBalances is
          TestStakingNoWETH
      {
          uint256 private _balanceOfZrxVault;
          mapping (address => uint256) private _zrxBalanceOf;
          function setBalanceOfZrxVault(uint256 balance)
              external
          {
              _balanceOfZrxVault = balance;
          }
          function setZrxBalanceOf(address staker, uint256 balance)
              external
          {
              _zrxBalanceOf[staker] = balance;
          }
          /// @dev `IZrxVault.balanceOfZrxVault`
          function balanceOfZrxVault()
              external
              view
              returns (uint256)
          {
              return _balanceOfZrxVault;
          }
          /// @dev `IZrxVault.balanceOf`
          function balanceOf(address staker)
              external
              view
              returns (uint256)
          {
              return _zrxBalanceOf[staker];
          }
          /// @dev Set `_ownerStakeByStatus`
          function setOwnerStakeByStatus(
              address owner,
              IStructs.StakeStatus status,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _ownerStakeByStatus[uint8(status)][owner] = stake;
          }
          /// @dev Set `_delegatedStakeToPoolByOwner`
          function setDelegatedStakeToPoolByOwner(
              address owner,
              bytes32 poolId,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _delegatedStakeToPoolByOwner[owner][poolId] = stake;
          }
          /// @dev Set `_delegatedStakeByPoolId`
          function setDelegatedStakeByPoolId(
              bytes32 poolId,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _delegatedStakeByPoolId[poolId] = stake;
          }
          /// @dev Set `_globalStakeByStatus`
          function setGlobalStakeByStatus(
              IStructs.StakeStatus status,
              IStructs.StoredBalance memory stake
          )
              public
          {
              _globalStakeByStatus[uint8(status)] = stake;
          }
          /// @dev Overridden to use this contract as the ZRX vault.
          function getZrxVault()
              public
              view
              returns (IZrxVault zrxVault)
          {
              return IZrxVault(address(this));
          }
          /// @dev Overridden to just return the input with the epoch incremented.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
              balance.currentEpoch += 1;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStakingPool is
          TestStakingNoWETH
      {
          function setLastPoolId(bytes32 poolId)
              external
          {
              lastPoolId = poolId;
          }
          function setPoolIdByMaker(bytes32 poolId, address maker)
              external
          {
              poolIdByMaker[maker] = poolId;
          }
          // solhint-disable no-empty-blocks
          function testOnlyStakingPoolOperatorModifier(bytes32 poolId)
              external
              view
              onlyStakingPoolOperator(poolId)
          {}
          function setPoolById(bytes32 poolId, IStructs.Pool memory pool)
              public
          {
              _poolById[poolId] = pool;
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestMixinStakingPoolRewards is
          TestStakingNoWETH
      {
          // solhint-disable no-simple-event-func-name
          event UpdateCumulativeReward(
              bytes32 poolId
          );
          event WithdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address delegator
          );
          struct UnfinalizedPoolReward {
              uint256 reward;
              uint256 membersStake;
          }
          constructor() public {
              _addAuthorizedAddress(msg.sender);
              init();
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          // Rewards returned by `_computeMemberRewardOverInterval()`, indexed
          // by `_getMemberRewardOverIntervalHash()`.
          mapping (bytes32 => uint256) private _memberRewardsOverInterval;
          // Rewards returned by `_getUnfinalizedPoolRewards()`, indexed by pool ID.
          mapping (bytes32 => UnfinalizedPoolReward) private _unfinalizedPoolRewards;
          // Set pool `rewardsByPoolId`.
          function setPoolRewards(
              bytes32 poolId,
              uint256 _rewardsByPoolId
          )
              external
          {
              rewardsByPoolId[poolId] = _rewardsByPoolId;
          }
          // Set `wethReservedForPoolRewards`.
          function setWethReservedForPoolRewards(
              uint256 _wethReservedForPoolRewards
          )
              external
          {
              wethReservedForPoolRewards = _wethReservedForPoolRewards;
          }
          // Set the rewards returned by a call to `_computeMemberRewardOverInterval()`.
          function setMemberRewardsOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch,
              uint256 reward
          )
              external
          {
              bytes32 rewardHash = _getMemberRewardOverIntervalHash(
                  poolId,
                  memberStakeOverInterval,
                  beginEpoch,
                  endEpoch
              );
              _memberRewardsOverInterval[rewardHash] = reward;
          }
          // Set the rewards returned by `_getUnfinalizedPoolRewards()`.
          function setUnfinalizedPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              external
          {
              _unfinalizedPoolRewards[poolId] = UnfinalizedPoolReward(
                  reward,
                  membersStake
              );
          }
          // Set `currentEpoch`.
          function setCurrentEpoch(uint256 epoch) external {
              currentEpoch = epoch;
          }
          // Expose `_syncPoolRewards()` for testing.
          function syncPoolRewards(
              bytes32 poolId,
              uint256 reward,
              uint256 membersStake
          )
              external
              returns (uint256 operatorReward, uint256 membersReward)
          {
              return _syncPoolRewards(poolId, reward, membersStake);
          }
          // Expose `_withdrawAndSyncDelegatorRewards()` for testing.
          function withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              external
          {
              return _withdrawAndSyncDelegatorRewards(
                  poolId,
                  member
              );
          }
          // Expose `_computePoolRewardsSplit()` for testing.
          function computePoolRewardsSplit(
              uint32 operatorShare,
              uint256 totalReward,
              uint256 membersStake
          )
              external
              pure
              returns (uint256 operatorReward, uint256 membersReward)
          {
              return _computePoolRewardsSplit(
                  operatorShare,
                  totalReward,
                  membersStake
              );
          }
          // Access `_delegatedStakeToPoolByOwner`
          function delegatedStakeToPoolByOwner(address member, bytes32 poolId)
              external
              view
              returns (IStructs.StoredBalance memory balance)
          {
              return _delegatedStakeToPoolByOwner[member][poolId];
          }
          // Set `_delegatedStakeToPoolByOwner`
          function setDelegatedStakeToPoolByOwner(
              address member,
              bytes32 poolId,
              IStructs.StoredBalance memory balance
          )
              public
          {
              _delegatedStakeToPoolByOwner[member][poolId] = balance;
          }
          // Set `_poolById`.
          function setPool(
              bytes32 poolId,
              IStructs.Pool memory pool
          )
              public
          {
              _poolById[poolId] = pool;
          }
          // Overridden to emit an event.
          function _withdrawAndSyncDelegatorRewards(
              bytes32 poolId,
              address member
          )
              internal
          {
              emit WithdrawAndSyncDelegatorRewards(poolId, member);
              return MixinStakingPoolRewards._withdrawAndSyncDelegatorRewards(
                  poolId,
                  member
              );
          }
          // Overridden to use `_memberRewardsOverInterval`
          function _computeMemberRewardOverInterval(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              internal
              view
              returns (uint256 reward)
          {
              bytes32 rewardHash = _getMemberRewardOverIntervalHash(
                  poolId,
                  memberStakeOverInterval,
                  beginEpoch,
                  endEpoch
              );
              return _memberRewardsOverInterval[rewardHash];
          }
          // Overridden to use `_unfinalizedPoolRewards`
          function _getUnfinalizedPoolRewards(
              bytes32 poolId
          )
              internal
              view
              returns (uint256 reward, uint256 membersStake)
          {
              (reward, membersStake) = (
                  _unfinalizedPoolRewards[poolId].reward,
                  _unfinalizedPoolRewards[poolId].membersStake
              );
          }
          // Overridden to just increase `currentEpoch`.
          function _loadCurrentBalance(IStructs.StoredBalance storage balancePtr)
              internal
              view
              returns (IStructs.StoredBalance memory balance)
          {
              balance = balancePtr;
              balance.currentEpoch += 1;
          }
          // Overridden to revert if a pool has unfinalized rewards.
          function _assertPoolFinalizedLastEpoch(bytes32 poolId)
              internal
              view
          {
              require(
                  _unfinalizedPoolRewards[poolId].membersStake == 0,
                  "POOL_NOT_FINALIZED"
              );
          }
          // Overridden to just emit an event.
          function _updateCumulativeReward(bytes32 poolId)
              internal
          {
              emit UpdateCumulativeReward(poolId);
          }
          // Compute a hash to index `_memberRewardsOverInterval`
          function _getMemberRewardOverIntervalHash(
              bytes32 poolId,
              uint256 memberStakeOverInterval,
              uint256 beginEpoch,
              uint256 endEpoch
          )
              private
              pure
              returns (bytes32 rewardHash)
          {
              return keccak256(
                  abi.encode(
                      poolId,
                      memberStakeOverInterval,
                      beginEpoch,
                      endEpoch
                  )
              );
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/interfaces/IStructs.sol";
      import "./TestStakingNoWETH.sol";
      contract TestProtocolFees is
          TestStakingNoWETH
      {
          struct TestPool {
              uint96 operatorStake;
              uint96 membersStake;
              mapping(address => bool) isMaker;
          }
          event ERC20ProxyTransferFrom(
              address from,
              address to,
              uint256 amount
          );
          mapping(bytes32 => TestPool) private _testPools;
          mapping(address => bytes32) private _makersToTestPoolIds;
          constructor(address exchangeAddress) public {
              _addAuthorizedAddress(msg.sender);
              init();
              validExchanges[exchangeAddress] = true;
              _removeAuthorizedAddressAtIndex(msg.sender, 0);
          }
          function advanceEpoch()
              external
          {
              currentEpoch += 1;
          }
          /// @dev Create a test pool.
          function createTestPool(
              bytes32 poolId,
              uint96 operatorStake,
              uint96 membersStake,
              address[] calldata makerAddresses
          )
              external
          {
              TestPool storage pool = _testPools[poolId];
              pool.operatorStake = operatorStake;
              pool.membersStake = membersStake;
              for (uint256 i = 0; i < makerAddresses.length; ++i) {
                  pool.isMaker[makerAddresses[i]] = true;
                  _makersToTestPoolIds[makerAddresses[i]] = poolId;
                  poolIdByMaker[makerAddresses[i]] = poolId;
              }
          }
          /// @dev The ERC20Proxy `transferFrom()` function.
          function transferFrom(
              address from,
              address to,
              uint256 amount
          )
              external
              returns (bool)
          {
              emit ERC20ProxyTransferFrom(from, to, amount);
              return true;
          }
          function getAggregatedStatsForCurrentEpoch()
              external
              view
              returns (IStructs.AggregatedStats memory)
          {
              return aggregatedStatsByEpoch[currentEpoch];
          }
          /// @dev Overridden to use test pools.
          function getStakingPoolIdOfMaker(address makerAddress)
              public
              view
              returns (bytes32)
          {
              return _makersToTestPoolIds[makerAddress];
          }
          /// @dev Overridden to use test pools.
          function getTotalStakeDelegatedToPool(bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              TestPool memory pool = _testPools[poolId];
              uint96 stake = pool.operatorStake + pool.membersStake;
              return IStructs.StoredBalance({
                  currentEpoch: currentEpoch.downcastToUint64(),
                  currentEpochBalance: stake,
                  nextEpochBalance: stake
              });
          }
          /// @dev Overridden to use test pools.
          function getStakeDelegatedToPoolByOwner(address, bytes32 poolId)
              public
              view
              returns (IStructs.StoredBalance memory balance)
          {
              TestPool memory pool = _testPools[poolId];
              return IStructs.StoredBalance({
                  currentEpoch: currentEpoch.downcastToUint64(),
                  currentEpochBalance: pool.operatorStake,
                  nextEpochBalance: pool.operatorStake
              });
          }
          function getWethContract()
              public
              view
              returns (IEtherToken wethContract)
          {
              return IEtherToken(address(this));
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "../src/Staking.sol";
      contract TestProxyDestination is
          Staking
      {
          // Init will revert if this flag is set to `true`
          bool public initFailFlag;
          /// @dev Emitted when `init` is called
          event InitCalled(
              bool initCalled
          );
          /// @dev returns the input string
          function echo(string calldata val)
              external
              returns (string memory)
          {
              return val;
          }
          /// @dev Just a function that'll do some math on input
          function doMath(uint256 a, uint256 b)
              external
              returns (uint256 sum, uint256 difference)
          {
              return (
                  a + b,
                  a - b
              );
          }
          /// @dev reverts with "Goodbye, World!"
          function die()
              external
          {
              revert("Goodbye, World!");
          }
          /// @dev Called when attached to the StakingProxy.
          ///      Reverts if `initFailFlag` is set, otherwise
          ///      sets storage params and emits `InitCalled`.
          function init()
              public
          {
              if (initFailFlag) {
                  revert("INIT_FAIL_FLAG_SET");
              }
              // Set params such that they'll pass `StakingProxy.assertValidStorageParams`
              epochDurationInSeconds = 5 days;
              cobbDouglasAlphaNumerator = 1;
              cobbDouglasAlphaDenominator = 1;
              rewardDelegatedStakeWeight = PPM_DENOMINATOR;
              minimumPoolStake = 100;
              // Emit event to notify that `init` was called
              emit InitCalled(true);
          }
      }/*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      pragma experimental ABIEncoderV2;
      import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
      import "@0x/contracts-utils/contracts/src/LibBytes.sol";
      import "../src/Staking.sol";
      contract TestStorageLayoutAndConstants is
          Staking
      {
          using LibBytes for bytes;
          /// @dev Construction will fail if the storage layout or the deployment constants are incompatible
          ///      with the V1 staking proxy.
          constructor() public {
              _assertDeploymentConstants();
              _assertStorageLayout();
          }
          /// @dev This function will fail if the deployment constants change to the point where they
          ///      are considered "invalid".
          function _assertDeploymentConstants()
              internal
              view
          {
              require(
                  address(getWethContract()) != address(0),
                  "WETH_MUST_BE_SET"
              );
              require(
                  address(getZrxVault()) != address(0),
                  "ZRX_VAULT_MUST_BE_SET"
              );
          }
          /// @dev This function will fail if the storage layout of this contract deviates from
          ///      the original staking contract's storage. The use of this function provides assurance
          ///      that regressions from the original storage layout will not occur.
          function _assertStorageLayout()
              internal
              pure
          {
              assembly {
                  let slot := 0x0
                  let offset := 0x0
                  /// Ownable
                  assertSlotAndOffset(
                      owner_slot,
                      owner_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  /// Authorizable
                  assertSlotAndOffset(
                      authorized_slot,
                      authorized_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      authorities_slot,
                      authorities_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  /// MixinStorage
                  assertSlotAndOffset(
                      stakingContract_slot,
                      stakingContract_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _globalStakeByStatus_slot,
                      _globalStakeByStatus_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _ownerStakeByStatus_slot,
                      _ownerStakeByStatus_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _delegatedStakeToPoolByOwner_slot,
                      _delegatedStakeToPoolByOwner_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _delegatedStakeByPoolId_slot,
                      _delegatedStakeByPoolId_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      lastPoolId_slot,
                      lastPoolId_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      poolIdByMaker_slot,
                      poolIdByMaker_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _poolById_slot,
                      _poolById_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      rewardsByPoolId_slot,
                      rewardsByPoolId_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      currentEpoch_slot,
                      currentEpoch_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      currentEpochStartTimeInSeconds_slot,
                      currentEpochStartTimeInSeconds_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _cumulativeRewardsByPool_slot,
                      _cumulativeRewardsByPool_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      _cumulativeRewardsByPoolLastStored_slot,
                      _cumulativeRewardsByPoolLastStored_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      validExchanges_slot,
                      validExchanges_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      epochDurationInSeconds_slot,
                      epochDurationInSeconds_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      rewardDelegatedStakeWeight_slot,
                      rewardDelegatedStakeWeight_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      minimumPoolStake_slot,
                      minimumPoolStake_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      cobbDouglasAlphaNumerator_slot,
                      cobbDouglasAlphaNumerator_offset,
                      slot,
                      offset
                  )
                  offset := add(offset, 0x4)
                  // This number will be tightly packed into the previous values storage slot since
                  // they are both `uint32`. Because of this tight packing, the offset of this value
                  // must be 4, since the previous value is a 4 byte number.
                  assertSlotAndOffset(
                      cobbDouglasAlphaDenominator_slot,
                      cobbDouglasAlphaDenominator_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  offset := 0x0
                  assertSlotAndOffset(
                      poolStatsByEpoch_slot,
                      poolStatsByEpoch_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      aggregatedStatsByEpoch_slot,
                      aggregatedStatsByEpoch_offset,
                      slot,
                      offset
                  )
                  slot := add(slot, 0x1)
                  assertSlotAndOffset(
                      wethReservedForPoolRewards_slot,
                      wethReservedForPoolRewards_offset,
                      slot,
                      offset
                  )
                  // This assembly function will assert that the actual values for `_slot` and `_offset` are
                  // correct and will revert with a rich error if they are different than the expected values.
                  function assertSlotAndOffset(
                      actual_slot,
                      actual_offset,
                      expected_slot,
                      expected_offset
                  ) {
                      // If expected_slot is not equal to actual_slot, revert with a rich error.
                      if iszero(eq(expected_slot, actual_slot)) {
                          mstore(0x0, 0x213eb13400000000000000000000000000000000000000000000000000000000) // Rich error selector
                          mstore(0x4, 0x0)                                                                // Unexpected slot error code
                          mstore(0x24, expected_slot)                                                     // Expected slot
                          mstore(0x44, actual_slot)                                                       // Actual slot
                          revert(0x0, 0x64)
                      }
                      // If expected_offset is not equal to actual_offset, revert with a rich error.
                      if iszero(eq(expected_offset, actual_offset)) {
                          mstore(0x0, 0x213eb13400000000000000000000000000000000000000000000000000000000) // Rich error selector
                          mstore(0x4, 0x1)                                                                // Unexpected offset error code
                          mstore(0x24, expected_offset)                                                   // Expected offset
                          mstore(0x44, actual_offset)                                                     // Actual offset
                          revert(0x0, 0x64)
                      }
                  }
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      import "./LibBytesRichErrors.sol";
      import "./LibRichErrors.sol";
      library LibBytes {
          using LibBytes for bytes;
          /// @dev Gets the memory address for a byte array.
          /// @param input Byte array to lookup.
          /// @return memoryAddress Memory address of byte array. This
          ///         points to the header of the byte array which contains
          ///         the length.
          function rawAddress(bytes memory input)
              internal
              pure
              returns (uint256 memoryAddress)
          {
              assembly {
                  memoryAddress := input
              }
              return memoryAddress;
          }
          /// @dev Gets the memory address for the contents of a byte array.
          /// @param input Byte array to lookup.
          /// @return memoryAddress Memory address of the contents of the byte array.
          function contentAddress(bytes memory input)
              internal
              pure
              returns (uint256 memoryAddress)
          {
              assembly {
                  memoryAddress := add(input, 32)
              }
              return memoryAddress;
          }
          /// @dev Copies `length` bytes from memory location `source` to `dest`.
          /// @param dest memory address to copy bytes to.
          /// @param source memory address to copy bytes from.
          /// @param length number of bytes to copy.
          function memCopy(
              uint256 dest,
              uint256 source,
              uint256 length
          )
              internal
              pure
          {
              if (length < 32) {
                  // Handle a partial word by reading destination and masking
                  // off the bits we are interested in.
                  // This correctly handles overlap, zero lengths and source == dest
                  assembly {
                      let mask := sub(exp(256, sub(32, length)), 1)
                      let s := and(mload(source), not(mask))
                      let d := and(mload(dest), mask)
                      mstore(dest, or(s, d))
                  }
              } else {
                  // Skip the O(length) loop when source == dest.
                  if (source == dest) {
                      return;
                  }
                  // For large copies we copy whole words at a time. The final
                  // word is aligned to the end of the range (instead of after the
                  // previous) to handle partial words. So a copy will look like this:
                  //
                  //  ####
                  //      ####
                  //          ####
                  //            ####
                  //
                  // We handle overlap in the source and destination range by
                  // changing the copying direction. This prevents us from
                  // overwriting parts of source that we still need to copy.
                  //
                  // This correctly handles source == dest
                  //
                  if (source > dest) {
                      assembly {
                          // We subtract 32 from `sEnd` and `dEnd` because it
                          // is easier to compare with in the loop, and these
                          // are also the addresses we need for copying the
                          // last bytes.
                          length := sub(length, 32)
                          let sEnd := add(source, length)
                          let dEnd := add(dest, length)
                          // Remember the last 32 bytes of source
                          // This needs to be done here and not after the loop
                          // because we may have overwritten the last bytes in
                          // source already due to overlap.
                          let last := mload(sEnd)
                          // Copy whole words front to back
                          // Note: the first check is always true,
                          // this could have been a do-while loop.
                          // solhint-disable-next-line no-empty-blocks
                          for {} lt(source, sEnd) {} {
                              mstore(dest, mload(source))
                              source := add(source, 32)
                              dest := add(dest, 32)
                          }
                          // Write the last 32 bytes
                          mstore(dEnd, last)
                      }
                  } else {
                      assembly {
                          // We subtract 32 from `sEnd` and `dEnd` because those
                          // are the starting points when copying a word at the end.
                          length := sub(length, 32)
                          let sEnd := add(source, length)
                          let dEnd := add(dest, length)
                          // Remember the first 32 bytes of source
                          // This needs to be done here and not after the loop
                          // because we may have overwritten the first bytes in
                          // source already due to overlap.
                          let first := mload(source)
                          // Copy whole words back to front
                          // We use a signed comparisson here to allow dEnd to become
                          // negative (happens when source and dest < 32). Valid
                          // addresses in local memory will never be larger than
                          // 2**255, so they can be safely re-interpreted as signed.
                          // Note: the first check is always true,
                          // this could have been a do-while loop.
                          // solhint-disable-next-line no-empty-blocks
                          for {} slt(dest, dEnd) {} {
                              mstore(dEnd, mload(sEnd))
                              sEnd := sub(sEnd, 32)
                              dEnd := sub(dEnd, 32)
                          }
                          // Write the first 32 bytes
                          mstore(dest, first)
                      }
                  }
              }
          }
          /// @dev Returns a slices from a byte array.
          /// @param b The byte array to take a slice from.
          /// @param from The starting index for the slice (inclusive).
          /// @param to The final index for the slice (exclusive).
          /// @return result The slice containing bytes at indices [from, to)
          function slice(
              bytes memory b,
              uint256 from,
              uint256 to
          )
              internal
              pure
              returns (bytes memory result)
          {
              // Ensure that the from and to positions are valid positions for a slice within
              // the byte array that is being used.
              if (from > to) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
                      from,
                      to
                  ));
              }
              if (to > b.length) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
                      to,
                      b.length
                  ));
              }
              // Create a new bytes structure and copy contents
              result = new bytes(to - from);
              memCopy(
                  result.contentAddress(),
                  b.contentAddress() + from,
                  result.length
              );
              return result;
          }
          /// @dev Returns a slice from a byte array without preserving the input.
          /// @param b The byte array to take a slice from. Will be destroyed in the process.
          /// @param from The starting index for the slice (inclusive).
          /// @param to The final index for the slice (exclusive).
          /// @return result The slice containing bytes at indices [from, to)
          /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
          function sliceDestructive(
              bytes memory b,
              uint256 from,
              uint256 to
          )
              internal
              pure
              returns (bytes memory result)
          {
              // Ensure that the from and to positions are valid positions for a slice within
              // the byte array that is being used.
              if (from > to) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
                      from,
                      to
                  ));
              }
              if (to > b.length) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
                      to,
                      b.length
                  ));
              }
              // Create a new bytes structure around [from, to) in-place.
              assembly {
                  result := add(b, from)
                  mstore(result, sub(to, from))
              }
              return result;
          }
          /// @dev Pops the last byte off of a byte array by modifying its length.
          /// @param b Byte array that will be modified.
          /// @return The byte that was popped off.
          function popLastByte(bytes memory b)
              internal
              pure
              returns (bytes1 result)
          {
              if (b.length == 0) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
                      b.length,
                      0
                  ));
              }
              // Store last byte.
              result = b[b.length - 1];
              assembly {
                  // Decrement length of byte array.
                  let newLen := sub(mload(b), 1)
                  mstore(b, newLen)
              }
              return result;
          }
          /// @dev Tests equality of two byte arrays.
          /// @param lhs First byte array to compare.
          /// @param rhs Second byte array to compare.
          /// @return True if arrays are the same. False otherwise.
          function equals(
              bytes memory lhs,
              bytes memory rhs
          )
              internal
              pure
              returns (bool equal)
          {
              // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
              // We early exit on unequal lengths, but keccak would also correctly
              // handle this.
              return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
          }
          /// @dev Reads an address from a position in a byte array.
          /// @param b Byte array containing an address.
          /// @param index Index in byte array of address.
          /// @return address from byte array.
          function readAddress(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (address result)
          {
              if (b.length < index + 20) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
                      b.length,
                      index + 20 // 20 is length of address
                  ));
              }
              // Add offset to index:
              // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
              // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
              index += 20;
              // Read address from array memory
              assembly {
                  // 1. Add index to address of bytes array
                  // 2. Load 32-byte word from memory
                  // 3. Apply 20-byte mask to obtain address
                  result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
              }
              return result;
          }
          /// @dev Writes an address into a specific position in a byte array.
          /// @param b Byte array to insert address into.
          /// @param index Index in byte array of address.
          /// @param input Address to put into byte array.
          function writeAddress(
              bytes memory b,
              uint256 index,
              address input
          )
              internal
              pure
          {
              if (b.length < index + 20) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
                      b.length,
                      index + 20 // 20 is length of address
                  ));
              }
              // Add offset to index:
              // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
              // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
              index += 20;
              // Store address into array memory
              assembly {
                  // The address occupies 20 bytes and mstore stores 32 bytes.
                  // First fetch the 32-byte word where we'll be storing the address, then
                  // apply a mask so we have only the bytes in the word that the address will not occupy.
                  // Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
                  // 1. Add index to address of bytes array
                  // 2. Load 32-byte word from memory
                  // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
                  let neighbors := and(
                      mload(add(b, index)),
                      0xffffffffffffffffffffffff0000000000000000000000000000000000000000
                  )
                  // Make sure input address is clean.
                  // (Solidity does not guarantee this)
                  input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
                  // Store the neighbors and address into memory
                  mstore(add(b, index), xor(input, neighbors))
              }
          }
          /// @dev Reads a bytes32 value from a position in a byte array.
          /// @param b Byte array containing a bytes32 value.
          /// @param index Index in byte array of bytes32 value.
          /// @return bytes32 value from byte array.
          function readBytes32(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (bytes32 result)
          {
              if (b.length < index + 32) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
                      b.length,
                      index + 32
                  ));
              }
              // Arrays are prefixed by a 256 bit length parameter
              index += 32;
              // Read the bytes32 from array memory
              assembly {
                  result := mload(add(b, index))
              }
              return result;
          }
          /// @dev Writes a bytes32 into a specific position in a byte array.
          /// @param b Byte array to insert <input> into.
          /// @param index Index in byte array of <input>.
          /// @param input bytes32 to put into byte array.
          function writeBytes32(
              bytes memory b,
              uint256 index,
              bytes32 input
          )
              internal
              pure
          {
              if (b.length < index + 32) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
                      b.length,
                      index + 32
                  ));
              }
              // Arrays are prefixed by a 256 bit length parameter
              index += 32;
              // Read the bytes32 from array memory
              assembly {
                  mstore(add(b, index), input)
              }
          }
          /// @dev Reads a uint256 value from a position in a byte array.
          /// @param b Byte array containing a uint256 value.
          /// @param index Index in byte array of uint256 value.
          /// @return uint256 value from byte array.
          function readUint256(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (uint256 result)
          {
              result = uint256(readBytes32(b, index));
              return result;
          }
          /// @dev Writes a uint256 into a specific position in a byte array.
          /// @param b Byte array to insert <input> into.
          /// @param index Index in byte array of <input>.
          /// @param input uint256 to put into byte array.
          function writeUint256(
              bytes memory b,
              uint256 index,
              uint256 input
          )
              internal
              pure
          {
              writeBytes32(b, index, bytes32(input));
          }
          /// @dev Reads an unpadded bytes4 value from a position in a byte array.
          /// @param b Byte array containing a bytes4 value.
          /// @param index Index in byte array of bytes4 value.
          /// @return bytes4 value from byte array.
          function readBytes4(
              bytes memory b,
              uint256 index
          )
              internal
              pure
              returns (bytes4 result)
          {
              if (b.length < index + 4) {
                  LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
                      LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
                      b.length,
                      index + 4
                  ));
              }
              // Arrays are prefixed by a 32 byte length field
              index += 32;
              // Read the bytes4 from array memory
              assembly {
                  result := mload(add(b, index))
                  // Solidity does not require us to clean the trailing bytes.
                  // We do it anyway
                  result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
              }
              return result;
          }
          /// @dev Writes a new length to a byte array.
          ///      Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
          ///      Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
          /// @param b Bytes array to write new length to.
          /// @param length New length of byte array.
          function writeLength(bytes memory b, uint256 length)
              internal
              pure
          {
              assembly {
                  mstore(b, length)
              }
          }
      }
      /*
        Copyright 2019 ZeroEx Intl.
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
      */
      pragma solidity ^0.5.9;
      library LibBytesRichErrors {
          enum InvalidByteOperationErrorCodes {
              FromLessThanOrEqualsToRequired,
              ToLessThanOrEqualsLengthRequired,
              LengthGreaterThanZeroRequired,
              LengthGreaterThanOrEqualsFourRequired,
              LengthGreaterThanOrEqualsTwentyRequired,
              LengthGreaterThanOrEqualsThirtyTwoRequired,
              LengthGreaterThanOrEqualsNestedBytesLengthRequired,
              DestinationLengthGreaterThanOrEqualSourceLengthRequired
          }
          // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
          bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
              0x28006595;
          // solhint-disable func-name-mixedcase
          function InvalidByteOperationError(
              InvalidByteOperationErrorCodes errorCode,
              uint256 offset,
              uint256 required
          )
              internal
              pure
              returns (bytes memory)
          {
              return abi.encodeWithSelector(
                  INVALID_BYTE_OPERATION_ERROR_SELECTOR,
                  errorCode,
                  offset,
                  required
              );
          }
      }