diff --git a/contracts/staking/contracts/src/ReadOnlyProxy.sol b/contracts/staking/contracts/src/ReadOnlyProxy.sol index 7613d07ec3..4e3277c908 100644 --- a/contracts/staking/contracts/src/ReadOnlyProxy.sol +++ b/contracts/staking/contracts/src/ReadOnlyProxy.sol @@ -25,7 +25,6 @@ import "./libs/LibProxy.sol"; contract ReadOnlyProxy is MixinStorage { - using LibProxy for address; // solhint-disable payable-fallback diff --git a/contracts/staking/contracts/src/Staking.sol b/contracts/staking/contracts/src/Staking.sol index cdfcc5b171..dc9ad3357b 100644 --- a/contracts/staking/contracts/src/Staking.sol +++ b/contracts/staking/contracts/src/Staking.sol @@ -20,32 +20,15 @@ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; 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 "./stake/MixinStakeBalances.sol"; import "./stake/MixinStake.sol"; import "./staking_pools/MixinStakingPool.sol"; import "./fees/MixinExchangeFees.sol"; -import "./staking_pools/MixinStakingPoolRewards.sol"; contract Staking is IStaking, - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, MixinParams, - MixinZrxVault, - MixinExchangeManager, - MixinStakingPoolRewardVault, - MixinScheduler, - MixinStakeStorage, - MixinStakeBalances, - MixinStakingPoolRewards, MixinStake, MixinStakingPool, MixinExchangeFees diff --git a/contracts/staking/contracts/src/StakingProxy.sol b/contracts/staking/contracts/src/StakingProxy.sol index be36e5a8bd..43c2049ff4 100644 --- a/contracts/staking/contracts/src/StakingProxy.sol +++ b/contracts/staking/contracts/src/StakingProxy.sol @@ -19,23 +19,16 @@ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; -import "@0x/contracts-utils/contracts/src/Ownable.sol"; import "./libs/LibProxy.sol"; import "./immutable/MixinStorage.sol"; import "./interfaces/IStorageInit.sol"; -import "./interfaces/IStaking.sol"; -import "./interfaces/IStakingEvents.sol"; import "./interfaces/IStakingProxy.sol"; contract StakingProxy is - IStakingEvents, IStakingProxy, - MixinConstants, - Ownable, MixinStorage { - using LibProxy for address; /// @dev Constructor. diff --git a/contracts/staking/contracts/src/fees/MixinExchangeFees.sol b/contracts/staking/contracts/src/fees/MixinExchangeFees.sol index 9609d79d27..5b8befac37 100644 --- a/contracts/staking/contracts/src/fees/MixinExchangeFees.sol +++ b/contracts/staking/contracts/src/fees/MixinExchangeFees.sol @@ -24,15 +24,9 @@ import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "../libs/LibStakingRichErrors.sol"; import "../libs/LibFixedMath.sol"; -import "../immutable/MixinStorage.sol"; -import "../immutable/MixinConstants.sol"; import "../immutable/MixinDeploymentConstants.sol"; -import "../interfaces/IStakingEvents.sol"; import "../interfaces/IStructs.sol"; -import "../stake/MixinStakeBalances.sol"; -import "../sys/MixinScheduler.sol"; import "../staking_pools/MixinStakingPool.sol"; -import "../staking_pools/MixinStakingPoolRewardVault.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 /// monopolize a single pool that they all delegate to. contract MixinExchangeFees is - IStakingEvents, - MixinConstants, MixinDeploymentConstants, - Ownable, - MixinStorage, - MixinZrxVault, MixinExchangeManager, - MixinStakingPoolRewardVault, - MixinScheduler, - MixinStakeStorage, - MixinStakeBalances, - MixinStakingPoolRewards, MixinStakingPool { - using LibSafeMath for uint256; /// @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. /// @return Amount of fees. function getTotalProtocolFeesThisEpoch() - public + external view returns (uint256) { - return address(this).balance; - } - - /// @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]; + uint256 wethBalance = IEtherToken(WETH_ADDRESS).balanceOf(address(this)); + return address(this).balance.safeAdd(wethBalance); } /// @dev Withdraws the entire WETH balance of the contract. diff --git a/contracts/staking/contracts/src/fees/MixinExchangeManager.sol b/contracts/staking/contracts/src/fees/MixinExchangeManager.sol index 6249717d70..8aef521db8 100644 --- a/contracts/staking/contracts/src/fees/MixinExchangeManager.sol +++ b/contracts/staking/contracts/src/fees/MixinExchangeManager.sol @@ -21,7 +21,6 @@ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "../libs/LibStakingRichErrors.sol"; import "../interfaces/IStakingEvents.sol"; -import "../immutable/MixinConstants.sol"; import "../immutable/MixinStorage.sol"; @@ -31,14 +30,11 @@ import "../immutable/MixinStorage.sol"; /// then it should be removed. contract MixinExchangeManager is IStakingEvents, - MixinConstants, - Ownable, MixinStorage { - /// @dev Asserts that the call is coming from a valid exchange. modifier onlyExchange() { - if (!isValidExchangeAddress(msg.sender)) { + if (!validExchanges[msg.sender]) { LibRichErrors.rrevert(LibStakingRichErrors.OnlyCallableByExchangeError( msg.sender )); @@ -75,15 +71,4 @@ contract MixinExchangeManager is validExchanges[addr] = false; 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]; - } } diff --git a/contracts/staking/contracts/src/immutable/MixinStorage.sol b/contracts/staking/contracts/src/immutable/MixinStorage.sol index ff0b07d68c..85d5f64182 100644 --- a/contracts/staking/contracts/src/immutable/MixinStorage.sol +++ b/contracts/staking/contracts/src/immutable/MixinStorage.sol @@ -17,6 +17,7 @@ */ pragma solidity ^0.5.9; +pragma experimental ABIEncoderV2; import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetProxy.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; @@ -34,100 +35,99 @@ contract MixinStorage is MixinConstants, Ownable { - // WETH Asset Proxy - IAssetProxy internal wethAssetProxy; + IAssetProxy public wethAssetProxy; // address of staking contract - address internal stakingContract; + address public stakingContract; // address of read-only proxy - address internal readOnlyProxy; + address public readOnlyProxy; // address for read-only proxy to call - address internal readOnlyProxyCallee; + address public readOnlyProxyCallee; // mapping from Owner to Amount of Active Stake // (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 // (access using _loadAndSyncBalance or _loadUnsyncedBalance) - mapping (address => IStructs.StoredBalance) internal inactiveStakeByOwner; + mapping (address => IStructs.StoredBalance) internal _inactiveStakeByOwner; // mapping from Owner to Amount Delegated // (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 // (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 // (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 (address => uint256) internal withdrawableStakeByOwner; + mapping (address => uint256) internal _withdrawableStakeByOwner; // 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 // 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 (bytes32 => uint256) internal numMakersByPoolId; + mapping (bytes32 => uint256) public numMakersByPoolId; // current epoch - uint256 internal currentEpoch = INITIAL_EPOCH; + uint256 public currentEpoch = INITIAL_EPOCH; // current epoch start time - uint256 internal currentEpochStartTimeInSeconds; + uint256 public currentEpochStartTimeInSeconds; // fees collected this epoch - mapping (bytes32 => uint256) internal protocolFeesThisEpochByPool; + mapping (bytes32 => uint256) public protocolFeesThisEpochByPool; // pools that were active in the current epoch - bytes32[] internal activePoolsThisEpoch; + bytes32[] public activePoolsThisEpoch; // 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 (bytes32 => mapping (uint256 => uint256)) internal cumulativeRewardsByPoolReferenceCounter; + mapping (bytes32 => mapping (uint256 => uint256)) internal _cumulativeRewardsByPoolReferenceCounter; // mapping from Pool Id to Epoch - mapping (bytes32 => uint256) internal cumulativeRewardsByPoolLastStored; + mapping (bytes32 => uint256) internal _cumulativeRewardsByPoolLastStored; // registered 0x Exchange contracts - mapping (address => bool) internal validExchanges; + mapping (address => bool) public validExchanges; // ZRX vault (stores staked ZRX) - IZrxVault internal zrxVault; + IZrxVault public zrxVault; // 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) - IStakingPoolRewardVault internal rewardVault; + IStakingPoolRewardVault public rewardVault; // Minimum seconds between epochs. - uint256 internal epochDurationInSeconds; + uint256 public epochDurationInSeconds; // 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. - uint256 internal minimumPoolStake; + uint256 public minimumPoolStake; // Maximum number of maker addresses allowed to be registered to a pool. - uint256 internal maximumMakersInPool; + uint256 public maximumMakersInPool; // Numerator for cobb douglas alpha factor. - uint32 internal cobbDouglasAlphaNumerator; + uint32 public cobbDouglasAlphaNumerator; // Denominator for cobb douglas alpha factor. - uint32 internal cobbDouglasAlphaDenomintor; + uint32 public cobbDouglasAlphaDenomintor; } diff --git a/contracts/staking/contracts/src/interfaces/IStakingPoolRewardVault.sol b/contracts/staking/contracts/src/interfaces/IStakingPoolRewardVault.sol index 1e98e79580..95c4e7d6d2 100644 --- a/contracts/staking/contracts/src/interfaces/IStakingPoolRewardVault.sol +++ b/contracts/staking/contracts/src/interfaces/IStakingPoolRewardVault.sol @@ -17,6 +17,7 @@ */ pragma solidity ^0.5.9; +pragma experimental ABIEncoderV2; /// @dev This vault manages staking pool rewards. @@ -179,28 +180,4 @@ interface IStakingPoolRewardVault { external view 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); } diff --git a/contracts/staking/contracts/src/interfaces/IStorage.sol b/contracts/staking/contracts/src/interfaces/IStorage.sol new file mode 100644 index 0000000000..9d386382d9 --- /dev/null +++ b/contracts/staking/contracts/src/interfaces/IStorage.sol @@ -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); +} diff --git a/contracts/staking/contracts/src/stake/MixinStake.sol b/contracts/staking/contracts/src/stake/MixinStake.sol index 6d68d95e0b..b6994ac811 100644 --- a/contracts/staking/contracts/src/stake/MixinStake.sol +++ b/contracts/staking/contracts/src/stake/MixinStake.sol @@ -20,33 +20,14 @@ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; 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 "../sys/MixinScheduler.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. contract MixinStake is - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, - MixinZrxVault, - MixinStakingPoolRewardVault, - MixinScheduler, - MixinStakeStorage, - MixinStakeBalances, MixinStakingPoolRewards { - using LibSafeMath for uint256; /// @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); // mint stake - _incrementCurrentAndNextBalance(activeStakeByOwner[owner], amount); + _incrementCurrentAndNextBalance(_activeStakeByOwner[owner], amount); // notify emit Stake( @@ -90,10 +71,10 @@ contract MixinStake is } // burn inactive stake - _decrementCurrentAndNextBalance(inactiveStakeByOwner[owner], amount); + _decrementCurrentAndNextBalance(_inactiveStakeByOwner[owner], amount); // update withdrawable field - withdrawableStakeByOwner[owner] = currentWithdrawableStake.safeSub(amount); + _withdrawableStakeByOwner[owner] = currentWithdrawableStake.safeSub(amount); // withdraw equivalent amount of ZRX from vault _withdrawToOwnerFromZrxVault(owner, amount); @@ -156,7 +137,7 @@ contract MixinStake is // update withdrawable field, if necessary if (from.status == IStructs.StakeStatus.INACTIVE) { - withdrawableStakeByOwner[owner] = _computeWithdrawableStake(owner, withdrawableStake); + _withdrawableStakeByOwner[owner] = _computeWithdrawableStake(owner, withdrawableStake); } // notify @@ -192,16 +173,16 @@ contract MixinStake is } // 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 - _incrementNextBalance(delegatedStakeToPoolByOwner[owner][poolId], amount); + _incrementNextBalance(_delegatedStakeToPoolByOwner[owner][poolId], amount); // 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 - IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(delegatedStakeToPoolByOwner[owner][poolId]); + IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(_delegatedStakeToPoolByOwner[owner][poolId]); _syncRewardsForDelegator(poolId, owner, initDelegatedStakeToPoolByOwner, finalDelegatedStakeToPoolByOwner); } @@ -227,16 +208,16 @@ contract MixinStake is } // 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 - _decrementNextBalance(delegatedStakeToPoolByOwner[owner][poolId], amount); + _decrementNextBalance(_delegatedStakeToPoolByOwner[owner][poolId], amount); // 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 - IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(delegatedStakeToPoolByOwner[owner][poolId]); + IStructs.StoredBalance memory finalDelegatedStakeToPoolByOwner = _loadAndSyncBalance(_delegatedStakeToPoolByOwner[owner][poolId]); _syncRewardsForDelegator(poolId, owner, initDelegatedStakeToPoolByOwner, finalDelegatedStakeToPoolByOwner); } @@ -251,11 +232,11 @@ contract MixinStake is { // lookup status if (status == IStructs.StakeStatus.ACTIVE) { - return activeStakeByOwner[owner]; + return _activeStakeByOwner[owner]; } else if (status == IStructs.StakeStatus.INACTIVE) { - return inactiveStakeByOwner[owner]; + return _inactiveStakeByOwner[owner]; } else if (status == IStructs.StakeStatus.DELEGATED) { - return delegatedStakeByOwner[owner]; + return _delegatedStakeByOwner[owner]; } // invalid status diff --git a/contracts/staking/contracts/src/stake/MixinStakeBalances.sol b/contracts/staking/contracts/src/stake/MixinStakeBalances.sol index 6e88d8968d..096ab30784 100644 --- a/contracts/staking/contracts/src/stake/MixinStakeBalances.sol +++ b/contracts/staking/contracts/src/stake/MixinStakeBalances.sol @@ -21,9 +21,6 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "../interfaces/IStructs.sol"; -import "../immutable/MixinConstants.sol"; -import "../immutable/MixinStorage.sol"; -import "../sys/MixinScheduler.sol"; import "./MixinZrxVault.sol"; import "./MixinStakeStorage.sol"; @@ -31,22 +28,16 @@ import "./MixinStakeStorage.sol"; /// @dev This mixin contains logic for querying stake balances. /// **** Read MixinStake before continuing **** contract MixinStakeBalances is - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, MixinZrxVault, - MixinScheduler, MixinStakeStorage { - using LibSafeMath for uint256; /// @dev Returns the total stake for a given owner. /// @param owner of stake. /// @return Total active stake for owner. function getTotalStake(address owner) - public + external view returns (uint256) { @@ -57,11 +48,11 @@ contract MixinStakeBalances is /// @param owner of stake. /// @return Active stake for owner. function getActiveStake(address owner) - public + external view returns (IStructs.StakeBalance memory balance) { - IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(activeStakeByOwner[owner]); + IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_activeStakeByOwner[owner]); return IStructs.StakeBalance({ currentEpochBalance: storedBalance.currentEpochBalance, nextEpochBalance: storedBalance.nextEpochBalance @@ -72,11 +63,26 @@ contract MixinStakeBalances is /// @param owner of stake. /// @return Inactive stake for owner. function getInactiveStake(address owner) - public + external view 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({ currentEpochBalance: storedBalance.currentEpochBalance, nextEpochBalance: storedBalance.nextEpochBalance @@ -91,22 +97,7 @@ contract MixinStakeBalances is view returns (uint256) { - 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 - }); + return _computeWithdrawableStake(owner, _withdrawableStakeByOwner[owner]); } /// @dev Returns the stake delegated to a specific staking pool, by a given owner. @@ -118,7 +109,7 @@ contract MixinStakeBalances is view returns (IStructs.StakeBalance memory balance) { - IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(delegatedStakeToPoolByOwner[owner][poolId]); + IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_delegatedStakeToPoolByOwner[owner][poolId]); return IStructs.StakeBalance({ currentEpochBalance: storedBalance.currentEpochBalance, nextEpochBalance: storedBalance.nextEpochBalance @@ -133,7 +124,7 @@ contract MixinStakeBalances is view returns (IStructs.StakeBalance memory balance) { - IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(delegatedStakeByPoolId[poolId]); + IStructs.StoredBalance memory storedBalance = _loadAndSyncBalance(_delegatedStakeByPoolId[poolId]); return IStructs.StakeBalance({ currentEpochBalance: storedBalance.currentEpochBalance, nextEpochBalance: storedBalance.nextEpochBalance @@ -151,7 +142,7 @@ contract MixinStakeBalances is { // 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`. - IStructs.StoredBalance memory storedBalance = _loadUnsyncedBalance(inactiveStakeByOwner[owner]); + IStructs.StoredBalance memory storedBalance = _loadUnsyncedBalance(_inactiveStakeByOwner[owner]); if (storedBalance.currentEpoch == currentEpoch) { return LibSafeMath.min256(storedBalance.nextEpochBalance, lastStoredWithdrawableStake); } else if (uint256(storedBalance.currentEpoch).safeAdd(1) == currentEpoch) { diff --git a/contracts/staking/contracts/src/stake/MixinStakeStorage.sol b/contracts/staking/contracts/src/stake/MixinStakeStorage.sol index ae2a557e5d..0c202aeabf 100644 --- a/contracts/staking/contracts/src/stake/MixinStakeStorage.sol +++ b/contracts/staking/contracts/src/stake/MixinStakeStorage.sol @@ -21,21 +21,13 @@ pragma solidity ^0.5.9; import "../libs/LibSafeDowncast.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "../interfaces/IStructs.sol"; -import "../immutable/MixinConstants.sol"; -import "../immutable/MixinStorage.sol"; import "../sys/MixinScheduler.sol"; -import "./MixinZrxVault.sol"; /// @dev This mixin contains logic for managing stake storage. contract MixinStakeStorage is - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, MixinScheduler { - using LibSafeMath for uint256; using LibSafeDowncast for uint256; @@ -93,9 +85,9 @@ contract MixinStakeStorage is // load from storage balance = balancePtr; // sync - uint256 currentEpoch = getCurrentEpoch(); - if (currentEpoch > balance.currentEpoch) { - balance.currentEpoch = currentEpoch.downcastToUint32(); + uint256 currentEpoch_ = currentEpoch; + if (currentEpoch_ > balance.currentEpoch) { + balance.currentEpoch = currentEpoch_.downcastToUint32(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; diff --git a/contracts/staking/contracts/src/stake/MixinZrxVault.sol b/contracts/staking/contracts/src/stake/MixinZrxVault.sol index 2c11efe183..3b4f61e0be 100644 --- a/contracts/staking/contracts/src/stake/MixinZrxVault.sol +++ b/contracts/staking/contracts/src/stake/MixinZrxVault.sol @@ -25,11 +25,8 @@ import "../immutable/MixinStorage.sol"; /// @dev This mixin contains logic for managing and interfacing with the Zrx Vault. /// (see vaults/ZrxVault.sol). contract MixinZrxVault is - MixinConstants, - Ownable, MixinStorage { - /// @dev Set the Zrx Vault. /// @param zrxVaultAddress Address of the Zrx Vault. function setZrxVault(address zrxVaultAddress) @@ -39,16 +36,6 @@ contract MixinZrxVault is 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. /// @param owner of Zrx Tokens /// @param amount of tokens to deposit. diff --git a/contracts/staking/contracts/src/staking_pools/MixinCumulativeRewards.sol b/contracts/staking/contracts/src/staking_pools/MixinCumulativeRewards.sol index 8e19176efc..12b38f0f26 100644 --- a/contracts/staking/contracts/src/staking_pools/MixinCumulativeRewards.sol +++ b/contracts/staking/contracts/src/staking_pools/MixinCumulativeRewards.sol @@ -21,21 +21,12 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibFractions.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; -import "../immutable/MixinStorage.sol"; -import "../immutable/MixinConstants.sol"; import "../stake/MixinStakeBalances.sol"; import "./MixinStakingPoolRewardVault.sol"; contract MixinCumulativeRewards is - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, - MixinZrxVault, MixinStakingPoolRewardVault, - MixinScheduler, - MixinStakeStorage, MixinStakeBalances { using LibSafeMath for uint256; @@ -45,7 +36,6 @@ contract MixinCumulativeRewards is function _initializeCumulativeRewards(bytes32 poolId) internal { - uint256 currentEpoch = getCurrentEpoch(); // sets the default cumulative reward _forceSetCumulativeReward( poolId, @@ -78,9 +68,9 @@ contract MixinCumulativeRewards is returns (bool) { return ( - _isCumulativeRewardSet(cumulativeRewardsByPool[poolId][epoch]) && // is there a value to unset - cumulativeRewardsByPoolReferenceCounter[poolId][epoch] == 0 && // no references to this CR - cumulativeRewardsByPoolLastStored[poolId] > epoch // this is *not* the most recent CR + _isCumulativeRewardSet(_cumulativeRewardsByPool[poolId][epoch]) && // is there a value to unset + _cumulativeRewardsByPoolReferenceCounter[poolId][epoch] == 0 && // no references to this CR + _cumulativeRewardsByPoolLastStored[poolId] > epoch // this is *not* the most recent CR ); } @@ -95,7 +85,7 @@ contract MixinCumulativeRewards is ) internal { - if (_isCumulativeRewardSet(cumulativeRewardsByPool[poolId][epoch])) { + if (_isCumulativeRewardSet(_cumulativeRewardsByPool[poolId][epoch])) { // do nothing; we don't want to override the current value return; } @@ -114,7 +104,7 @@ contract MixinCumulativeRewards is ) internal { - cumulativeRewardsByPool[poolId][epoch] = value; + _cumulativeRewardsByPool[poolId][epoch] = value; _trySetMostRecentCumulativeRewardEpoch(poolId, epoch); } @@ -136,7 +126,7 @@ contract MixinCumulativeRewards is function _forceUnsetCumulativeReward(bytes32 poolId, uint256 epoch) 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. @@ -145,11 +135,11 @@ contract MixinCumulativeRewards is returns (IStructs.CumulativeRewardInfo memory) { // 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 return IStructs.CumulativeRewardInfo({ - cumulativeReward: cumulativeRewardsByPool[poolId][cumulativeRewardsLastStored], + cumulativeReward: _cumulativeRewardsByPool[poolId][cumulativeRewardsLastStored], cumulativeRewardEpoch: cumulativeRewardsLastStored }); } @@ -163,7 +153,7 @@ contract MixinCumulativeRewards is internal { // check if we should do any work - uint256 currentMostRecentEpoch = cumulativeRewardsByPoolLastStored[poolId]; + uint256 currentMostRecentEpoch = _cumulativeRewardsByPoolLastStored[poolId]; if (epoch == currentMostRecentEpoch) { return; } @@ -189,7 +179,7 @@ contract MixinCumulativeRewards is { // sanity check that we're not trying to go back in time assert(newMostRecentEpoch >= currentMostRecentEpoch); - cumulativeRewardsByPoolLastStored[poolId] = newMostRecentEpoch; + _cumulativeRewardsByPoolLastStored[poolId] = newMostRecentEpoch; // unset the previous most recent reward, if it is no longer needed _tryUnsetCumulativeReward(poolId, currentMostRecentEpoch); @@ -234,7 +224,7 @@ contract MixinCumulativeRewards is internal { // 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) _trySetCumulativeReward( @@ -254,8 +244,8 @@ contract MixinCumulativeRewards is internal { // remove dependency by decreasing reference counter - uint256 newReferenceCounter = cumulativeRewardsByPoolReferenceCounter[poolId][epoch].safeSub(1); - cumulativeRewardsByPoolReferenceCounter[poolId][epoch] = newReferenceCounter; + uint256 newReferenceCounter = _cumulativeRewardsByPoolReferenceCounter[poolId][epoch].safeSub(1); + _cumulativeRewardsByPoolReferenceCounter[poolId][epoch] = newReferenceCounter; // clear cumulative reward from state, if it is no longer needed _tryUnsetCumulativeReward(poolId, epoch); @@ -295,7 +285,7 @@ contract MixinCumulativeRewards is } // sanity check begin reward - IStructs.Fraction memory beginReward = cumulativeRewardsByPool[poolId][beginEpoch]; + IStructs.Fraction memory beginReward = _cumulativeRewardsByPool[poolId][beginEpoch]; if (!_isCumulativeRewardSet(beginReward)) { LibRichErrors.rrevert( LibStakingRichErrors.CumulativeRewardIntervalError( @@ -308,7 +298,7 @@ contract MixinCumulativeRewards is } // sanity check end reward - IStructs.Fraction memory endReward = cumulativeRewardsByPool[poolId][endEpoch]; + IStructs.Fraction memory endReward = _cumulativeRewardsByPool[poolId][endEpoch]; if (!_isCumulativeRewardSet(endReward)) { LibRichErrors.rrevert( LibStakingRichErrors.CumulativeRewardIntervalError( diff --git a/contracts/staking/contracts/src/staking_pools/MixinEthVault.sol b/contracts/staking/contracts/src/staking_pools/MixinEthVault.sol deleted file mode 100644 index 5159a11834..0000000000 --- a/contracts/staking/contracts/src/staking_pools/MixinEthVault.sol +++ /dev/null @@ -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); - } -} diff --git a/contracts/staking/contracts/src/staking_pools/MixinStakingPool.sol b/contracts/staking/contracts/src/staking_pools/MixinStakingPool.sol index a749870817..e96fd8551c 100644 --- a/contracts/staking/contracts/src/staking_pools/MixinStakingPool.sol +++ b/contracts/staking/contracts/src/staking_pools/MixinStakingPool.sol @@ -23,9 +23,6 @@ import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "../libs/LibStakingRichErrors.sol"; import "../interfaces/IStructs.sol"; -import "../interfaces/IStakingEvents.sol"; -import "../immutable/MixinConstants.sol"; -import "../immutable/MixinStorage.sol"; import "./MixinStakingPoolRewards.sol"; @@ -53,18 +50,8 @@ import "./MixinStakingPoolRewards.sol"; /// 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. contract MixinStakingPool is - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, - MixinZrxVault, - MixinStakingPoolRewardVault, - MixinScheduler, - MixinStakeStorage, - MixinStakeBalances, MixinStakingPoolRewards { - using LibSafeMath for uint256; /// @dev Create a new staking pool. The sender will be the operator of this pool. @@ -120,9 +107,9 @@ contract MixinStakingPool is return poolId; } - function joinStakingPoolAsMaker( - bytes32 poolId - ) + /// @dev Allows caller to join a staking pool if already assigned. + /// @param poolId Unique id of pool. + function joinStakingPoolAsMaker(bytes32 poolId) external { // Is the maker already in a pool? @@ -179,7 +166,7 @@ contract MixinStakingPool is } // Is the pool already full? - if (getNumberOfMakersInStakingPool(poolId) == maximumMakersInPool) { + if (numMakersByPoolId[poolId] == maximumMakersInPool) { LibRichErrors.rrevert(LibStakingRichErrors.MakerPoolAssignmentError( LibStakingRichErrors.MakerPoolAssignmentErrorCodes.PoolIsFull, makerAddress, @@ -264,27 +251,6 @@ contract MixinStakingPool is 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. /// @param poolId Unique id of pool. /// @return Next pool id after input pool. diff --git a/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewardVault.sol b/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewardVault.sol index fe52bd1495..d13c99d17c 100644 --- a/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewardVault.sol +++ b/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewardVault.sol @@ -30,11 +30,8 @@ import "../immutable/MixinStorage.sol"; /// from within this contract. contract MixinStakingPoolRewardVault is IStakingEvents, - MixinConstants, - Ownable, MixinStorage { - /// @dev Asserts that the sender is the operator of the input pool. /// @param poolId Pool sender must be operator of. modifier onlyStakingPoolOperator(bytes32 poolId) { @@ -80,23 +77,13 @@ contract MixinStakingPoolRewardVault is 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). /// 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. /// @param poolId Unique Id of pool. /// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator. function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare) - public + external onlyStakingPoolOperator(poolId) { rewardVault.decreaseOperatorShare(poolId, newOperatorShare); diff --git a/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewards.sol b/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewards.sol index 6fae9bf65c..081b1309ac 100644 --- a/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewards.sol +++ b/contracts/staking/contracts/src/staking_pools/MixinStakingPoolRewards.sol @@ -21,26 +21,12 @@ pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibFractions.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"; contract MixinStakingPoolRewards is - IStakingEvents, - MixinConstants, - Ownable, - MixinStorage, - MixinZrxVault, - MixinStakingPoolRewardVault, - MixinScheduler, - MixinStakeStorage, - MixinStakeBalances, MixinCumulativeRewards { - using LibSafeMath for uint256; /// @dev Computes the reward balance in ETH of a specific member of a pool. @@ -54,8 +40,8 @@ contract MixinStakingPoolRewards is { return _computeRewardBalanceOfDelegator( poolId, - _loadUnsyncedBalance(delegatedStakeToPoolByOwner[member][poolId]), - getCurrentEpoch() + _loadUnsyncedBalance(_delegatedStakeToPoolByOwner[member][poolId]), + currentEpoch ); } @@ -73,8 +59,6 @@ contract MixinStakingPoolRewards is ) internal { - uint256 currentEpoch = getCurrentEpoch(); - // 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. _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 reward to record for delegators. /// @param amountOfDelegatedStake the amount of delegated stake that will split this reward. @@ -113,12 +97,12 @@ contract MixinStakingPoolRewards is internal { // 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; // this is the most up-to-date cumulative rewards for this pool. - uint256 cumulativeRewardsLastStored = cumulativeRewardsByPoolLastStored[poolId]; - IStructs.Fraction memory mostRecentCumulativeRewards = cumulativeRewardsByPoolPtr[cumulativeRewardsLastStored]; + uint256 cumulativeRewardsLastStored = _cumulativeRewardsByPoolLastStored[poolId]; + IStructs.Fraction memory mostRecentCumulativeRewards = _cumulativeRewardsByPoolPtr[cumulativeRewardsLastStored]; // compute new cumulative reward (uint256 numerator, uint256 denominator) = LibFractions.addFractions( @@ -204,12 +188,12 @@ contract MixinStakingPoolRewards is // compute the reward accumulated by the `next` balance; // 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). - uint256 rewardsAccumulatedAfterLastStoredEpoch = (cumulativeRewardsByPoolLastStored[poolId] > unsyncedDelegatedStakeToPoolByOwner.currentEpoch) + uint256 rewardsAccumulatedAfterLastStoredEpoch = (_cumulativeRewardsByPoolLastStored[poolId] > unsyncedDelegatedStakeToPoolByOwner.currentEpoch) ? _computeMemberRewardOverInterval( poolId, unsyncedDelegatedStakeToPoolByOwner.nextEpochBalance, unsyncedDelegatedStakeToPoolByOwner.currentEpoch, - cumulativeRewardsByPoolLastStored[poolId] + _cumulativeRewardsByPoolLastStored[poolId] ) : 0; @@ -222,17 +206,17 @@ contract MixinStakingPoolRewards is /// 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. /// @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. function _setCumulativeRewardDependenciesForDelegator( bytes32 poolId, - IStructs.StoredBalance memory delegatedStakeToPoolByOwner, + IStructs.StoredBalance memory _delegatedStakeToPoolByOwner, bool isDependent ) private { // if this delegator is not yet initialized then there's no dependency to unset. - if (!isDependent && !delegatedStakeToPoolByOwner.isInitialized) { + if (!isDependent && !_delegatedStakeToPoolByOwner.isInitialized) { return; } @@ -240,20 +224,20 @@ contract MixinStakingPoolRewards is IStructs.CumulativeRewardInfo memory mostRecentCumulativeRewardInfo = _getMostRecentCumulativeRewardInfo(poolId); // record dependency on `lastEpoch` - if (delegatedStakeToPoolByOwner.currentEpoch > 0 && delegatedStakeToPoolByOwner.currentEpochBalance != 0) { + if (_delegatedStakeToPoolByOwner.currentEpoch > 0 && _delegatedStakeToPoolByOwner.currentEpochBalance != 0) { _addOrRemoveDependencyOnCumulativeReward( poolId, - uint256(delegatedStakeToPoolByOwner.currentEpoch).safeSub(1), + uint256(_delegatedStakeToPoolByOwner.currentEpoch).safeSub(1), mostRecentCumulativeRewardInfo, isDependent ); } // record dependency on current epoch. - if (delegatedStakeToPoolByOwner.currentEpochBalance != 0 || delegatedStakeToPoolByOwner.nextEpochBalance != 0) { + if (_delegatedStakeToPoolByOwner.currentEpochBalance != 0 || _delegatedStakeToPoolByOwner.nextEpochBalance != 0) { _addOrRemoveDependencyOnCumulativeReward( poolId, - delegatedStakeToPoolByOwner.currentEpoch, + _delegatedStakeToPoolByOwner.currentEpoch, mostRecentCumulativeRewardInfo, isDependent ); diff --git a/contracts/staking/contracts/src/sys/MixinParams.sol b/contracts/staking/contracts/src/sys/MixinParams.sol index 3a4a373b25..cd6fba21de 100644 --- a/contracts/staking/contracts/src/sys/MixinParams.sol +++ b/contracts/staking/contracts/src/sys/MixinParams.sol @@ -19,8 +19,6 @@ pragma solidity ^0.5.9; 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 "../interfaces/IStakingEvents.sol"; import "../libs/LibStakingRichErrors.sol"; @@ -28,11 +26,8 @@ import "../libs/LibStakingRichErrors.sol"; contract MixinParams is IStakingEvents, - MixinConstants, - Ownable, MixinStorage { - /// @dev Set all configurable parameters at once. /// @param _epochDurationInSeconds Minimum seconds between epochs. /// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm. diff --git a/contracts/staking/contracts/src/sys/MixinScheduler.sol b/contracts/staking/contracts/src/sys/MixinScheduler.sol index 481a965996..4145d43cb0 100644 --- a/contracts/staking/contracts/src/sys/MixinScheduler.sol +++ b/contracts/staking/contracts/src/sys/MixinScheduler.sol @@ -21,9 +21,7 @@ pragma solidity ^0.5.9; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/LibSafeMath.sol"; import "../libs/LibStakingRichErrors.sol"; -import "../immutable/MixinConstants.sol"; import "../immutable/MixinStorage.sol"; -import "../interfaces/IStructs.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. contract MixinScheduler is IStakingEvents, - MixinConstants, - Ownable, MixinStorage { - 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. /// The next epoch can begin once this time is reached. /// Epoch period = [startTimeInSeconds..endTimeInSeconds) @@ -72,7 +46,7 @@ contract MixinScheduler is view returns (uint256) { - return getCurrentEpochStartTimeInSeconds().safeAdd(epochDurationInSeconds); + return currentEpochStartTimeInSeconds.safeAdd(epochDurationInSeconds); } /// @dev Assert scheduler state before initializing it. diff --git a/contracts/staking/contracts/src/vaults/EthVault.sol b/contracts/staking/contracts/src/vaults/EthVault.sol index 9625ed3ba9..7c4a755c2b 100644 --- a/contracts/staking/contracts/src/vaults/EthVault.sol +++ b/contracts/staking/contracts/src/vaults/EthVault.sol @@ -25,16 +25,13 @@ import "./MixinVaultCore.sol"; /// @dev This vault manages ETH. contract EthVault is - Authorizable, IEthVault, - IVaultCore, MixinVaultCore { - using LibSafeMath for uint256; // mapping from Owner to ETH balance - mapping (address => uint256) internal balances; + mapping (address => uint256) internal _balances; /// @dev Constructor. constructor() @@ -51,7 +48,7 @@ contract EthVault is { // update balance uint256 amount = msg.value; - balances[owner] = balances[owner].safeAdd(msg.value); + _balances[owner] = _balances[owner].safeAdd(msg.value); // notify emit EthDepositedIntoVault(msg.sender, owner, amount); @@ -74,7 +71,7 @@ contract EthVault is { // get total balance address payable owner = msg.sender; - totalBalance = balances[owner]; + totalBalance = _balances[owner]; // withdraw ETH to owner _withdrawFrom(owner, totalBalance); @@ -88,7 +85,7 @@ contract EthVault is view returns (uint256) { - return balances[owner]; + return _balances[owner]; } /// @dev Withdraw an `amount` of ETH to `owner` from the vault. @@ -100,7 +97,7 @@ contract EthVault is // update balance // note that this call will revert if trying to withdraw more // than the current balance - balances[owner] = balances[owner].safeSub(amount); + _balances[owner] = _balances[owner].safeSub(amount); // notify emit EthWithdrawnFromVault(msg.sender, owner, amount); diff --git a/contracts/staking/contracts/src/vaults/MixinVaultCore.sol b/contracts/staking/contracts/src/vaults/MixinVaultCore.sol index 3c4a5d6dfa..b916cc90a1 100644 --- a/contracts/staking/contracts/src/vaults/MixinVaultCore.sol +++ b/contracts/staking/contracts/src/vaults/MixinVaultCore.sol @@ -18,7 +18,7 @@ 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 "../libs/LibStakingRichErrors.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 /// status in the staking contract. contract MixinVaultCore is - Authorizable, + Ownable, IVaultCore { - // Address of staking contract address payable internal stakingContractAddress; diff --git a/contracts/staking/contracts/src/vaults/StakingPoolRewardVault.sol b/contracts/staking/contracts/src/vaults/StakingPoolRewardVault.sol index b3646bcd59..a5b005fb93 100644 --- a/contracts/staking/contracts/src/vaults/StakingPoolRewardVault.sol +++ b/contracts/staking/contracts/src/vaults/StakingPoolRewardVault.sol @@ -40,21 +40,18 @@ import "../immutable/MixinConstants.sol"; /// When in Catastrophic Failure Mode, the Staking contract can still /// perform withdrawals on behalf of its users. contract StakingPoolRewardVault is - Authorizable, IStakingPoolRewardVault, - IVaultCore, MixinConstants, MixinVaultCore { - using LibSafeMath for uint256; using LibSafeDowncast for uint256; // mapping from poolId to Pool metadata - mapping (bytes32 => Pool) internal poolById; + mapping (bytes32 => Pool) public poolById; // address of ether vault - IEthVault internal ethVault; + IEthVault internal _ethVault; /// @dev Fallback function. This contract is payable, but only by the staking contract. function () @@ -73,7 +70,7 @@ contract StakingPoolRewardVault is external onlyOwner { - ethVault = IEthVault(ethVaultAddress); + _ethVault = IEthVault(ethVaultAddress); emit EthVaultChanged(ethVaultAddress); } @@ -256,39 +253,6 @@ contract StakingPoolRewardVault is 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 /// pool operator and members of the pool based on the pool operator's share. /// @param pool Pool struct with the balances to increment. @@ -328,14 +292,14 @@ contract StakingPoolRewardVault is private { // sanity check on eth vault - IEthVault _ethVault = ethVault; - if (address(_ethVault) == address(0)) { + IEthVault ethVault_ = _ethVault; + if (address(ethVault_) == address(0)) { LibRichErrors.rrevert( LibStakingRichErrors.EthVaultNotSetError() ); } // perform xfer - _ethVault.depositFor.value(amount)(from); + ethVault_.depositFor.value(amount)(from); } } diff --git a/contracts/staking/contracts/src/vaults/ZrxVault.sol b/contracts/staking/contracts/src/vaults/ZrxVault.sol index 05e9b63329..09a7994031 100644 --- a/contracts/staking/contracts/src/vaults/ZrxVault.sol +++ b/contracts/staking/contracts/src/vaults/ZrxVault.sol @@ -34,40 +34,37 @@ import "./MixinVaultCore.sol"; /// failure mode, it cannot be returned to normal mode; this prevents /// corruption of related state in the staking contract. contract ZrxVault is - Authorizable, - IVaultCore, IZrxVault, MixinVaultCore { - using LibSafeMath for uint256; // mapping from Owner to ZRX balance - mapping (address => uint256) internal balances; + mapping (address => uint256) internal _balances; // Zrx Asset Proxy - IAssetProxy internal zrxAssetProxy; + IAssetProxy public zrxAssetProxy; // Zrx Token - IERC20Token internal zrxToken; + IERC20Token internal _zrxToken; // Asset data for the ERC20 Proxy - bytes internal zrxAssetData; + bytes internal _zrxAssetData; /// @dev Constructor. /// @param zrxProxyAddress Address of the 0x Zrx Proxy. - /// @param zrxTokenAddress Address of the Zrx Token. + /// @param _zrxTokenAddress Address of the Zrx Token. constructor( address zrxProxyAddress, - address zrxTokenAddress + address _zrxTokenAddress ) public { zrxAssetProxy = IAssetProxy(zrxProxyAddress); - zrxToken = IERC20Token(zrxTokenAddress); - zrxAssetData = abi.encodeWithSelector( + _zrxToken = IERC20Token(_zrxTokenAddress); + _zrxAssetData = abi.encodeWithSelector( IAssetData(address(0)).ERC20Token.selector, - zrxTokenAddress + _zrxTokenAddress ); } @@ -95,14 +92,14 @@ contract ZrxVault is onlyNotInCatastrophicFailure { // update balance - balances[owner] = balances[owner].safeAdd(amount); + _balances[owner] = _balances[owner].safeAdd(amount); // notify emit ZrxDepositedIntoVault(msg.sender, owner, amount); // deposit ZRX from owner zrxAssetProxy.transferFrom( - zrxAssetData, + _zrxAssetData, owner, address(this), amount @@ -131,7 +128,7 @@ contract ZrxVault is returns (uint256) { // get total balance - uint256 totalBalance = balances[owner]; + uint256 totalBalance = _balances[owner]; // withdraw ZRX to owner _withdrawFrom(owner, totalBalance); @@ -145,7 +142,7 @@ contract ZrxVault is view returns (uint256) { - return balances[owner]; + return _balances[owner]; } /// @dev Withdraw an `amount` of Zrx Tokens to `owner` from the vault. @@ -157,13 +154,13 @@ contract ZrxVault is // update balance // note that this call will revert if trying to withdraw more // than the current balance - balances[owner] = balances[owner].safeSub(amount); + _balances[owner] = _balances[owner].safeSub(amount); // notify emit ZrxWithdrawnFromVault(msg.sender, owner, amount); // withdraw ZRX to owner - zrxToken.transfer( + _zrxToken.transfer( owner, amount ); diff --git a/contracts/staking/contracts/test/TestStorageLayout.sol b/contracts/staking/contracts/test/TestStorageLayout.sol index 8b2d17c40f..5603773c02 100644 --- a/contracts/staking/contracts/test/TestStorageLayout.sol +++ b/contracts/staking/contracts/test/TestStorageLayout.sol @@ -55,22 +55,22 @@ contract TestStorageLayout is if sub(stakingContract_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(activeStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } + if sub(_activeStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(inactiveStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } + if sub(_inactiveStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(delegatedStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } + if sub(_delegatedStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(delegatedStakeToPoolByOwner_slot, slot) { revertIncorrectStorageSlot() } + if sub(_delegatedStakeToPoolByOwner_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(delegatedStakeByPoolId_slot, slot) { revertIncorrectStorageSlot() } + if sub(_delegatedStakeByPoolId_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(withdrawableStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } + if sub(_withdrawableStakeByOwner_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) if sub(nextPoolId_slot, slot) { revertIncorrectStorageSlot() } @@ -94,13 +94,13 @@ contract TestStorageLayout is if sub(activePoolsThisEpoch_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(cumulativeRewardsByPool_slot, slot) { revertIncorrectStorageSlot() } + if sub(_cumulativeRewardsByPool_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(cumulativeRewardsByPoolReferenceCounter_slot, slot) { revertIncorrectStorageSlot() } + if sub(_cumulativeRewardsByPoolReferenceCounter_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) - if sub(cumulativeRewardsByPoolLastStored_slot, slot) { revertIncorrectStorageSlot() } + if sub(_cumulativeRewardsByPoolLastStored_slot, slot) { revertIncorrectStorageSlot() } slot := add(slot, 1) if sub(validExchanges_slot, slot) { revertIncorrectStorageSlot() } diff --git a/contracts/staking/package.json b/contracts/staking/package.json index 490419276e..ce94e2a83f 100644 --- a/contracts/staking/package.json +++ b/contracts/staking/package.json @@ -37,7 +37,7 @@ }, "config": { "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": { "type": "git", diff --git a/contracts/staking/src/artifacts.ts b/contracts/staking/src/artifacts.ts index 1c0bbe1114..c0661b3135 100644 --- a/contracts/staking/src/artifacts.ts +++ b/contracts/staking/src/artifacts.ts @@ -11,6 +11,7 @@ import * as IStaking from '../generated-artifacts/IStaking.json'; import * as IStakingEvents from '../generated-artifacts/IStakingEvents.json'; import * as IStakingPoolRewardVault from '../generated-artifacts/IStakingPoolRewardVault.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 IStructs from '../generated-artifacts/IStructs.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 MixinCumulativeRewards from '../generated-artifacts/MixinCumulativeRewards.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 MixinExchangeManager from '../generated-artifacts/MixinExchangeManager.json'; import * as MixinParams from '../generated-artifacts/MixinParams.json'; @@ -68,6 +68,7 @@ export const artifacts = { IStakingEvents: IStakingEvents as ContractArtifact, IStakingPoolRewardVault: IStakingPoolRewardVault as ContractArtifact, IStakingProxy: IStakingProxy as ContractArtifact, + IStorage: IStorage as ContractArtifact, IStorageInit: IStorageInit as ContractArtifact, IStructs: IStructs as ContractArtifact, IVaultCore: IVaultCore as ContractArtifact, @@ -82,7 +83,6 @@ export const artifacts = { MixinStakeStorage: MixinStakeStorage as ContractArtifact, MixinZrxVault: MixinZrxVault as ContractArtifact, MixinCumulativeRewards: MixinCumulativeRewards as ContractArtifact, - MixinEthVault: MixinEthVault as ContractArtifact, MixinStakingPool: MixinStakingPool as ContractArtifact, MixinStakingPoolRewardVault: MixinStakingPoolRewardVault as ContractArtifact, MixinStakingPoolRewards: MixinStakingPoolRewards as ContractArtifact, diff --git a/contracts/staking/src/wrappers.ts b/contracts/staking/src/wrappers.ts index 19693381bc..7cb426c8d6 100644 --- a/contracts/staking/src/wrappers.ts +++ b/contracts/staking/src/wrappers.ts @@ -9,6 +9,7 @@ export * from '../generated-wrappers/i_staking'; export * from '../generated-wrappers/i_staking_events'; export * from '../generated-wrappers/i_staking_pool_reward_vault'; 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_structs'; 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_cumulative_rewards'; 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_manager'; export * from '../generated-wrappers/mixin_params'; diff --git a/contracts/staking/test/actors/finalizer_actor.ts b/contracts/staking/test/actors/finalizer_actor.ts index 296d452674..1965a117f6 100644 --- a/contracts/staking/test/actors/finalizer_actor.ts +++ b/contracts/staking/test/actors/finalizer_actor.ts @@ -164,7 +164,8 @@ export class FinalizerActor extends BaseActor { private async _getOperatorShareByPoolIdAsync(poolIds: string[]): Promise { const operatorShareByPoolId: OperatorShareByPoolId = {}; 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; } return operatorShareByPoolId; @@ -179,15 +180,13 @@ export class FinalizerActor extends BaseActor { } private async _getRewardVaultBalanceAsync(poolId: string): Promise { - const balances = await Promise.all([ - this._stakingApiWrapper.rewardVaultContract.balanceOf.callAsync(poolId), - this._stakingApiWrapper.rewardVaultContract.balanceOfOperator.callAsync(poolId), - this._stakingApiWrapper.rewardVaultContract.balanceOfMembers.callAsync(poolId), - ]); + const pool = await this._stakingApiWrapper.rewardVaultContract.poolById.callAsync(poolId); + const operatorBalance = pool[2]; + const membersBalance = pool[3]; return { - poolBalance: balances[0], - operatorBalance: balances[1], - membersBalance: balances[2], + poolBalance: operatorBalance.plus(membersBalance), + operatorBalance, + membersBalance, }; } } diff --git a/contracts/staking/test/actors/pool_operator_actor.ts b/contracts/staking/test/actors/pool_operator_actor.ts index 2aa711e3ad..977369ea8b 100644 --- a/contracts/staking/test/actors/pool_operator_actor.ts +++ b/contracts/staking/test/actors/pool_operator_actor.ts @@ -1,5 +1,5 @@ import { expect } from '@0x/contracts-test-utils'; -import { RevertError } from '@0x/utils'; +import { BigNumber, RevertError } from '@0x/utils'; import * as _ from 'lodash'; import { constants as stakingConstants } from '../utils/constants'; @@ -13,7 +13,7 @@ export class PoolOperatorActor extends BaseActor { revertError?: RevertError, ): Promise { // query next pool id - const nextPoolId = await this._stakingApiWrapper.stakingContract.getNextStakingPoolId.callAsync(); + const nextPoolId = await this._stakingApiWrapper.stakingContract.nextPoolId.callAsync(); // create pool const poolIdPromise = this._stakingApiWrapper.utils.createStakingPoolAsync( this._owner, @@ -35,7 +35,7 @@ export class PoolOperatorActor extends BaseActor { ); expect(poolIdOfMaker, 'pool id of maker').to.be.equal(poolId); // 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, ); expect(numMakersAfterRemoving, 'number of makers in pool').to.be.bignumber.equal(1); @@ -103,9 +103,8 @@ export class PoolOperatorActor extends BaseActor { } await txReceiptPromise; // Check operator share - const decreasedOperatorShare = await this._stakingApiWrapper.rewardVaultContract.getOperatorShare.callAsync( - poolId, - ); + const pool = await this._stakingApiWrapper.rewardVaultContract.poolById.callAsync(poolId); + const decreasedOperatorShare = new BigNumber(pool[1]); expect(decreasedOperatorShare, 'updated operator share').to.be.bignumber.equal(newOperatorShare); } } diff --git a/contracts/staking/test/epoch_test.ts b/contracts/staking/test/epoch_test.ts index 0d1a6f51a7..e32df331fb 100644 --- a/contracts/staking/test/epoch_test.ts +++ b/contracts/staking/test/epoch_test.ts @@ -34,14 +34,14 @@ blockchainTests('Epochs', env => { ///// 2/3 Validate Initial Epoch & TimeLock Period ///// { // epoch - const currentEpoch = await stakingApiWrapper.stakingContract.getCurrentEpoch.callAsync(); + const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync(); expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH); } ///// 3/3 Increment Epoch (TimeLock Should Not Increment) ///// await stakingApiWrapper.utils.skipToNextEpochAsync(); { // 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)); } }); diff --git a/contracts/staking/test/exchange_test.ts b/contracts/staking/test/exchange_test.ts index 6e5799054f..0565896145 100644 --- a/contracts/staking/test/exchange_test.ts +++ b/contracts/staking/test/exchange_test.ts @@ -27,18 +27,14 @@ blockchainTests('Exchange Integrations', env => { }); blockchainTests.resets('Exchange Tracking in Staking Contract', () => { it('basic exchange tracking', async () => { - const { - isValidExchangeAddress, - addExchangeAddress, - removeExchangeAddress, - } = stakingApiWrapper.stakingContract; + const { validExchanges, addExchangeAddress, removeExchangeAddress } = stakingApiWrapper.stakingContract; // 1 try querying an invalid addresses const invalidAddress = '0x0000000000000000000000000000000000000001'; - const isInvalidAddressValid = await isValidExchangeAddress.callAsync(invalidAddress); + const isInvalidAddressValid = await validExchanges.callAsync(invalidAddress); expect(isInvalidAddressValid).to.be.false(); // 2 add valid address await addExchangeAddress.awaitTransactionSuccessAsync(exchange); - const isValidAddressValid = await isValidExchangeAddress.callAsync(exchange); + const isValidAddressValid = await validExchanges.callAsync(exchange); expect(isValidAddressValid).to.be.true(); // 3 try adding valid address again let revertError = new StakingRevertErrors.ExchangeAddressAlreadyRegisteredError(exchange); @@ -46,7 +42,7 @@ blockchainTests('Exchange Integrations', env => { await expect(tx).to.revertWith(revertError); // 4 remove valid address await removeExchangeAddress.awaitTransactionSuccessAsync(exchange); - const isValidAddressStillValid = await isValidExchangeAddress.callAsync(exchange); + const isValidAddressStillValid = await validExchanges.callAsync(exchange); expect(isValidAddressStillValid).to.be.false(); // 5 try removing valid address again revertError = new StakingRevertErrors.ExchangeAddressNotRegisteredError(exchange); diff --git a/contracts/staking/test/pools_test.ts b/contracts/staking/test/pools_test.ts index 7ebd02bb15..79995fb1d2 100644 --- a/contracts/staking/test/pools_test.ts +++ b/contracts/staking/test/pools_test.ts @@ -40,7 +40,7 @@ blockchainTests('Staking Pool Management', env => { const poolId = await poolOperator.createStakingPoolAsync(operatorShare, false); expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); // 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); }); 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); expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); // 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); }); 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 - 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); // remove maker from pool @@ -149,7 +149,7 @@ blockchainTests('Staking Pool Management', env => { ); // 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); }); 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 - 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( stakingConstants.DEFAULT_PARAMS.maximumMakersInPool, ); diff --git a/contracts/staking/test/protocol_fees.ts b/contracts/staking/test/protocol_fees.ts index 36764a8abd..dd9250ff09 100644 --- a/contracts/staking/test/protocol_fees.ts +++ b/contracts/staking/test/protocol_fees.ts @@ -167,7 +167,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, ); 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); }); @@ -180,7 +180,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, ); assertNoWETHTransferLogs(receipt.logs); - const poolFees = await testContract.getProtocolFeesThisEpochByPool.callAsync(poolId); + const poolFees = await testContract.protocolFeesThisEpochByPool.callAsync(poolId); expect(poolFees).to.bignumber.eq(ZERO_AMOUNT); }); @@ -198,7 +198,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { await payAsync(); await payAsync(); 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); }); }); @@ -238,7 +238,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { { from: exchangeAddress, value: ZERO_AMOUNT }, ); 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); }); @@ -251,7 +251,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { { from: exchangeAddress, value: ZERO_AMOUNT }, ); 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); }); @@ -269,7 +269,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { await payAsync(); await payAsync(); 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); }); @@ -289,7 +289,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { await payAsync(true); await payAsync(false); 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); }); }); @@ -309,7 +309,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { await payAsync(makerAddress); await payAsync(otherMakerAddress); 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); }); @@ -330,8 +330,8 @@ blockchainTests('Protocol Fee Unit Tests', env => { await payAsync(poolId, makerAddress, fee); await payAsync(otherPoolId, otherMakerAddress, otherFee); const [poolFees, otherPoolFees] = await Promise.all([ - testContract.getProtocolFeesThisEpochByPool.callAsync(poolId), - testContract.getProtocolFeesThisEpochByPool.callAsync(otherPoolId), + testContract.protocolFeesThisEpochByPool.callAsync(poolId), + testContract.protocolFeesThisEpochByPool.callAsync(otherPoolId), ]); expect(poolFees).to.bignumber.eq(fee); expect(otherPoolFees).to.bignumber.eq(otherFee); @@ -347,7 +347,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { 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); }); @@ -359,7 +359,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { 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); }); @@ -371,7 +371,7 @@ blockchainTests('Protocol Fee Unit Tests', env => { 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); }); }); diff --git a/contracts/staking/test/rewards_test.ts b/contracts/staking/test/rewards_test.ts index 7822daac27..f7c63c5ce7 100644 --- a/contracts/staking/test/rewards_test.ts +++ b/contracts/staking/test/rewards_test.ts @@ -119,6 +119,10 @@ blockchainTests.resets('Testing Rewards', env => { ? _expectedEndBalances.membersRewardVaultBalance : 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([ // staker 1 stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync( @@ -133,11 +137,7 @@ blockchainTests.resets('Testing Rewards', env => { ), stakingApiWrapper.ethVaultContract.balanceOf.callAsync(stakers[1].getOwner()), // operator - stakingApiWrapper.rewardVaultContract.balanceOfOperator.callAsync(poolId), 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( expectedEndBalances.stakerRewardVaultBalance_1, @@ -151,16 +151,17 @@ blockchainTests.resets('Testing Rewards', env => { expect(finalEndBalancesAsArray[3], 'stakerEthVaultBalance_2').to.be.bignumber.equal( expectedEndBalances.stakerEthVaultBalance_2, ); - expect(finalEndBalancesAsArray[4], 'operatorRewardVaultBalance').to.be.bignumber.equal( - expectedEndBalances.operatorRewardVaultBalance, - ); - expect(finalEndBalancesAsArray[5], 'operatorEthVaultBalance').to.be.bignumber.equal( + + expect(finalEndBalancesAsArray[4], 'operatorEthVaultBalance').to.be.bignumber.equal( 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, ); - expect(finalEndBalancesAsArray[7], 'membersRewardVaultBalance').to.be.bignumber.equal( + expect(poolBalances.membersBalance, 'membersRewardVaultBalance').to.be.bignumber.equal( expectedEndBalances.membersRewardVaultBalance, ); }; diff --git a/contracts/staking/tsconfig.json b/contracts/staking/tsconfig.json index 4c4584f4de..1072f1ce8f 100644 --- a/contracts/staking/tsconfig.json +++ b/contracts/staking/tsconfig.json @@ -9,6 +9,7 @@ "generated-artifacts/IStakingEvents.json", "generated-artifacts/IStakingPoolRewardVault.json", "generated-artifacts/IStakingProxy.json", + "generated-artifacts/IStorage.json", "generated-artifacts/IStorageInit.json", "generated-artifacts/IStructs.json", "generated-artifacts/IVaultCore.json", @@ -21,7 +22,6 @@ "generated-artifacts/MixinConstants.json", "generated-artifacts/MixinCumulativeRewards.json", "generated-artifacts/MixinDeploymentConstants.json", - "generated-artifacts/MixinEthVault.json", "generated-artifacts/MixinExchangeFees.json", "generated-artifacts/MixinExchangeManager.json", "generated-artifacts/MixinParams.json",