Merge pull request #2158 from 0xProject/feat/3.0/cleanup-staking-contracts

Change state var visibilities, delete redundant code
This commit is contained in:
Amir Bandeali 2019-09-17 12:57:51 -07:00 committed by GitHub
commit ee5cb6909c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 339 additions and 548 deletions

View File

@ -25,7 +25,6 @@ import "./libs/LibProxy.sol";
contract ReadOnlyProxy is contract ReadOnlyProxy is
MixinStorage MixinStorage
{ {
using LibProxy for address; using LibProxy for address;
// solhint-disable payable-fallback // solhint-disable payable-fallback

View File

@ -20,32 +20,15 @@ pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2; pragma experimental ABIEncoderV2;
import "./interfaces/IStaking.sol"; import "./interfaces/IStaking.sol";
import "./fees/MixinExchangeManager.sol";
import "./stake/MixinZrxVault.sol";
import "./staking_pools/MixinStakingPoolRewardVault.sol";
import "./sys/MixinScheduler.sol";
import "./sys/MixinParams.sol"; import "./sys/MixinParams.sol";
import "./stake/MixinStakeBalances.sol";
import "./stake/MixinStake.sol"; import "./stake/MixinStake.sol";
import "./staking_pools/MixinStakingPool.sol"; import "./staking_pools/MixinStakingPool.sol";
import "./fees/MixinExchangeFees.sol"; import "./fees/MixinExchangeFees.sol";
import "./staking_pools/MixinStakingPoolRewards.sol";
contract Staking is contract Staking is
IStaking, IStaking,
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinParams, MixinParams,
MixinZrxVault,
MixinExchangeManager,
MixinStakingPoolRewardVault,
MixinScheduler,
MixinStakeStorage,
MixinStakeBalances,
MixinStakingPoolRewards,
MixinStake, MixinStake,
MixinStakingPool, MixinStakingPool,
MixinExchangeFees MixinExchangeFees

View File

@ -19,23 +19,16 @@
pragma solidity ^0.5.9; pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2; pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "./libs/LibProxy.sol"; import "./libs/LibProxy.sol";
import "./immutable/MixinStorage.sol"; import "./immutable/MixinStorage.sol";
import "./interfaces/IStorageInit.sol"; import "./interfaces/IStorageInit.sol";
import "./interfaces/IStaking.sol";
import "./interfaces/IStakingEvents.sol";
import "./interfaces/IStakingProxy.sol"; import "./interfaces/IStakingProxy.sol";
contract StakingProxy is contract StakingProxy is
IStakingEvents,
IStakingProxy, IStakingProxy,
MixinConstants,
Ownable,
MixinStorage MixinStorage
{ {
using LibProxy for address; using LibProxy for address;
/// @dev Constructor. /// @dev Constructor.

View File

@ -24,15 +24,9 @@ import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
import "../libs/LibFixedMath.sol"; import "../libs/LibFixedMath.sol";
import "../immutable/MixinStorage.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinDeploymentConstants.sol"; import "../immutable/MixinDeploymentConstants.sol";
import "../interfaces/IStakingEvents.sol";
import "../interfaces/IStructs.sol"; import "../interfaces/IStructs.sol";
import "../stake/MixinStakeBalances.sol";
import "../sys/MixinScheduler.sol";
import "../staking_pools/MixinStakingPool.sol"; import "../staking_pools/MixinStakingPool.sol";
import "../staking_pools/MixinStakingPoolRewardVault.sol";
import "./MixinExchangeManager.sol"; import "./MixinExchangeManager.sol";
@ -46,21 +40,10 @@ import "./MixinExchangeManager.sol";
/// stake provided by directly by the maker; this is a disincentive for market makers to /// stake provided by directly by the maker; this is a disincentive for market makers to
/// monopolize a single pool that they all delegate to. /// monopolize a single pool that they all delegate to.
contract MixinExchangeFees is contract MixinExchangeFees is
IStakingEvents,
MixinConstants,
MixinDeploymentConstants, MixinDeploymentConstants,
Ownable,
MixinStorage,
MixinZrxVault,
MixinExchangeManager, MixinExchangeManager,
MixinStakingPoolRewardVault,
MixinScheduler,
MixinStakeStorage,
MixinStakeBalances,
MixinStakingPoolRewards,
MixinStakingPool MixinStakingPool
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
/// @dev Pays a protocol fee in ETH or WETH. /// @dev Pays a protocol fee in ETH or WETH.
@ -149,22 +132,12 @@ contract MixinExchangeFees is
/// @dev Returns the total amount of fees collected thus far, in the current epoch. /// @dev Returns the total amount of fees collected thus far, in the current epoch.
/// @return Amount of fees. /// @return Amount of fees.
function getTotalProtocolFeesThisEpoch() function getTotalProtocolFeesThisEpoch()
public external
view view
returns (uint256) returns (uint256)
{ {
return address(this).balance; uint256 wethBalance = IEtherToken(WETH_ADDRESS).balanceOf(address(this));
} return address(this).balance.safeAdd(wethBalance);
/// @dev Returns the amount of fees attributed to the input pool.
/// @param poolId Pool Id to query.
/// @return Amount of fees.
function getProtocolFeesThisEpochByPool(bytes32 poolId)
public
view
returns (uint256)
{
return protocolFeesThisEpochByPool[poolId];
} }
/// @dev Withdraws the entire WETH balance of the contract. /// @dev Withdraws the entire WETH balance of the contract.

View File

@ -21,7 +21,6 @@ pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
import "../interfaces/IStakingEvents.sol"; import "../interfaces/IStakingEvents.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol"; import "../immutable/MixinStorage.sol";
@ -31,14 +30,11 @@ import "../immutable/MixinStorage.sol";
/// then it should be removed. /// then it should be removed.
contract MixinExchangeManager is contract MixinExchangeManager is
IStakingEvents, IStakingEvents,
MixinConstants,
Ownable,
MixinStorage MixinStorage
{ {
/// @dev Asserts that the call is coming from a valid exchange. /// @dev Asserts that the call is coming from a valid exchange.
modifier onlyExchange() { modifier onlyExchange() {
if (!isValidExchangeAddress(msg.sender)) { if (!validExchanges[msg.sender]) {
LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableByExchangeError( LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableByExchangeError(
msg.sender msg.sender
)); ));
@ -75,15 +71,4 @@ contract MixinExchangeManager is
validExchanges[addr] = false; validExchanges[addr] = false;
emit ExchangeRemoved(addr); emit ExchangeRemoved(addr);
} }
/// @dev Returns true iff the address is a valid exchange.
/// @param addr Address of exchange contract.
/// @return True iff input address is a valid exchange.
function isValidExchangeAddress(address addr)
public
view
returns (bool)
{
return validExchanges[addr];
}
} }

View File

@ -17,6 +17,7 @@
*/ */
pragma solidity ^0.5.9; pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetProxy.sol"; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetProxy.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
@ -34,100 +35,99 @@ contract MixinStorage is
MixinConstants, MixinConstants,
Ownable Ownable
{ {
// WETH Asset Proxy // WETH Asset Proxy
IAssetProxy internal wethAssetProxy; IAssetProxy public wethAssetProxy;
// address of staking contract // address of staking contract
address internal stakingContract; address public stakingContract;
// address of read-only proxy // address of read-only proxy
address internal readOnlyProxy; address public readOnlyProxy;
// address for read-only proxy to call // address for read-only proxy to call
address internal readOnlyProxyCallee; address public readOnlyProxyCallee;
// mapping from Owner to Amount of Active Stake // mapping from Owner to Amount of Active Stake
// (access using _loadAndSyncBalance or _loadUnsyncedBalance) // (access using _loadAndSyncBalance or _loadUnsyncedBalance)
mapping (address => IStructs.StoredBalance) internal activeStakeByOwner; mapping (address => IStructs.StoredBalance) internal _activeStakeByOwner;
// mapping from Owner to Amount of Inactive Stake // mapping from Owner to Amount of Inactive Stake
// (access using _loadAndSyncBalance or _loadUnsyncedBalance) // (access using _loadAndSyncBalance or _loadUnsyncedBalance)
mapping (address => IStructs.StoredBalance) internal inactiveStakeByOwner; mapping (address => IStructs.StoredBalance) internal _inactiveStakeByOwner;
// mapping from Owner to Amount Delegated // mapping from Owner to Amount Delegated
// (access using _loadAndSyncBalance or _loadUnsyncedBalance) // (access using _loadAndSyncBalance or _loadUnsyncedBalance)
mapping (address => IStructs.StoredBalance) internal delegatedStakeByOwner; mapping (address => IStructs.StoredBalance) internal _delegatedStakeByOwner;
// mapping from Owner to Pool Id to Amount Delegated // mapping from Owner to Pool Id to Amount Delegated
// (access using _loadAndSyncBalance or _loadUnsyncedBalance) // (access using _loadAndSyncBalance or _loadUnsyncedBalance)
mapping (address => mapping (bytes32 => IStructs.StoredBalance)) internal delegatedStakeToPoolByOwner; mapping (address => mapping (bytes32 => IStructs.StoredBalance)) internal _delegatedStakeToPoolByOwner;
// mapping from Pool Id to Amount Delegated // mapping from Pool Id to Amount Delegated
// (access using _loadAndSyncBalance or _loadUnsyncedBalance) // (access using _loadAndSyncBalance or _loadUnsyncedBalance)
mapping (bytes32 => IStructs.StoredBalance) internal delegatedStakeByPoolId; mapping (bytes32 => IStructs.StoredBalance) internal _delegatedStakeByPoolId;
// mapping from Owner to Amount of Withdrawable Stake // mapping from Owner to Amount of Withdrawable Stake
mapping (address => uint256) internal withdrawableStakeByOwner; mapping (address => uint256) internal _withdrawableStakeByOwner;
// tracking Pool Id // tracking Pool Id
bytes32 internal nextPoolId = INITIAL_POOL_ID; bytes32 public nextPoolId = INITIAL_POOL_ID;
// mapping from Maker Address to a struct representing the pool the maker has joined and // mapping from Maker Address to a struct representing the pool the maker has joined and
// whether the operator of that pool has subsequently added the maker. // whether the operator of that pool has subsequently added the maker.
mapping (address => IStructs.MakerPoolJoinStatus) internal poolJoinedByMakerAddress; mapping (address => IStructs.MakerPoolJoinStatus) public poolJoinedByMakerAddress;
// mapping from Pool Id to number of makers assigned to that pool // mapping from Pool Id to number of makers assigned to that pool
mapping (bytes32 => uint256) internal numMakersByPoolId; mapping (bytes32 => uint256) public numMakersByPoolId;
// current epoch // current epoch
uint256 internal currentEpoch = INITIAL_EPOCH; uint256 public currentEpoch = INITIAL_EPOCH;
// current epoch start time // current epoch start time
uint256 internal currentEpochStartTimeInSeconds; uint256 public currentEpochStartTimeInSeconds;
// fees collected this epoch // fees collected this epoch
mapping (bytes32 => uint256) internal protocolFeesThisEpochByPool; mapping (bytes32 => uint256) public protocolFeesThisEpochByPool;
// pools that were active in the current epoch // pools that were active in the current epoch
bytes32[] internal activePoolsThisEpoch; bytes32[] public activePoolsThisEpoch;
// mapping from Pool Id to Epoch to Reward Ratio // mapping from Pool Id to Epoch to Reward Ratio
mapping (bytes32 => mapping (uint256 => IStructs.Fraction)) internal cumulativeRewardsByPool; mapping (bytes32 => mapping (uint256 => IStructs.Fraction)) internal _cumulativeRewardsByPool;
// mapping from Pool Id to Epoch to Cumulative Rewards Reference Counter // mapping from Pool Id to Epoch to Cumulative Rewards Reference Counter
mapping (bytes32 => mapping (uint256 => uint256)) internal cumulativeRewardsByPoolReferenceCounter; mapping (bytes32 => mapping (uint256 => uint256)) internal _cumulativeRewardsByPoolReferenceCounter;
// mapping from Pool Id to Epoch // mapping from Pool Id to Epoch
mapping (bytes32 => uint256) internal cumulativeRewardsByPoolLastStored; mapping (bytes32 => uint256) internal _cumulativeRewardsByPoolLastStored;
// registered 0x Exchange contracts // registered 0x Exchange contracts
mapping (address => bool) internal validExchanges; mapping (address => bool) public validExchanges;
// ZRX vault (stores staked ZRX) // ZRX vault (stores staked ZRX)
IZrxVault internal zrxVault; IZrxVault public zrxVault;
// ETH Vault (stores eth balances of stakers and pool operators) // ETH Vault (stores eth balances of stakers and pool operators)
IEthVault internal ethVault; IEthVault public ethVault;
// Rebate Vault (stores rewards for pools before they are moved to the eth vault on a per-user basis) // Rebate Vault (stores rewards for pools before they are moved to the eth vault on a per-user basis)
IStakingPoolRewardVault internal rewardVault; IStakingPoolRewardVault public rewardVault;
// Minimum seconds between epochs. // Minimum seconds between epochs.
uint256 internal epochDurationInSeconds; uint256 public epochDurationInSeconds;
// How much delegated stake is weighted vs operator stake, in ppm. // How much delegated stake is weighted vs operator stake, in ppm.
uint32 internal rewardDelegatedStakeWeight; uint32 public rewardDelegatedStakeWeight;
// Minimum amount of stake required in a pool to collect rewards. // Minimum amount of stake required in a pool to collect rewards.
uint256 internal minimumPoolStake; uint256 public minimumPoolStake;
// Maximum number of maker addresses allowed to be registered to a pool. // Maximum number of maker addresses allowed to be registered to a pool.
uint256 internal maximumMakersInPool; uint256 public maximumMakersInPool;
// Numerator for cobb douglas alpha factor. // Numerator for cobb douglas alpha factor.
uint32 internal cobbDouglasAlphaNumerator; uint32 public cobbDouglasAlphaNumerator;
// Denominator for cobb douglas alpha factor. // Denominator for cobb douglas alpha factor.
uint32 internal cobbDouglasAlphaDenomintor; uint32 public cobbDouglasAlphaDenomintor;
} }

View File

@ -17,6 +17,7 @@
*/ */
pragma solidity ^0.5.9; pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
/// @dev This vault manages staking pool rewards. /// @dev This vault manages staking pool rewards.
@ -179,28 +180,4 @@ interface IStakingPoolRewardVault {
external external
view view
returns (uint256); returns (uint256);
/// @dev Returns the balance of a pool operator.
/// @param poolId Unique Id of pool.
/// @return Balance in ETH.
function balanceOfOperator(bytes32 poolId)
external
view
returns (uint256);
/// @dev Returns the balance co-owned by members of a pool.
/// @param poolId Unique Id of pool.
/// @return Balance in ETH.
function balanceOfMembers(bytes32 poolId)
external
view
returns (uint256);
/// @dev Returns the operator share of a pool's balance.
/// @param poolId Unique Id of pool.
/// @return Operator share (integer out of 100)
function getOperatorShare(bytes32 poolId)
external
view
returns (uint256);
} }

View File

@ -0,0 +1,135 @@
/*
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/IAssetProxy.sol";
import "../interfaces/IZrxVault.sol";
import "../interfaces/IEthVault.sol";
import "../interfaces/IStakingPoolRewardVault.sol";
import "../interfaces/IStructs.sol";
interface IStorage {
function wethAssetProxy()
external
view
returns (IAssetProxy);
function stakingContract()
external
view
returns (address);
function readOnlyProxy()
external
view
returns (address);
function readOnlyProxyCallee()
external
view
returns (address);
function nextPoolId()
external
view
returns (bytes32);
function poolJoinedByMakerAddress(address makerAddress)
external
view
returns (IStructs.MakerPoolJoinStatus memory);
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 activePoolsThisEpoch()
external
view
returns (bytes32[] memory);
function validExchanges(address exchangeAddress)
external
view
returns (bool);
function zrxVault()
external
view
returns (IZrxVault);
function ethVault()
external
view
returns (IEthVault);
function rewardVault()
external
view
returns (IStakingPoolRewardVault);
function epochDurationInSeconds()
external
view
returns (uint256);
function rewardDelegatedStakeWeight()
external
view
returns(uint32);
function minimumPoolStake()
external
view
returns (uint256);
function maximumMakersInPool()
external
view
returns(uint256);
function cobbDouglasAlphaNumerator()
external
view
returns (uint32);
function cobbDouglasAlphaDenomintor()
external
view
returns (uint32);
}

View File

@ -20,33 +20,14 @@ pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2; pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol";
import "../interfaces/IStakingEvents.sol";
import "./MixinZrxVault.sol";
import "../staking_pools/MixinStakingPoolRewardVault.sol";
import "../staking_pools/MixinStakingPoolRewards.sol"; import "../staking_pools/MixinStakingPoolRewards.sol";
import "../sys/MixinScheduler.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
import "./MixinZrxVault.sol";
import "./MixinStakeBalances.sol";
import "./MixinStakeStorage.sol";
/// @dev This mixin contains logic for managing ZRX tokens and Stake. /// @dev This mixin contains logic for managing ZRX tokens and Stake.
contract MixinStake is contract MixinStake is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinZrxVault,
MixinStakingPoolRewardVault,
MixinScheduler,
MixinStakeStorage,
MixinStakeBalances,
MixinStakingPoolRewards MixinStakingPoolRewards
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
/// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault. Unstake to retrieve the ZRX. /// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault. Unstake to retrieve the ZRX.
@ -61,7 +42,7 @@ contract MixinStake is
_depositFromOwnerIntoZrxVault(owner, amount); _depositFromOwnerIntoZrxVault(owner, amount);
// mint stake // mint stake
_incrementCurrentAndNextBalance(activeStakeByOwner[owner], amount); _incrementCurrentAndNextBalance(_activeStakeByOwner[owner], amount);
// notify // notify
emit Stake( emit Stake(
@ -90,10 +71,10 @@ contract MixinStake is
} }
// burn inactive stake // burn inactive stake
_decrementCurrentAndNextBalance(inactiveStakeByOwner[owner], amount); _decrementCurrentAndNextBalance(_inactiveStakeByOwner[owner], amount);
// update withdrawable field // update withdrawable field
withdrawableStakeByOwner[owner] = currentWithdrawableStake.safeSub(amount); _withdrawableStakeByOwner[owner] = currentWithdrawableStake.safeSub(amount);
// withdraw equivalent amount of ZRX from vault // withdraw equivalent amount of ZRX from vault
_withdrawToOwnerFromZrxVault(owner, amount); _withdrawToOwnerFromZrxVault(owner, amount);
@ -156,7 +137,7 @@ contract MixinStake is
// update withdrawable field, if necessary // update withdrawable field, if necessary
if (from.status == IStructs.StakeStatus.INACTIVE) { if (from.status == IStructs.StakeStatus.INACTIVE) {
withdrawableStakeByOwner[owner] = _computeWithdrawableStake(owner, withdrawableStake); _withdrawableStakeByOwner[owner] = _computeWithdrawableStake(owner, withdrawableStake);
} }
// notify // notify
@ -192,16 +173,16 @@ contract MixinStake is
} }
// cache amount delegated to pool by owner // cache amount delegated to pool by owner
IStructs.StoredBalance memory initDelegatedStakeToPoolByOwner = _loadUnsyncedBalance(delegatedStakeToPoolByOwner[owner][poolId]); IStructs.StoredBalance memory initDelegatedStakeToPoolByOwner = _loadUnsyncedBalance(_delegatedStakeToPoolByOwner[owner][poolId]);
// increment how much stake the owner has delegated to the input pool // increment how much stake the owner has delegated to the input pool
_incrementNextBalance(delegatedStakeToPoolByOwner[owner][poolId], amount); _incrementNextBalance(_delegatedStakeToPoolByOwner[owner][poolId], amount);
// increment how much stake has been delegated to pool // increment how much stake has been delegated to pool
_incrementNextBalance(delegatedStakeByPoolId[poolId], amount); _incrementNextBalance(_delegatedStakeByPoolId[poolId], amount);
// synchronizes reward state in the pool that the staker is delegating to // synchronizes reward state in the pool that the staker is delegating to
IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(delegatedStakeToPoolByOwner[owner][poolId]); IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(_delegatedStakeToPoolByOwner[owner][poolId]);
_syncRewardsForDelegator(poolId, owner, initDelegatedStakeToPoolByOwner, finalDelegatedStakeToPoolByOwner); _syncRewardsForDelegator(poolId, owner, initDelegatedStakeToPoolByOwner, finalDelegatedStakeToPoolByOwner);
} }
@ -227,16 +208,16 @@ contract MixinStake is
} }
// cache amount delegated to pool by owner // cache amount delegated to pool by owner
IStructs.StoredBalance memory initDelegatedStakeToPoolByOwner = _loadUnsyncedBalance(delegatedStakeToPoolByOwner[owner][poolId]); IStructs.StoredBalance memory initDelegatedStakeToPoolByOwner = _loadUnsyncedBalance(_delegatedStakeToPoolByOwner[owner][poolId]);
// decrement how much stake the owner has delegated to the input pool // decrement how much stake the owner has delegated to the input pool
_decrementNextBalance(delegatedStakeToPoolByOwner[owner][poolId], amount); _decrementNextBalance(_delegatedStakeToPoolByOwner[owner][poolId], amount);
// decrement how much stake has been delegated to pool // decrement how much stake has been delegated to pool
_decrementNextBalance(delegatedStakeByPoolId[poolId], amount); _decrementNextBalance(_delegatedStakeByPoolId[poolId], amount);
// synchronizes reward state in the pool that the staker is undelegating from // synchronizes reward state in the pool that the staker is undelegating from
IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(delegatedStakeToPoolByOwner[owner][poolId]); IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(_delegatedStakeToPoolByOwner[owner][poolId]);
_syncRewardsForDelegator(poolId, owner, initDelegatedStakeToPoolByOwner, finalDelegatedStakeToPoolByOwner); _syncRewardsForDelegator(poolId, owner, initDelegatedStakeToPoolByOwner, finalDelegatedStakeToPoolByOwner);
} }
@ -251,11 +232,11 @@ contract MixinStake is
{ {
// lookup status // lookup status
if (status == IStructs.StakeStatus.ACTIVE) { if (status == IStructs.StakeStatus.ACTIVE) {
return activeStakeByOwner[owner]; return _activeStakeByOwner[owner];
} else if (status == IStructs.StakeStatus.INACTIVE) { } else if (status == IStructs.StakeStatus.INACTIVE) {
return inactiveStakeByOwner[owner]; return _inactiveStakeByOwner[owner];
} else if (status == IStructs.StakeStatus.DELEGATED) { } else if (status == IStructs.StakeStatus.DELEGATED) {
return delegatedStakeByOwner[owner]; return _delegatedStakeByOwner[owner];
} }
// invalid status // invalid status

View File

@ -21,9 +21,6 @@ pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../interfaces/IStructs.sol"; import "../interfaces/IStructs.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol";
import "../sys/MixinScheduler.sol";
import "./MixinZrxVault.sol"; import "./MixinZrxVault.sol";
import "./MixinStakeStorage.sol"; import "./MixinStakeStorage.sol";
@ -31,22 +28,16 @@ import "./MixinStakeStorage.sol";
/// @dev This mixin contains logic for querying stake balances. /// @dev This mixin contains logic for querying stake balances.
/// **** Read MixinStake before continuing **** /// **** Read MixinStake before continuing ****
contract MixinStakeBalances is contract MixinStakeBalances is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinZrxVault, MixinZrxVault,
MixinScheduler,
MixinStakeStorage MixinStakeStorage
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
/// @dev Returns the total stake for a given owner. /// @dev Returns the total stake for a given owner.
/// @param owner of stake. /// @param owner of stake.
/// @return Total active stake for owner. /// @return Total active stake for owner.
function getTotalStake(address owner) function getTotalStake(address owner)
public external
view view
returns (uint256) returns (uint256)
{ {
@ -57,11 +48,11 @@ contract MixinStakeBalances is
/// @param owner of stake. /// @param owner of stake.
/// @return Active stake for owner. /// @return Active stake for owner.
function getActiveStake(address owner) function getActiveStake(address owner)
public external
view view
returns (IStructs.StakeBalance memory balance) returns (IStructs.StakeBalance memory balance)
{ {
IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(activeStakeByOwner[owner]); IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_activeStakeByOwner[owner]);
return IStructs.StakeBalance({ return IStructs.StakeBalance({
currentEpochBalance: storedBalance.currentEpochBalance, currentEpochBalance: storedBalance.currentEpochBalance,
nextEpochBalance: storedBalance.nextEpochBalance nextEpochBalance: storedBalance.nextEpochBalance
@ -72,11 +63,26 @@ contract MixinStakeBalances is
/// @param owner of stake. /// @param owner of stake.
/// @return Inactive stake for owner. /// @return Inactive stake for owner.
function getInactiveStake(address owner) function getInactiveStake(address owner)
public external
view view
returns (IStructs.StakeBalance memory balance) returns (IStructs.StakeBalance memory balance)
{ {
IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(inactiveStakeByOwner[owner]); IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_inactiveStakeByOwner[owner]);
return IStructs.StakeBalance({
currentEpochBalance: storedBalance.currentEpochBalance,
nextEpochBalance: storedBalance.nextEpochBalance
});
}
/// @dev Returns the stake delegated by a given owner.
/// @param owner of stake.
/// @return Delegated stake for owner.
function getStakeDelegatedByOwner(address owner)
external
view
returns (IStructs.StakeBalance memory balance)
{
IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_delegatedStakeByOwner[owner]);
return IStructs.StakeBalance({ return IStructs.StakeBalance({
currentEpochBalance: storedBalance.currentEpochBalance, currentEpochBalance: storedBalance.currentEpochBalance,
nextEpochBalance: storedBalance.nextEpochBalance nextEpochBalance: storedBalance.nextEpochBalance
@ -91,22 +97,7 @@ contract MixinStakeBalances is
view view
returns (uint256) returns (uint256)
{ {
return _computeWithdrawableStake(owner, withdrawableStakeByOwner[owner]); return _computeWithdrawableStake(owner, _withdrawableStakeByOwner[owner]);
}
/// @dev Returns the stake delegated by a given owner.
/// @param owner of stake.
/// @return Delegated stake for owner.
function getStakeDelegatedByOwner(address owner)
public
view
returns (IStructs.StakeBalance memory balance)
{
IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(delegatedStakeByOwner[owner]);
return IStructs.StakeBalance({
currentEpochBalance: storedBalance.currentEpochBalance,
nextEpochBalance: storedBalance.nextEpochBalance
});
} }
/// @dev Returns the stake delegated to a specific staking pool, by a given owner. /// @dev Returns the stake delegated to a specific staking pool, by a given owner.
@ -118,7 +109,7 @@ contract MixinStakeBalances is
view view
returns (IStructs.StakeBalance memory balance) returns (IStructs.StakeBalance memory balance)
{ {
IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(delegatedStakeToPoolByOwner[owner][poolId]); IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_delegatedStakeToPoolByOwner[owner][poolId]);
return IStructs.StakeBalance({ return IStructs.StakeBalance({
currentEpochBalance: storedBalance.currentEpochBalance, currentEpochBalance: storedBalance.currentEpochBalance,
nextEpochBalance: storedBalance.nextEpochBalance nextEpochBalance: storedBalance.nextEpochBalance
@ -133,7 +124,7 @@ contract MixinStakeBalances is
view view
returns (IStructs.StakeBalance memory balance) returns (IStructs.StakeBalance memory balance)
{ {
IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(delegatedStakeByPoolId[poolId]); IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_delegatedStakeByPoolId[poolId]);
return IStructs.StakeBalance({ return IStructs.StakeBalance({
currentEpochBalance: storedBalance.currentEpochBalance, currentEpochBalance: storedBalance.currentEpochBalance,
nextEpochBalance: storedBalance.nextEpochBalance nextEpochBalance: storedBalance.nextEpochBalance
@ -151,7 +142,7 @@ contract MixinStakeBalances is
{ {
// stake cannot be withdrawn if it has been reallocated for the `next` epoch; // stake cannot be withdrawn if it has been reallocated for the `next` epoch;
// so the upper bound of withdrawable stake is always limited by the value of `next`. // so the upper bound of withdrawable stake is always limited by the value of `next`.
IStructs.StoredBalance memory storedBalance = _loadUnsyncedBalance(inactiveStakeByOwner[owner]); IStructs.StoredBalance memory storedBalance = _loadUnsyncedBalance(_inactiveStakeByOwner[owner]);
if (storedBalance.currentEpoch == currentEpoch) { if (storedBalance.currentEpoch == currentEpoch) {
return LibSafeMath.min256(storedBalance.nextEpochBalance, lastStoredWithdrawableStake); return LibSafeMath.min256(storedBalance.nextEpochBalance, lastStoredWithdrawableStake);
} else if (uint256(storedBalance.currentEpoch).safeAdd(1) == currentEpoch) { } else if (uint256(storedBalance.currentEpoch).safeAdd(1) == currentEpoch) {

View File

@ -21,21 +21,13 @@ pragma solidity ^0.5.9;
import "../libs/LibSafeDowncast.sol"; import "../libs/LibSafeDowncast.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../interfaces/IStructs.sol"; import "../interfaces/IStructs.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol";
import "../sys/MixinScheduler.sol"; import "../sys/MixinScheduler.sol";
import "./MixinZrxVault.sol";
/// @dev This mixin contains logic for managing stake storage. /// @dev This mixin contains logic for managing stake storage.
contract MixinStakeStorage is contract MixinStakeStorage is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinScheduler MixinScheduler
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
using LibSafeDowncast for uint256; using LibSafeDowncast for uint256;
@ -93,9 +85,9 @@ contract MixinStakeStorage is
// load from storage // load from storage
balance = balancePtr; balance = balancePtr;
// sync // sync
uint256 currentEpoch = getCurrentEpoch(); uint256 currentEpoch_ = currentEpoch;
if (currentEpoch > balance.currentEpoch) { if (currentEpoch_ > balance.currentEpoch) {
balance.currentEpoch = currentEpoch.downcastToUint32(); balance.currentEpoch = currentEpoch_.downcastToUint32();
balance.currentEpochBalance = balance.nextEpochBalance; balance.currentEpochBalance = balance.nextEpochBalance;
} }
return balance; return balance;

View File

@ -25,11 +25,8 @@ import "../immutable/MixinStorage.sol";
/// @dev This mixin contains logic for managing and interfacing with the Zrx Vault. /// @dev This mixin contains logic for managing and interfacing with the Zrx Vault.
/// (see vaults/ZrxVault.sol). /// (see vaults/ZrxVault.sol).
contract MixinZrxVault is contract MixinZrxVault is
MixinConstants,
Ownable,
MixinStorage MixinStorage
{ {
/// @dev Set the Zrx Vault. /// @dev Set the Zrx Vault.
/// @param zrxVaultAddress Address of the Zrx Vault. /// @param zrxVaultAddress Address of the Zrx Vault.
function setZrxVault(address zrxVaultAddress) function setZrxVault(address zrxVaultAddress)
@ -39,16 +36,6 @@ contract MixinZrxVault is
zrxVault = IZrxVault(zrxVaultAddress); zrxVault = IZrxVault(zrxVaultAddress);
} }
/// @dev Return the current Zrx Vault
/// @return Zrx Vault
function getZrxVault()
public
view
returns (address)
{
return address(zrxVault);
}
/// @dev Deposits Zrx Tokens from the `owner` into the vault. /// @dev Deposits Zrx Tokens from the `owner` into the vault.
/// @param owner of Zrx Tokens /// @param owner of Zrx Tokens
/// @param amount of tokens to deposit. /// @param amount of tokens to deposit.

View File

@ -21,21 +21,12 @@ pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibFractions.sol"; import "@0x/contracts-utils/contracts/src/LibFractions.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../immutable/MixinStorage.sol";
import "../immutable/MixinConstants.sol";
import "../stake/MixinStakeBalances.sol"; import "../stake/MixinStakeBalances.sol";
import "./MixinStakingPoolRewardVault.sol"; import "./MixinStakingPoolRewardVault.sol";
contract MixinCumulativeRewards is contract MixinCumulativeRewards is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinZrxVault,
MixinStakingPoolRewardVault, MixinStakingPoolRewardVault,
MixinScheduler,
MixinStakeStorage,
MixinStakeBalances MixinStakeBalances
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
@ -45,7 +36,6 @@ contract MixinCumulativeRewards is
function _initializeCumulativeRewards(bytes32 poolId) function _initializeCumulativeRewards(bytes32 poolId)
internal internal
{ {
uint256 currentEpoch = getCurrentEpoch();
// sets the default cumulative reward // sets the default cumulative reward
_forceSetCumulativeReward( _forceSetCumulativeReward(
poolId, poolId,
@ -78,9 +68,9 @@ contract MixinCumulativeRewards is
returns (bool) returns (bool)
{ {
return ( return (
_isCumulativeRewardSet(cumulativeRewardsByPool[poolId][epoch]) && // is there a value to unset _isCumulativeRewardSet(_cumulativeRewardsByPool[poolId][epoch]) && // is there a value to unset
cumulativeRewardsByPoolReferenceCounter[poolId][epoch] == 0 && // no references to this CR _cumulativeRewardsByPoolReferenceCounter[poolId][epoch] == 0 && // no references to this CR
cumulativeRewardsByPoolLastStored[poolId] > epoch // this is *not* the most recent CR _cumulativeRewardsByPoolLastStored[poolId] > epoch // this is *not* the most recent CR
); );
} }
@ -95,7 +85,7 @@ contract MixinCumulativeRewards is
) )
internal internal
{ {
if (_isCumulativeRewardSet(cumulativeRewardsByPool[poolId][epoch])) { if (_isCumulativeRewardSet(_cumulativeRewardsByPool[poolId][epoch])) {
// do nothing; we don't want to override the current value // do nothing; we don't want to override the current value
return; return;
} }
@ -114,7 +104,7 @@ contract MixinCumulativeRewards is
) )
internal internal
{ {
cumulativeRewardsByPool[poolId][epoch] = value; _cumulativeRewardsByPool[poolId][epoch] = value;
_trySetMostRecentCumulativeRewardEpoch(poolId, epoch); _trySetMostRecentCumulativeRewardEpoch(poolId, epoch);
} }
@ -136,7 +126,7 @@ contract MixinCumulativeRewards is
function _forceUnsetCumulativeReward(bytes32 poolId, uint256 epoch) function _forceUnsetCumulativeReward(bytes32 poolId, uint256 epoch)
internal internal
{ {
cumulativeRewardsByPool[poolId][epoch] = IStructs.Fraction({numerator: 0, denominator: 0}); _cumulativeRewardsByPool[poolId][epoch] = IStructs.Fraction({numerator: 0, denominator: 0});
} }
/// @dev Returns info on most recent cumulative reward. /// @dev Returns info on most recent cumulative reward.
@ -145,11 +135,11 @@ contract MixinCumulativeRewards is
returns (IStructs.CumulativeRewardInfo memory) returns (IStructs.CumulativeRewardInfo memory)
{ {
// fetch the last epoch at which we stored a cumulative reward for this pool // fetch the last epoch at which we stored a cumulative reward for this pool
uint256 cumulativeRewardsLastStored = cumulativeRewardsByPoolLastStored[poolId]; uint256 cumulativeRewardsLastStored = _cumulativeRewardsByPoolLastStored[poolId];
// query and return cumulative reward info for this pool // query and return cumulative reward info for this pool
return IStructs.CumulativeRewardInfo({ return IStructs.CumulativeRewardInfo({
cumulativeReward: cumulativeRewardsByPool[poolId][cumulativeRewardsLastStored], cumulativeReward: _cumulativeRewardsByPool[poolId][cumulativeRewardsLastStored],
cumulativeRewardEpoch: cumulativeRewardsLastStored cumulativeRewardEpoch: cumulativeRewardsLastStored
}); });
} }
@ -163,7 +153,7 @@ contract MixinCumulativeRewards is
internal internal
{ {
// check if we should do any work // check if we should do any work
uint256 currentMostRecentEpoch = cumulativeRewardsByPoolLastStored[poolId]; uint256 currentMostRecentEpoch = _cumulativeRewardsByPoolLastStored[poolId];
if (epoch == currentMostRecentEpoch) { if (epoch == currentMostRecentEpoch) {
return; return;
} }
@ -189,7 +179,7 @@ contract MixinCumulativeRewards is
{ {
// sanity check that we're not trying to go back in time // sanity check that we're not trying to go back in time
assert(newMostRecentEpoch >= currentMostRecentEpoch); assert(newMostRecentEpoch >= currentMostRecentEpoch);
cumulativeRewardsByPoolLastStored[poolId] = newMostRecentEpoch; _cumulativeRewardsByPoolLastStored[poolId] = newMostRecentEpoch;
// unset the previous most recent reward, if it is no longer needed // unset the previous most recent reward, if it is no longer needed
_tryUnsetCumulativeReward(poolId, currentMostRecentEpoch); _tryUnsetCumulativeReward(poolId, currentMostRecentEpoch);
@ -234,7 +224,7 @@ contract MixinCumulativeRewards is
internal internal
{ {
// add dependency by increasing the reference counter // add dependency by increasing the reference counter
cumulativeRewardsByPoolReferenceCounter[poolId][epoch] = cumulativeRewardsByPoolReferenceCounter[poolId][epoch].safeAdd(1); _cumulativeRewardsByPoolReferenceCounter[poolId][epoch] = _cumulativeRewardsByPoolReferenceCounter[poolId][epoch].safeAdd(1);
// set CR to most recent reward (if it is not already set) // set CR to most recent reward (if it is not already set)
_trySetCumulativeReward( _trySetCumulativeReward(
@ -254,8 +244,8 @@ contract MixinCumulativeRewards is
internal internal
{ {
// remove dependency by decreasing reference counter // remove dependency by decreasing reference counter
uint256 newReferenceCounter = cumulativeRewardsByPoolReferenceCounter[poolId][epoch].safeSub(1); uint256 newReferenceCounter = _cumulativeRewardsByPoolReferenceCounter[poolId][epoch].safeSub(1);
cumulativeRewardsByPoolReferenceCounter[poolId][epoch] = newReferenceCounter; _cumulativeRewardsByPoolReferenceCounter[poolId][epoch] = newReferenceCounter;
// clear cumulative reward from state, if it is no longer needed // clear cumulative reward from state, if it is no longer needed
_tryUnsetCumulativeReward(poolId, epoch); _tryUnsetCumulativeReward(poolId, epoch);
@ -295,7 +285,7 @@ contract MixinCumulativeRewards is
} }
// sanity check begin reward // sanity check begin reward
IStructs.Fraction memory beginReward = cumulativeRewardsByPool[poolId][beginEpoch]; IStructs.Fraction memory beginReward = _cumulativeRewardsByPool[poolId][beginEpoch];
if (!_isCumulativeRewardSet(beginReward)) { if (!_isCumulativeRewardSet(beginReward)) {
LibRichErrors.rrevert( LibRichErrors.rrevert(
LibStakingRichErrors.CumulativeRewardIntervalError( LibStakingRichErrors.CumulativeRewardIntervalError(
@ -308,7 +298,7 @@ contract MixinCumulativeRewards is
} }
// sanity check end reward // sanity check end reward
IStructs.Fraction memory endReward = cumulativeRewardsByPool[poolId][endEpoch]; IStructs.Fraction memory endReward = _cumulativeRewardsByPool[poolId][endEpoch];
if (!_isCumulativeRewardSet(endReward)) { if (!_isCumulativeRewardSet(endReward)) {
LibRichErrors.rrevert( LibRichErrors.rrevert(
LibStakingRichErrors.CumulativeRewardIntervalError( LibStakingRichErrors.CumulativeRewardIntervalError(

View File

@ -1,53 +0,0 @@
/*
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/IStakingEvents.sol";
import "../interfaces/IEthVault.sol";
import "../immutable/MixinStorage.sol";
/// @dev This mixin contains logic for managing and interfacing with the Eth Vault.
/// (see vaults/EthVault.sol).
contract MixinEthVault is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage
{
/// @dev Set the Eth Vault.
/// @param ethVaultAddress Address of the Eth Vault.
function setEthVault(address ethVaultAddress)
external
onlyOwner
{
ethVault = IEthVault(ethVaultAddress);
}
/// @dev Return the current Eth Vault
/// @return Eth Vault
function getEthVault()
public
view
returns (address)
{
return address(ethVault);
}
}

View File

@ -23,9 +23,6 @@ import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
import "../interfaces/IStructs.sol"; import "../interfaces/IStructs.sol";
import "../interfaces/IStakingEvents.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol";
import "./MixinStakingPoolRewards.sol"; import "./MixinStakingPoolRewards.sol";
@ -53,18 +50,8 @@ import "./MixinStakingPoolRewards.sol";
/// 2. Add the addresses that you use to market make on 0x. /// 2. Add the addresses that you use to market make on 0x.
/// 3. Leverage the staking power of others by convincing them to delegate to your pool. /// 3. Leverage the staking power of others by convincing them to delegate to your pool.
contract MixinStakingPool is contract MixinStakingPool is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinZrxVault,
MixinStakingPoolRewardVault,
MixinScheduler,
MixinStakeStorage,
MixinStakeBalances,
MixinStakingPoolRewards MixinStakingPoolRewards
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
/// @dev Create a new staking pool. The sender will be the operator of this pool. /// @dev Create a new staking pool. The sender will be the operator of this pool.
@ -120,9 +107,9 @@ contract MixinStakingPool is
return poolId; return poolId;
} }
function joinStakingPoolAsMaker( /// @dev Allows caller to join a staking pool if already assigned.
bytes32 poolId /// @param poolId Unique id of pool.
) function joinStakingPoolAsMaker(bytes32 poolId)
external external
{ {
// Is the maker already in a pool? // Is the maker already in a pool?
@ -179,7 +166,7 @@ contract MixinStakingPool is
} }
// Is the pool already full? // Is the pool already full?
if (getNumberOfMakersInStakingPool(poolId) == maximumMakersInPool) { if (numMakersByPoolId[poolId] == maximumMakersInPool) {
LibRichErrors.rrevert(LibStakingRichErrors.MakerPoolAssignmentError( LibRichErrors.rrevert(LibStakingRichErrors.MakerPoolAssignmentError(
LibStakingRichErrors.MakerPoolAssignmentErrorCodes.PoolIsFull, LibStakingRichErrors.MakerPoolAssignmentErrorCodes.PoolIsFull,
makerAddress, makerAddress,
@ -264,27 +251,6 @@ contract MixinStakingPool is
return poolJoinedByMakerAddress[makerAddress].confirmed; return poolJoinedByMakerAddress[makerAddress].confirmed;
} }
/// @dev Returns the current number of makers in a given pool.
/// @param poolId Unique id of pool.
/// @return Size of pool.
function getNumberOfMakersInStakingPool(bytes32 poolId)
public
view
returns (uint256)
{
return numMakersByPoolId[poolId];
}
/// @dev Returns the unique id that will be assigned to the next pool that is created.
/// @return Pool id.
function getNextStakingPoolId()
public
view
returns (bytes32)
{
return nextPoolId;
}
/// @dev Computes the unique id that comes after the input pool id. /// @dev Computes the unique id that comes after the input pool id.
/// @param poolId Unique id of pool. /// @param poolId Unique id of pool.
/// @return Next pool id after input pool. /// @return Next pool id after input pool.

View File

@ -30,11 +30,8 @@ import "../immutable/MixinStorage.sol";
/// from within this contract. /// from within this contract.
contract MixinStakingPoolRewardVault is contract MixinStakingPoolRewardVault is
IStakingEvents, IStakingEvents,
MixinConstants,
Ownable,
MixinStorage MixinStorage
{ {
/// @dev Asserts that the sender is the operator of the input pool. /// @dev Asserts that the sender is the operator of the input pool.
/// @param poolId Pool sender must be operator of. /// @param poolId Pool sender must be operator of.
modifier onlyStakingPoolOperator(bytes32 poolId) { modifier onlyStakingPoolOperator(bytes32 poolId) {
@ -80,23 +77,13 @@ contract MixinStakingPoolRewardVault is
emit StakingPoolRewardVaultChanged(rewardVaultAddress); emit StakingPoolRewardVaultChanged(rewardVaultAddress);
} }
/// @dev Returns the staking pool reward vault
/// @return Address of reward vault.
function getStakingPoolRewardVault()
public
view
returns (address)
{
return address(rewardVault);
}
/// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members). /// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
/// Note that this is only callable by the pool operator, and will revert if the new operator /// Note that this is only callable by the pool operator, and will revert if the new operator
/// share value is greater than the old value. /// share value is greater than the old value.
/// @param poolId Unique Id of pool. /// @param poolId Unique Id of pool.
/// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator. /// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare) function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
public external
onlyStakingPoolOperator(poolId) onlyStakingPoolOperator(poolId)
{ {
rewardVault.decreaseOperatorShare(poolId, newOperatorShare); rewardVault.decreaseOperatorShare(poolId, newOperatorShare);

View File

@ -21,26 +21,12 @@ pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibFractions.sol"; import "@0x/contracts-utils/contracts/src/LibFractions.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../immutable/MixinStorage.sol";
import "../immutable/MixinConstants.sol";
import "../stake/MixinStakeBalances.sol";
import "./MixinStakingPoolRewardVault.sol";
import "./MixinCumulativeRewards.sol"; import "./MixinCumulativeRewards.sol";
contract MixinStakingPoolRewards is contract MixinStakingPoolRewards is
IStakingEvents,
MixinConstants,
Ownable,
MixinStorage,
MixinZrxVault,
MixinStakingPoolRewardVault,
MixinScheduler,
MixinStakeStorage,
MixinStakeBalances,
MixinCumulativeRewards MixinCumulativeRewards
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
/// @dev Computes the reward balance in ETH of a specific member of a pool. /// @dev Computes the reward balance in ETH of a specific member of a pool.
@ -54,8 +40,8 @@ contract MixinStakingPoolRewards is
{ {
return _computeRewardBalanceOfDelegator( return _computeRewardBalanceOfDelegator(
poolId, poolId,
_loadUnsyncedBalance(delegatedStakeToPoolByOwner[member][poolId]), _loadUnsyncedBalance(_delegatedStakeToPoolByOwner[member][poolId]),
getCurrentEpoch() currentEpoch
); );
} }
@ -73,8 +59,6 @@ contract MixinStakingPoolRewards is
) )
internal internal
{ {
uint256 currentEpoch = getCurrentEpoch();
// transfer any rewards from the transient pool vault to the eth vault; // transfer any rewards from the transient pool vault to the eth vault;
// this must be done before we can modify the owner's portion of the delegator pool. // this must be done before we can modify the owner's portion of the delegator pool.
_transferDelegatorRewardsToEthVault( _transferDelegatorRewardsToEthVault(
@ -99,7 +83,7 @@ contract MixinStakingPoolRewards is
); );
} }
/// @dev Records a reward for delegators. This adds to the `cumulativeRewardsByPool`. /// @dev Records a reward for delegators. This adds to the `_cumulativeRewardsByPool`.
/// @param poolId Unique Id of pool. /// @param poolId Unique Id of pool.
/// @param reward to record for delegators. /// @param reward to record for delegators.
/// @param amountOfDelegatedStake the amount of delegated stake that will split this reward. /// @param amountOfDelegatedStake the amount of delegated stake that will split this reward.
@ -113,12 +97,12 @@ contract MixinStakingPoolRewards is
internal internal
{ {
// cache a storage pointer to the cumulative rewards for `poolId` indexed by epoch. // cache a storage pointer to the cumulative rewards for `poolId` indexed by epoch.
mapping (uint256 => IStructs.Fraction) storage cumulativeRewardsByPoolPtr = cumulativeRewardsByPool[poolId]; mapping (uint256 => IStructs.Fraction) storage _cumulativeRewardsByPoolPtr = _cumulativeRewardsByPool[poolId];
// fetch the last epoch at which we stored an entry for this pool; // 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. // this is the most up-to-date cumulative rewards for this pool.
uint256 cumulativeRewardsLastStored = cumulativeRewardsByPoolLastStored[poolId]; uint256 cumulativeRewardsLastStored = _cumulativeRewardsByPoolLastStored[poolId];
IStructs.Fraction memory mostRecentCumulativeRewards = cumulativeRewardsByPoolPtr[cumulativeRewardsLastStored]; IStructs.Fraction memory mostRecentCumulativeRewards = _cumulativeRewardsByPoolPtr[cumulativeRewardsLastStored];
// compute new cumulative reward // compute new cumulative reward
(uint256 numerator, uint256 denominator) = LibFractions.addFractions( (uint256 numerator, uint256 denominator) = LibFractions.addFractions(
@ -204,12 +188,12 @@ contract MixinStakingPoolRewards is
// compute the reward accumulated by the `next` balance; // compute the reward accumulated by the `next` balance;
// this starts at `delegatedStake.currentEpoch + 1` and goes up until the last epoch, during which // this starts at `delegatedStake.currentEpoch + 1` and goes up until the last epoch, during which
// rewards were accumulated. This is at most the most recently finalized epoch (current epoch - 1). // rewards were accumulated. This is at most the most recently finalized epoch (current epoch - 1).
uint256 rewardsAccumulatedAfterLastStoredEpoch = (cumulativeRewardsByPoolLastStored[poolId] > unsyncedDelegatedStakeToPoolByOwner.currentEpoch) uint256 rewardsAccumulatedAfterLastStoredEpoch = (_cumulativeRewardsByPoolLastStored[poolId] > unsyncedDelegatedStakeToPoolByOwner.currentEpoch)
? _computeMemberRewardOverInterval( ? _computeMemberRewardOverInterval(
poolId, poolId,
unsyncedDelegatedStakeToPoolByOwner.nextEpochBalance, unsyncedDelegatedStakeToPoolByOwner.nextEpochBalance,
unsyncedDelegatedStakeToPoolByOwner.currentEpoch, unsyncedDelegatedStakeToPoolByOwner.currentEpoch,
cumulativeRewardsByPoolLastStored[poolId] _cumulativeRewardsByPoolLastStored[poolId]
) )
: 0; : 0;
@ -222,17 +206,17 @@ contract MixinStakingPoolRewards is
/// A delegator always depends on the cumulative reward for the current epoch. /// A delegator always depends on the cumulative reward for the current epoch.
/// They will also depend on the previous epoch's reward, if they are already staked with the input pool. /// They will also depend on the previous epoch's reward, if they are already staked with the input pool.
/// @param poolId Unique id of pool. /// @param poolId Unique id of pool.
/// @param delegatedStakeToPoolByOwner Amount of stake the member has delegated to the pool. /// @param _delegatedStakeToPoolByOwner Amount of stake the member has delegated to the pool.
/// @param isDependent is true iff adding a dependency. False, otherwise. /// @param isDependent is true iff adding a dependency. False, otherwise.
function _setCumulativeRewardDependenciesForDelegator( function _setCumulativeRewardDependenciesForDelegator(
bytes32 poolId, bytes32 poolId,
IStructs.StoredBalance memory delegatedStakeToPoolByOwner, IStructs.StoredBalance memory _delegatedStakeToPoolByOwner,
bool isDependent bool isDependent
) )
private private
{ {
// if this delegator is not yet initialized then there's no dependency to unset. // if this delegator is not yet initialized then there's no dependency to unset.
if (!isDependent && !delegatedStakeToPoolByOwner.isInitialized) { if (!isDependent && !_delegatedStakeToPoolByOwner.isInitialized) {
return; return;
} }
@ -240,20 +224,20 @@ contract MixinStakingPoolRewards is
IStructs.CumulativeRewardInfo memory mostRecentCumulativeRewardInfo = _getMostRecentCumulativeRewardInfo(poolId); IStructs.CumulativeRewardInfo memory mostRecentCumulativeRewardInfo = _getMostRecentCumulativeRewardInfo(poolId);
// record dependency on `lastEpoch` // record dependency on `lastEpoch`
if (delegatedStakeToPoolByOwner.currentEpoch > 0 && delegatedStakeToPoolByOwner.currentEpochBalance != 0) { if (_delegatedStakeToPoolByOwner.currentEpoch > 0 && _delegatedStakeToPoolByOwner.currentEpochBalance != 0) {
_addOrRemoveDependencyOnCumulativeReward( _addOrRemoveDependencyOnCumulativeReward(
poolId, poolId,
uint256(delegatedStakeToPoolByOwner.currentEpoch).safeSub(1), uint256(_delegatedStakeToPoolByOwner.currentEpoch).safeSub(1),
mostRecentCumulativeRewardInfo, mostRecentCumulativeRewardInfo,
isDependent isDependent
); );
} }
// record dependency on current epoch. // record dependency on current epoch.
if (delegatedStakeToPoolByOwner.currentEpochBalance != 0 || delegatedStakeToPoolByOwner.nextEpochBalance != 0) { if (_delegatedStakeToPoolByOwner.currentEpochBalance != 0 || _delegatedStakeToPoolByOwner.nextEpochBalance != 0) {
_addOrRemoveDependencyOnCumulativeReward( _addOrRemoveDependencyOnCumulativeReward(
poolId, poolId,
delegatedStakeToPoolByOwner.currentEpoch, _delegatedStakeToPoolByOwner.currentEpoch,
mostRecentCumulativeRewardInfo, mostRecentCumulativeRewardInfo,
isDependent isDependent
); );

View File

@ -19,8 +19,6 @@
pragma solidity ^0.5.9; pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol"; import "../immutable/MixinStorage.sol";
import "../interfaces/IStakingEvents.sol"; import "../interfaces/IStakingEvents.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
@ -28,11 +26,8 @@ import "../libs/LibStakingRichErrors.sol";
contract MixinParams is contract MixinParams is
IStakingEvents, IStakingEvents,
MixinConstants,
Ownable,
MixinStorage MixinStorage
{ {
/// @dev Set all configurable parameters at once. /// @dev Set all configurable parameters at once.
/// @param _epochDurationInSeconds Minimum seconds between epochs. /// @param _epochDurationInSeconds Minimum seconds between epochs.
/// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm. /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.

View File

@ -21,9 +21,7 @@ pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
import "../immutable/MixinConstants.sol";
import "../immutable/MixinStorage.sol"; import "../immutable/MixinStorage.sol";
import "../interfaces/IStructs.sol";
import "../interfaces/IStakingEvents.sol"; import "../interfaces/IStakingEvents.sol";
@ -35,34 +33,10 @@ import "../interfaces/IStakingEvents.sol";
/// and consistent scheduling metric than time. TimeLocks, for example, are measured in epochs. /// and consistent scheduling metric than time. TimeLocks, for example, are measured in epochs.
contract MixinScheduler is contract MixinScheduler is
IStakingEvents, IStakingEvents,
MixinConstants,
Ownable,
MixinStorage MixinStorage
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
/// @dev Returns the current epoch.
/// @return Epoch.
function getCurrentEpoch()
public
view
returns (uint256)
{
return currentEpoch;
}
/// @dev Returns the start time in seconds of the current epoch.
/// Epoch period = [startTimeInSeconds..endTimeInSeconds)
/// @return Time in seconds.
function getCurrentEpochStartTimeInSeconds()
public
view
returns (uint256)
{
return currentEpochStartTimeInSeconds;
}
/// @dev Returns the earliest end time in seconds of this epoch. /// @dev Returns the earliest end time in seconds of this epoch.
/// The next epoch can begin once this time is reached. /// The next epoch can begin once this time is reached.
/// Epoch period = [startTimeInSeconds..endTimeInSeconds) /// Epoch period = [startTimeInSeconds..endTimeInSeconds)
@ -72,7 +46,7 @@ contract MixinScheduler is
view view
returns (uint256) returns (uint256)
{ {
return getCurrentEpochStartTimeInSeconds().safeAdd(epochDurationInSeconds); return currentEpochStartTimeInSeconds.safeAdd(epochDurationInSeconds);
} }
/// @dev Assert scheduler state before initializing it. /// @dev Assert scheduler state before initializing it.

View File

@ -25,16 +25,13 @@ import "./MixinVaultCore.sol";
/// @dev This vault manages ETH. /// @dev This vault manages ETH.
contract EthVault is contract EthVault is
Authorizable,
IEthVault, IEthVault,
IVaultCore,
MixinVaultCore MixinVaultCore
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
// mapping from Owner to ETH balance // mapping from Owner to ETH balance
mapping (address => uint256) internal balances; mapping (address => uint256) internal _balances;
/// @dev Constructor. /// @dev Constructor.
constructor() constructor()
@ -51,7 +48,7 @@ contract EthVault is
{ {
// update balance // update balance
uint256 amount = msg.value; uint256 amount = msg.value;
balances[owner] = balances[owner].safeAdd(msg.value); _balances[owner] = _balances[owner].safeAdd(msg.value);
// notify // notify
emit EthDepositedIntoVault(msg.sender, owner, amount); emit EthDepositedIntoVault(msg.sender, owner, amount);
@ -74,7 +71,7 @@ contract EthVault is
{ {
// get total balance // get total balance
address payable owner = msg.sender; address payable owner = msg.sender;
totalBalance = balances[owner]; totalBalance = _balances[owner];
// withdraw ETH to owner // withdraw ETH to owner
_withdrawFrom(owner, totalBalance); _withdrawFrom(owner, totalBalance);
@ -88,7 +85,7 @@ contract EthVault is
view view
returns (uint256) returns (uint256)
{ {
return balances[owner]; return _balances[owner];
} }
/// @dev Withdraw an `amount` of ETH to `owner` from the vault. /// @dev Withdraw an `amount` of ETH to `owner` from the vault.
@ -100,7 +97,7 @@ contract EthVault is
// update balance // update balance
// note that this call will revert if trying to withdraw more // note that this call will revert if trying to withdraw more
// than the current balance // than the current balance
balances[owner] = balances[owner].safeSub(amount); _balances[owner] = _balances[owner].safeSub(amount);
// notify // notify
emit EthWithdrawnFromVault(msg.sender, owner, amount); emit EthWithdrawnFromVault(msg.sender, owner, amount);

View File

@ -18,7 +18,7 @@
pragma solidity ^0.5.9; pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/Authorizable.sol"; import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "../libs/LibStakingRichErrors.sol"; import "../libs/LibStakingRichErrors.sol";
import "../interfaces/IVaultCore.sol"; import "../interfaces/IVaultCore.sol";
@ -36,10 +36,9 @@ import "../interfaces/IVaultCore.sol";
/// a vault cannot be reset to normal mode; this prevents corruption of related /// a vault cannot be reset to normal mode; this prevents corruption of related
/// status in the staking contract. /// status in the staking contract.
contract MixinVaultCore is contract MixinVaultCore is
Authorizable, Ownable,
IVaultCore IVaultCore
{ {
// Address of staking contract // Address of staking contract
address payable internal stakingContractAddress; address payable internal stakingContractAddress;

View File

@ -40,21 +40,18 @@ import "../immutable/MixinConstants.sol";
/// When in Catastrophic Failure Mode, the Staking contract can still /// When in Catastrophic Failure Mode, the Staking contract can still
/// perform withdrawals on behalf of its users. /// perform withdrawals on behalf of its users.
contract StakingPoolRewardVault is contract StakingPoolRewardVault is
Authorizable,
IStakingPoolRewardVault, IStakingPoolRewardVault,
IVaultCore,
MixinConstants, MixinConstants,
MixinVaultCore MixinVaultCore
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
using LibSafeDowncast for uint256; using LibSafeDowncast for uint256;
// mapping from poolId to Pool metadata // mapping from poolId to Pool metadata
mapping (bytes32 => Pool) internal poolById; mapping (bytes32 => Pool) public poolById;
// address of ether vault // address of ether vault
IEthVault internal ethVault; IEthVault internal _ethVault;
/// @dev Fallback function. This contract is payable, but only by the staking contract. /// @dev Fallback function. This contract is payable, but only by the staking contract.
function () function ()
@ -73,7 +70,7 @@ contract StakingPoolRewardVault is
external external
onlyOwner onlyOwner
{ {
ethVault = IEthVault(ethVaultAddress); _ethVault = IEthVault(ethVaultAddress);
emit EthVaultChanged(ethVaultAddress); emit EthVaultChanged(ethVaultAddress);
} }
@ -256,39 +253,6 @@ contract StakingPoolRewardVault is
return poolById[poolId].operatorBalance + poolById[poolId].membersBalance; return poolById[poolId].operatorBalance + poolById[poolId].membersBalance;
} }
/// @dev Returns the balance of a pool operator.
/// @param poolId Unique Id of pool.
/// @return Balance in ETH.
function balanceOfOperator(bytes32 poolId)
external
view
returns (uint256)
{
return poolById[poolId].operatorBalance;
}
/// @dev Returns the balance co-owned by members of a pool.
/// @param poolId Unique Id of pool.
/// @return Balance in ETH.
function balanceOfMembers(bytes32 poolId)
external
view
returns (uint256)
{
return poolById[poolId].membersBalance;
}
/// @dev Returns the operator share of a pool's balance.
/// @param poolId Unique Id of pool.
/// @return Operator share (integer out of 100)
function getOperatorShare(bytes32 poolId)
external
view
returns (uint256)
{
return poolById[poolId].operatorShare;
}
/// @dev Increments a balances in a Pool struct, splitting the input amount between the /// @dev Increments a balances in a Pool struct, splitting the input amount between the
/// pool operator and members of the pool based on the pool operator's share. /// pool operator and members of the pool based on the pool operator's share.
/// @param pool Pool struct with the balances to increment. /// @param pool Pool struct with the balances to increment.
@ -328,14 +292,14 @@ contract StakingPoolRewardVault is
private private
{ {
// sanity check on eth vault // sanity check on eth vault
IEthVault _ethVault = ethVault; IEthVault ethVault_ = _ethVault;
if (address(_ethVault) == address(0)) { if (address(ethVault_) == address(0)) {
LibRichErrors.rrevert( LibRichErrors.rrevert(
LibStakingRichErrors.EthVaultNotSetError() LibStakingRichErrors.EthVaultNotSetError()
); );
} }
// perform xfer // perform xfer
_ethVault.depositFor.value(amount)(from); ethVault_.depositFor.value(amount)(from);
} }
} }

View File

@ -34,40 +34,37 @@ import "./MixinVaultCore.sol";
/// failure mode, it cannot be returned to normal mode; this prevents /// failure mode, it cannot be returned to normal mode; this prevents
/// corruption of related state in the staking contract. /// corruption of related state in the staking contract.
contract ZrxVault is contract ZrxVault is
Authorizable,
IVaultCore,
IZrxVault, IZrxVault,
MixinVaultCore MixinVaultCore
{ {
using LibSafeMath for uint256; using LibSafeMath for uint256;
// mapping from Owner to ZRX balance // mapping from Owner to ZRX balance
mapping (address => uint256) internal balances; mapping (address => uint256) internal _balances;
// Zrx Asset Proxy // Zrx Asset Proxy
IAssetProxy internal zrxAssetProxy; IAssetProxy public zrxAssetProxy;
// Zrx Token // Zrx Token
IERC20Token internal zrxToken; IERC20Token internal _zrxToken;
// Asset data for the ERC20 Proxy // Asset data for the ERC20 Proxy
bytes internal zrxAssetData; bytes internal _zrxAssetData;
/// @dev Constructor. /// @dev Constructor.
/// @param zrxProxyAddress Address of the 0x Zrx Proxy. /// @param zrxProxyAddress Address of the 0x Zrx Proxy.
/// @param zrxTokenAddress Address of the Zrx Token. /// @param _zrxTokenAddress Address of the Zrx Token.
constructor( constructor(
address zrxProxyAddress, address zrxProxyAddress,
address zrxTokenAddress address _zrxTokenAddress
) )
public public
{ {
zrxAssetProxy = IAssetProxy(zrxProxyAddress); zrxAssetProxy = IAssetProxy(zrxProxyAddress);
zrxToken = IERC20Token(zrxTokenAddress); _zrxToken = IERC20Token(_zrxTokenAddress);
zrxAssetData = abi.encodeWithSelector( _zrxAssetData = abi.encodeWithSelector(
IAssetData(address(0)).ERC20Token.selector, IAssetData(address(0)).ERC20Token.selector,
zrxTokenAddress _zrxTokenAddress
); );
} }
@ -95,14 +92,14 @@ contract ZrxVault is
onlyNotInCatastrophicFailure onlyNotInCatastrophicFailure
{ {
// update balance // update balance
balances[owner] = balances[owner].safeAdd(amount); _balances[owner] = _balances[owner].safeAdd(amount);
// notify // notify
emit ZrxDepositedIntoVault(msg.sender, owner, amount); emit ZrxDepositedIntoVault(msg.sender, owner, amount);
// deposit ZRX from owner // deposit ZRX from owner
zrxAssetProxy.transferFrom( zrxAssetProxy.transferFrom(
zrxAssetData, _zrxAssetData,
owner, owner,
address(this), address(this),
amount amount
@ -131,7 +128,7 @@ contract ZrxVault is
returns (uint256) returns (uint256)
{ {
// get total balance // get total balance
uint256 totalBalance = balances[owner]; uint256 totalBalance = _balances[owner];
// withdraw ZRX to owner // withdraw ZRX to owner
_withdrawFrom(owner, totalBalance); _withdrawFrom(owner, totalBalance);
@ -145,7 +142,7 @@ contract ZrxVault is
view view
returns (uint256) returns (uint256)
{ {
return balances[owner]; return _balances[owner];
} }
/// @dev Withdraw an `amount` of Zrx Tokens to `owner` from the vault. /// @dev Withdraw an `amount` of Zrx Tokens to `owner` from the vault.
@ -157,13 +154,13 @@ contract ZrxVault is
// update balance // update balance
// note that this call will revert if trying to withdraw more // note that this call will revert if trying to withdraw more
// than the current balance // than the current balance
balances[owner] = balances[owner].safeSub(amount); _balances[owner] = _balances[owner].safeSub(amount);
// notify // notify
emit ZrxWithdrawnFromVault(msg.sender, owner, amount); emit ZrxWithdrawnFromVault(msg.sender, owner, amount);
// withdraw ZRX to owner // withdraw ZRX to owner
zrxToken.transfer( _zrxToken.transfer(
owner, owner,
amount amount
); );

View File

@ -55,22 +55,22 @@ contract TestStorageLayout is
if sub(stakingContract_slot, slot) { revertIncorrectStorageSlot() } if sub(stakingContract_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(activeStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } if sub(_activeStakeByOwner_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(inactiveStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } if sub(_inactiveStakeByOwner_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(delegatedStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } if sub(_delegatedStakeByOwner_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(delegatedStakeToPoolByOwner_slot, slot) { revertIncorrectStorageSlot() } if sub(_delegatedStakeToPoolByOwner_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(delegatedStakeByPoolId_slot, slot) { revertIncorrectStorageSlot() } if sub(_delegatedStakeByPoolId_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(withdrawableStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } if sub(_withdrawableStakeByOwner_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(nextPoolId_slot, slot) { revertIncorrectStorageSlot() } if sub(nextPoolId_slot, slot) { revertIncorrectStorageSlot() }
@ -94,13 +94,13 @@ contract TestStorageLayout is
if sub(activePoolsThisEpoch_slot, slot) { revertIncorrectStorageSlot() } if sub(activePoolsThisEpoch_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(cumulativeRewardsByPool_slot, slot) { revertIncorrectStorageSlot() } if sub(_cumulativeRewardsByPool_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(cumulativeRewardsByPoolReferenceCounter_slot, slot) { revertIncorrectStorageSlot() } if sub(_cumulativeRewardsByPoolReferenceCounter_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(cumulativeRewardsByPoolLastStored_slot, slot) { revertIncorrectStorageSlot() } if sub(_cumulativeRewardsByPoolLastStored_slot, slot) { revertIncorrectStorageSlot() }
slot := add(slot, 1) slot := add(slot, 1)
if sub(validExchanges_slot, slot) { revertIncorrectStorageSlot() } if sub(validExchanges_slot, slot) { revertIncorrectStorageSlot() }

View File

@ -37,7 +37,7 @@
}, },
"config": { "config": {
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually.", "abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually.",
"abis": "./generated-artifacts/@(EthVault|IEthVault|IStaking|IStakingEvents|IStakingPoolRewardVault|IStakingProxy|IStorageInit|IStructs|IVaultCore|IZrxVault|LibFixedMath|LibFixedMathRichErrors|LibProxy|LibSafeDowncast|LibStakingRichErrors|MixinConstants|MixinCumulativeRewards|MixinDeploymentConstants|MixinEthVault|MixinExchangeFees|MixinExchangeManager|MixinParams|MixinScheduler|MixinStake|MixinStakeBalances|MixinStakeStorage|MixinStakingPool|MixinStakingPoolRewardVault|MixinStakingPoolRewards|MixinStorage|MixinVaultCore|MixinZrxVault|ReadOnlyProxy|Staking|StakingPoolRewardVault|StakingProxy|TestCobbDouglas|TestCumulativeRewardTracking|TestInitTarget|TestLibFixedMath|TestLibProxy|TestLibProxyReceiver|TestLibSafeDowncast|TestProtocolFees|TestProtocolFeesERC20Proxy|TestStaking|TestStakingProxy|TestStorageLayout|ZrxVault).json" "abis": "./generated-artifacts/@(EthVault|IEthVault|IStaking|IStakingEvents|IStakingPoolRewardVault|IStakingProxy|IStorage|IStorageInit|IStructs|IVaultCore|IZrxVault|LibFixedMath|LibFixedMathRichErrors|LibProxy|LibSafeDowncast|LibStakingRichErrors|MixinConstants|MixinCumulativeRewards|MixinDeploymentConstants|MixinExchangeFees|MixinExchangeManager|MixinParams|MixinScheduler|MixinStake|MixinStakeBalances|MixinStakeStorage|MixinStakingPool|MixinStakingPoolRewardVault|MixinStakingPoolRewards|MixinStorage|MixinVaultCore|MixinZrxVault|ReadOnlyProxy|Staking|StakingPoolRewardVault|StakingProxy|TestCobbDouglas|TestCumulativeRewardTracking|TestInitTarget|TestLibFixedMath|TestLibProxy|TestLibProxyReceiver|TestLibSafeDowncast|TestProtocolFees|TestProtocolFeesERC20Proxy|TestStaking|TestStakingProxy|TestStorageLayout|ZrxVault).json"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

@ -11,6 +11,7 @@ import * as IStaking from '../generated-artifacts/IStaking.json';
import * as IStakingEvents from '../generated-artifacts/IStakingEvents.json'; import * as IStakingEvents from '../generated-artifacts/IStakingEvents.json';
import * as IStakingPoolRewardVault from '../generated-artifacts/IStakingPoolRewardVault.json'; import * as IStakingPoolRewardVault from '../generated-artifacts/IStakingPoolRewardVault.json';
import * as IStakingProxy from '../generated-artifacts/IStakingProxy.json'; import * as IStakingProxy from '../generated-artifacts/IStakingProxy.json';
import * as IStorage from '../generated-artifacts/IStorage.json';
import * as IStorageInit from '../generated-artifacts/IStorageInit.json'; import * as IStorageInit from '../generated-artifacts/IStorageInit.json';
import * as IStructs from '../generated-artifacts/IStructs.json'; import * as IStructs from '../generated-artifacts/IStructs.json';
import * as IVaultCore from '../generated-artifacts/IVaultCore.json'; import * as IVaultCore from '../generated-artifacts/IVaultCore.json';
@ -23,7 +24,6 @@ import * as LibStakingRichErrors from '../generated-artifacts/LibStakingRichErro
import * as MixinConstants from '../generated-artifacts/MixinConstants.json'; import * as MixinConstants from '../generated-artifacts/MixinConstants.json';
import * as MixinCumulativeRewards from '../generated-artifacts/MixinCumulativeRewards.json'; import * as MixinCumulativeRewards from '../generated-artifacts/MixinCumulativeRewards.json';
import * as MixinDeploymentConstants from '../generated-artifacts/MixinDeploymentConstants.json'; import * as MixinDeploymentConstants from '../generated-artifacts/MixinDeploymentConstants.json';
import * as MixinEthVault from '../generated-artifacts/MixinEthVault.json';
import * as MixinExchangeFees from '../generated-artifacts/MixinExchangeFees.json'; import * as MixinExchangeFees from '../generated-artifacts/MixinExchangeFees.json';
import * as MixinExchangeManager from '../generated-artifacts/MixinExchangeManager.json'; import * as MixinExchangeManager from '../generated-artifacts/MixinExchangeManager.json';
import * as MixinParams from '../generated-artifacts/MixinParams.json'; import * as MixinParams from '../generated-artifacts/MixinParams.json';
@ -68,6 +68,7 @@ export const artifacts = {
IStakingEvents: IStakingEvents as ContractArtifact, IStakingEvents: IStakingEvents as ContractArtifact,
IStakingPoolRewardVault: IStakingPoolRewardVault as ContractArtifact, IStakingPoolRewardVault: IStakingPoolRewardVault as ContractArtifact,
IStakingProxy: IStakingProxy as ContractArtifact, IStakingProxy: IStakingProxy as ContractArtifact,
IStorage: IStorage as ContractArtifact,
IStorageInit: IStorageInit as ContractArtifact, IStorageInit: IStorageInit as ContractArtifact,
IStructs: IStructs as ContractArtifact, IStructs: IStructs as ContractArtifact,
IVaultCore: IVaultCore as ContractArtifact, IVaultCore: IVaultCore as ContractArtifact,
@ -82,7 +83,6 @@ export const artifacts = {
MixinStakeStorage: MixinStakeStorage as ContractArtifact, MixinStakeStorage: MixinStakeStorage as ContractArtifact,
MixinZrxVault: MixinZrxVault as ContractArtifact, MixinZrxVault: MixinZrxVault as ContractArtifact,
MixinCumulativeRewards: MixinCumulativeRewards as ContractArtifact, MixinCumulativeRewards: MixinCumulativeRewards as ContractArtifact,
MixinEthVault: MixinEthVault as ContractArtifact,
MixinStakingPool: MixinStakingPool as ContractArtifact, MixinStakingPool: MixinStakingPool as ContractArtifact,
MixinStakingPoolRewardVault: MixinStakingPoolRewardVault as ContractArtifact, MixinStakingPoolRewardVault: MixinStakingPoolRewardVault as ContractArtifact,
MixinStakingPoolRewards: MixinStakingPoolRewards as ContractArtifact, MixinStakingPoolRewards: MixinStakingPoolRewards as ContractArtifact,

View File

@ -9,6 +9,7 @@ export * from '../generated-wrappers/i_staking';
export * from '../generated-wrappers/i_staking_events'; export * from '../generated-wrappers/i_staking_events';
export * from '../generated-wrappers/i_staking_pool_reward_vault'; export * from '../generated-wrappers/i_staking_pool_reward_vault';
export * from '../generated-wrappers/i_staking_proxy'; export * from '../generated-wrappers/i_staking_proxy';
export * from '../generated-wrappers/i_storage';
export * from '../generated-wrappers/i_storage_init'; export * from '../generated-wrappers/i_storage_init';
export * from '../generated-wrappers/i_structs'; export * from '../generated-wrappers/i_structs';
export * from '../generated-wrappers/i_vault_core'; export * from '../generated-wrappers/i_vault_core';
@ -21,7 +22,6 @@ export * from '../generated-wrappers/lib_staking_rich_errors';
export * from '../generated-wrappers/mixin_constants'; export * from '../generated-wrappers/mixin_constants';
export * from '../generated-wrappers/mixin_cumulative_rewards'; export * from '../generated-wrappers/mixin_cumulative_rewards';
export * from '../generated-wrappers/mixin_deployment_constants'; export * from '../generated-wrappers/mixin_deployment_constants';
export * from '../generated-wrappers/mixin_eth_vault';
export * from '../generated-wrappers/mixin_exchange_fees'; export * from '../generated-wrappers/mixin_exchange_fees';
export * from '../generated-wrappers/mixin_exchange_manager'; export * from '../generated-wrappers/mixin_exchange_manager';
export * from '../generated-wrappers/mixin_params'; export * from '../generated-wrappers/mixin_params';

View File

@ -164,7 +164,8 @@ export class FinalizerActor extends BaseActor {
private async _getOperatorShareByPoolIdAsync(poolIds: string[]): Promise<OperatorShareByPoolId> { private async _getOperatorShareByPoolIdAsync(poolIds: string[]): Promise<OperatorShareByPoolId> {
const operatorShareByPoolId: OperatorShareByPoolId = {}; const operatorShareByPoolId: OperatorShareByPoolId = {};
for (const poolId of poolIds) { for (const poolId of poolIds) {
const operatorShare = await this._stakingApiWrapper.rewardVaultContract.getOperatorShare.callAsync(poolId); const pool = await this._stakingApiWrapper.rewardVaultContract.poolById.callAsync(poolId);
const operatorShare = new BigNumber(pool[1]);
operatorShareByPoolId[poolId] = operatorShare; operatorShareByPoolId[poolId] = operatorShare;
} }
return operatorShareByPoolId; return operatorShareByPoolId;
@ -179,15 +180,13 @@ export class FinalizerActor extends BaseActor {
} }
private async _getRewardVaultBalanceAsync(poolId: string): Promise<RewardVaultBalance> { private async _getRewardVaultBalanceAsync(poolId: string): Promise<RewardVaultBalance> {
const balances = await Promise.all([ const pool = await this._stakingApiWrapper.rewardVaultContract.poolById.callAsync(poolId);
this._stakingApiWrapper.rewardVaultContract.balanceOf.callAsync(poolId), const operatorBalance = pool[2];
this._stakingApiWrapper.rewardVaultContract.balanceOfOperator.callAsync(poolId), const membersBalance = pool[3];
this._stakingApiWrapper.rewardVaultContract.balanceOfMembers.callAsync(poolId),
]);
return { return {
poolBalance: balances[0], poolBalance: operatorBalance.plus(membersBalance),
operatorBalance: balances[1], operatorBalance,
membersBalance: balances[2], membersBalance,
}; };
} }
} }

View File

@ -1,5 +1,5 @@
import { expect } from '@0x/contracts-test-utils'; import { expect } from '@0x/contracts-test-utils';
import { RevertError } from '@0x/utils'; import { BigNumber, RevertError } from '@0x/utils';
import * as _ from 'lodash'; import * as _ from 'lodash';
import { constants as stakingConstants } from '../utils/constants'; import { constants as stakingConstants } from '../utils/constants';
@ -13,7 +13,7 @@ export class PoolOperatorActor extends BaseActor {
revertError?: RevertError, revertError?: RevertError,
): Promise<string> { ): Promise<string> {
// query next pool id // query next pool id
const nextPoolId = await this._stakingApiWrapper.stakingContract.getNextStakingPoolId.callAsync(); const nextPoolId = await this._stakingApiWrapper.stakingContract.nextPoolId.callAsync();
// create pool // create pool
const poolIdPromise = this._stakingApiWrapper.utils.createStakingPoolAsync( const poolIdPromise = this._stakingApiWrapper.utils.createStakingPoolAsync(
this._owner, this._owner,
@ -35,7 +35,7 @@ export class PoolOperatorActor extends BaseActor {
); );
expect(poolIdOfMaker, 'pool id of maker').to.be.equal(poolId); expect(poolIdOfMaker, 'pool id of maker').to.be.equal(poolId);
// check the number of makers in the pool // check the number of makers in the pool
const numMakersAfterRemoving = await this._stakingApiWrapper.stakingContract.getNumberOfMakersInStakingPool.callAsync( const numMakersAfterRemoving = await this._stakingApiWrapper.stakingContract.numMakersByPoolId.callAsync(
poolId, poolId,
); );
expect(numMakersAfterRemoving, 'number of makers in pool').to.be.bignumber.equal(1); expect(numMakersAfterRemoving, 'number of makers in pool').to.be.bignumber.equal(1);
@ -103,9 +103,8 @@ export class PoolOperatorActor extends BaseActor {
} }
await txReceiptPromise; await txReceiptPromise;
// Check operator share // Check operator share
const decreasedOperatorShare = await this._stakingApiWrapper.rewardVaultContract.getOperatorShare.callAsync( const pool = await this._stakingApiWrapper.rewardVaultContract.poolById.callAsync(poolId);
poolId, const decreasedOperatorShare = new BigNumber(pool[1]);
);
expect(decreasedOperatorShare, 'updated operator share').to.be.bignumber.equal(newOperatorShare); expect(decreasedOperatorShare, 'updated operator share').to.be.bignumber.equal(newOperatorShare);
} }
} }

View File

@ -34,14 +34,14 @@ blockchainTests('Epochs', env => {
///// 2/3 Validate Initial Epoch & TimeLock Period ///// ///// 2/3 Validate Initial Epoch & TimeLock Period /////
{ {
// epoch // epoch
const currentEpoch = await stakingApiWrapper.stakingContract.getCurrentEpoch.callAsync(); const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync();
expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH); expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH);
} }
///// 3/3 Increment Epoch (TimeLock Should Not Increment) ///// ///// 3/3 Increment Epoch (TimeLock Should Not Increment) /////
await stakingApiWrapper.utils.skipToNextEpochAsync(); await stakingApiWrapper.utils.skipToNextEpochAsync();
{ {
// epoch // epoch
const currentEpoch = await stakingApiWrapper.stakingContract.getCurrentEpoch.callAsync(); const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync();
expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH.plus(1)); expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH.plus(1));
} }
}); });

View File

@ -27,18 +27,14 @@ blockchainTests('Exchange Integrations', env => {
}); });
blockchainTests.resets('Exchange Tracking in Staking Contract', () => { blockchainTests.resets('Exchange Tracking in Staking Contract', () => {
it('basic exchange tracking', async () => { it('basic exchange tracking', async () => {
const { const { validExchanges, addExchangeAddress, removeExchangeAddress } = stakingApiWrapper.stakingContract;
isValidExchangeAddress,
addExchangeAddress,
removeExchangeAddress,
} = stakingApiWrapper.stakingContract;
// 1 try querying an invalid addresses // 1 try querying an invalid addresses
const invalidAddress = '0x0000000000000000000000000000000000000001'; const invalidAddress = '0x0000000000000000000000000000000000000001';
const isInvalidAddressValid = await isValidExchangeAddress.callAsync(invalidAddress); const isInvalidAddressValid = await validExchanges.callAsync(invalidAddress);
expect(isInvalidAddressValid).to.be.false(); expect(isInvalidAddressValid).to.be.false();
// 2 add valid address // 2 add valid address
await addExchangeAddress.awaitTransactionSuccessAsync(exchange); await addExchangeAddress.awaitTransactionSuccessAsync(exchange);
const isValidAddressValid = await isValidExchangeAddress.callAsync(exchange); const isValidAddressValid = await validExchanges.callAsync(exchange);
expect(isValidAddressValid).to.be.true(); expect(isValidAddressValid).to.be.true();
// 3 try adding valid address again // 3 try adding valid address again
let revertError = new StakingRevertErrors.ExchangeAddressAlreadyRegisteredError(exchange); let revertError = new StakingRevertErrors.ExchangeAddressAlreadyRegisteredError(exchange);
@ -46,7 +42,7 @@ blockchainTests('Exchange Integrations', env => {
await expect(tx).to.revertWith(revertError); await expect(tx).to.revertWith(revertError);
// 4 remove valid address // 4 remove valid address
await removeExchangeAddress.awaitTransactionSuccessAsync(exchange); await removeExchangeAddress.awaitTransactionSuccessAsync(exchange);
const isValidAddressStillValid = await isValidExchangeAddress.callAsync(exchange); const isValidAddressStillValid = await validExchanges.callAsync(exchange);
expect(isValidAddressStillValid).to.be.false(); expect(isValidAddressStillValid).to.be.false();
// 5 try removing valid address again // 5 try removing valid address again
revertError = new StakingRevertErrors.ExchangeAddressNotRegisteredError(exchange); revertError = new StakingRevertErrors.ExchangeAddressNotRegisteredError(exchange);

View File

@ -40,7 +40,7 @@ blockchainTests('Staking Pool Management', env => {
const poolId = await poolOperator.createStakingPoolAsync(operatorShare, false); const poolId = await poolOperator.createStakingPoolAsync(operatorShare, false);
expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID);
// check that the next pool id was incremented // check that the next pool id was incremented
const nextPoolId = await stakingApiWrapper.stakingContract.getNextStakingPoolId.callAsync(); const nextPoolId = await stakingApiWrapper.stakingContract.nextPoolId.callAsync();
expect(nextPoolId).to.be.equal(stakingConstants.SECOND_POOL_ID); expect(nextPoolId).to.be.equal(stakingConstants.SECOND_POOL_ID);
}); });
it('Should fail to create a pool with operator share > 100', async () => { it('Should fail to create a pool with operator share > 100', async () => {
@ -66,7 +66,7 @@ blockchainTests('Staking Pool Management', env => {
const poolId = await poolOperator.createStakingPoolAsync(operatorShare, true); const poolId = await poolOperator.createStakingPoolAsync(operatorShare, true);
expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID);
// check that the next pool id was incremented // check that the next pool id was incremented
const nextPoolId = await stakingApiWrapper.stakingContract.getNextStakingPoolId.callAsync(); const nextPoolId = await stakingApiWrapper.stakingContract.nextPoolId.callAsync();
expect(nextPoolId).to.be.equal(stakingConstants.SECOND_POOL_ID); expect(nextPoolId).to.be.equal(stakingConstants.SECOND_POOL_ID);
}); });
it('Should throw if operatorShare is > PPM_DENOMINATOR', async () => { it('Should throw if operatorShare is > PPM_DENOMINATOR', async () => {
@ -138,7 +138,7 @@ blockchainTests('Staking Pool Management', env => {
); );
// check the number of makers in the pool // check the number of makers in the pool
let numMakers = await stakingApiWrapper.stakingContract.getNumberOfMakersInStakingPool.callAsync(poolId); let numMakers = await stakingApiWrapper.stakingContract.numMakersByPoolId.callAsync(poolId);
expect(numMakers, 'number of makers in pool after adding').to.be.bignumber.equal(3); expect(numMakers, 'number of makers in pool after adding').to.be.bignumber.equal(3);
// remove maker from pool // remove maker from pool
@ -149,7 +149,7 @@ blockchainTests('Staking Pool Management', env => {
); );
// check the number of makers in the pool // check the number of makers in the pool
numMakers = await stakingApiWrapper.stakingContract.getNumberOfMakersInStakingPool.callAsync(poolId); numMakers = await stakingApiWrapper.stakingContract.numMakersByPoolId.callAsync(poolId);
expect(numMakers, 'number of makers in pool after removing').to.be.bignumber.equal(0); expect(numMakers, 'number of makers in pool after removing').to.be.bignumber.equal(0);
}); });
it('Should fail if maker already assigned to another pool tries to join', async () => { it('Should fail if maker already assigned to another pool tries to join', async () => {
@ -337,7 +337,7 @@ blockchainTests('Staking Pool Management', env => {
); );
// check the number of makers in the pool // check the number of makers in the pool
const numMakers = await stakingApiWrapper.stakingContract.getNumberOfMakersInStakingPool.callAsync(poolId); const numMakers = await stakingApiWrapper.stakingContract.numMakersByPoolId.callAsync(poolId);
expect(numMakers, 'number of makers in pool').to.be.bignumber.equal( expect(numMakers, 'number of makers in pool').to.be.bignumber.equal(
stakingConstants.DEFAULT_PARAMS.maximumMakersInPool, stakingConstants.DEFAULT_PARAMS.maximumMakersInPool,
); );

View File

@ -167,7 +167,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
); );
assertNoWETHTransferLogs(receipt.logs); assertNoWETHTransferLogs(receipt.logs);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); expect(poolFees).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
}); });
@ -180,7 +180,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
); );
assertNoWETHTransferLogs(receipt.logs); assertNoWETHTransferLogs(receipt.logs);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(ZERO_AMOUNT); expect(poolFees).to.bignumber.eq(ZERO_AMOUNT);
}); });
@ -198,7 +198,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
await payAsync(); await payAsync();
await payAsync(); await payAsync();
const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2); const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(expectedTotalFees); expect(poolFees).to.bignumber.eq(expectedTotalFees);
}); });
}); });
@ -238,7 +238,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
{ from: exchangeAddress, value: ZERO_AMOUNT }, { from: exchangeAddress, value: ZERO_AMOUNT },
); );
assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID); assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); expect(poolFees).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
}); });
@ -251,7 +251,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
{ from: exchangeAddress, value: ZERO_AMOUNT }, { from: exchangeAddress, value: ZERO_AMOUNT },
); );
assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID); assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(ZERO_AMOUNT); expect(poolFees).to.bignumber.eq(ZERO_AMOUNT);
}); });
@ -269,7 +269,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
await payAsync(); await payAsync();
await payAsync(); await payAsync();
const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2); const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(expectedTotalFees); expect(poolFees).to.bignumber.eq(expectedTotalFees);
}); });
@ -289,7 +289,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
await payAsync(true); await payAsync(true);
await payAsync(false); await payAsync(false);
const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2); const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(expectedTotalFees); expect(poolFees).to.bignumber.eq(expectedTotalFees);
}); });
}); });
@ -309,7 +309,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
await payAsync(makerAddress); await payAsync(makerAddress);
await payAsync(otherMakerAddress); await payAsync(otherMakerAddress);
const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2); const expectedTotalFees = DEFAULT_PROTOCOL_FEE_PAID.times(2);
const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(poolFees).to.bignumber.eq(expectedTotalFees); expect(poolFees).to.bignumber.eq(expectedTotalFees);
}); });
@ -330,8 +330,8 @@ blockchainTests('Protocol Fee Unit Tests', env => {
await payAsync(poolId, makerAddress, fee); await payAsync(poolId, makerAddress, fee);
await payAsync(otherPoolId, otherMakerAddress, otherFee); await payAsync(otherPoolId, otherMakerAddress, otherFee);
const [poolFees, otherPoolFees] = await Promise.all([ const [poolFees, otherPoolFees] = await Promise.all([
testContract.getProtocolFeesThisEpochByPool.callAsync(poolId), testContract.protocolFeesThisEpochByPool.callAsync(poolId),
testContract.getProtocolFeesThisEpochByPool.callAsync(otherPoolId), testContract.protocolFeesThisEpochByPool.callAsync(otherPoolId),
]); ]);
expect(poolFees).to.bignumber.eq(fee); expect(poolFees).to.bignumber.eq(fee);
expect(otherPoolFees).to.bignumber.eq(otherFee); expect(otherPoolFees).to.bignumber.eq(otherFee);
@ -347,7 +347,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
DEFAULT_PROTOCOL_FEE_PAID, DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
); );
const feesCredited = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const feesCredited = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
}); });
@ -359,7 +359,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
DEFAULT_PROTOCOL_FEE_PAID, DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
); );
const feesCredited = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const feesCredited = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
}); });
@ -371,7 +371,7 @@ blockchainTests('Protocol Fee Unit Tests', env => {
DEFAULT_PROTOCOL_FEE_PAID, DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
); );
const feesCredited = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); const feesCredited = await testContract.protocolFeesThisEpochByPool.callAsync(poolId);
expect(feesCredited).to.bignumber.eq(0); expect(feesCredited).to.bignumber.eq(0);
}); });
}); });

View File

@ -119,6 +119,10 @@ blockchainTests.resets('Testing Rewards', env => {
? _expectedEndBalances.membersRewardVaultBalance ? _expectedEndBalances.membersRewardVaultBalance
: ZERO, : ZERO,
}; };
const pool = await stakingApiWrapper.rewardVaultContract.poolById.callAsync(poolId);
const operatorBalance = pool[2];
const membersBalance = pool[3];
const poolBalances = { poolBalance: operatorBalance.plus(membersBalance), operatorBalance, membersBalance };
const finalEndBalancesAsArray = await Promise.all([ const finalEndBalancesAsArray = await Promise.all([
// staker 1 // staker 1
stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync( stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync(
@ -133,11 +137,7 @@ blockchainTests.resets('Testing Rewards', env => {
), ),
stakingApiWrapper.ethVaultContract.balanceOf.callAsync(stakers[1].getOwner()), stakingApiWrapper.ethVaultContract.balanceOf.callAsync(stakers[1].getOwner()),
// operator // operator
stakingApiWrapper.rewardVaultContract.balanceOfOperator.callAsync(poolId),
stakingApiWrapper.ethVaultContract.balanceOf.callAsync(poolOperator), stakingApiWrapper.ethVaultContract.balanceOf.callAsync(poolOperator),
// undivided balance in reward pool
stakingApiWrapper.rewardVaultContract.balanceOf.callAsync(poolId),
stakingApiWrapper.rewardVaultContract.balanceOfMembers.callAsync(poolId),
]); ]);
expect(finalEndBalancesAsArray[0], 'stakerRewardVaultBalance_1').to.be.bignumber.equal( expect(finalEndBalancesAsArray[0], 'stakerRewardVaultBalance_1').to.be.bignumber.equal(
expectedEndBalances.stakerRewardVaultBalance_1, expectedEndBalances.stakerRewardVaultBalance_1,
@ -151,16 +151,17 @@ blockchainTests.resets('Testing Rewards', env => {
expect(finalEndBalancesAsArray[3], 'stakerEthVaultBalance_2').to.be.bignumber.equal( expect(finalEndBalancesAsArray[3], 'stakerEthVaultBalance_2').to.be.bignumber.equal(
expectedEndBalances.stakerEthVaultBalance_2, expectedEndBalances.stakerEthVaultBalance_2,
); );
expect(finalEndBalancesAsArray[4], 'operatorRewardVaultBalance').to.be.bignumber.equal(
expectedEndBalances.operatorRewardVaultBalance, expect(finalEndBalancesAsArray[4], 'operatorEthVaultBalance').to.be.bignumber.equal(
);
expect(finalEndBalancesAsArray[5], 'operatorEthVaultBalance').to.be.bignumber.equal(
expectedEndBalances.operatorEthVaultBalance, expectedEndBalances.operatorEthVaultBalance,
); );
expect(finalEndBalancesAsArray[6], 'poolRewardVaultBalance').to.be.bignumber.equal( expect(poolBalances.operatorBalance, 'operatorRewardVaultBalance').to.be.bignumber.equal(
expectedEndBalances.operatorRewardVaultBalance,
);
expect(poolBalances.poolBalance, 'poolRewardVaultBalance').to.be.bignumber.equal(
expectedEndBalances.poolRewardVaultBalance, expectedEndBalances.poolRewardVaultBalance,
); );
expect(finalEndBalancesAsArray[7], 'membersRewardVaultBalance').to.be.bignumber.equal( expect(poolBalances.membersBalance, 'membersRewardVaultBalance').to.be.bignumber.equal(
expectedEndBalances.membersRewardVaultBalance, expectedEndBalances.membersRewardVaultBalance,
); );
}; };

View File

@ -9,6 +9,7 @@
"generated-artifacts/IStakingEvents.json", "generated-artifacts/IStakingEvents.json",
"generated-artifacts/IStakingPoolRewardVault.json", "generated-artifacts/IStakingPoolRewardVault.json",
"generated-artifacts/IStakingProxy.json", "generated-artifacts/IStakingProxy.json",
"generated-artifacts/IStorage.json",
"generated-artifacts/IStorageInit.json", "generated-artifacts/IStorageInit.json",
"generated-artifacts/IStructs.json", "generated-artifacts/IStructs.json",
"generated-artifacts/IVaultCore.json", "generated-artifacts/IVaultCore.json",
@ -21,7 +22,6 @@
"generated-artifacts/MixinConstants.json", "generated-artifacts/MixinConstants.json",
"generated-artifacts/MixinCumulativeRewards.json", "generated-artifacts/MixinCumulativeRewards.json",
"generated-artifacts/MixinDeploymentConstants.json", "generated-artifacts/MixinDeploymentConstants.json",
"generated-artifacts/MixinEthVault.json",
"generated-artifacts/MixinExchangeFees.json", "generated-artifacts/MixinExchangeFees.json",
"generated-artifacts/MixinExchangeManager.json", "generated-artifacts/MixinExchangeManager.json",
"generated-artifacts/MixinParams.json", "generated-artifacts/MixinParams.json",