diff --git a/contracts/colony/Colony.sol b/contracts/colony/Colony.sol index 6f227a5087..c48f9c6079 100755 --- a/contracts/colony/Colony.sol +++ b/contracts/colony/Colony.sol @@ -105,8 +105,12 @@ contract Colony is ColonyStorage, PatriciaTreeProofs { ); } - function getUserRoles(address who, uint256 where) public view returns (bytes32) { - return ColonyAuthority(address(authority)).getUserRoles(who, where); + function getUserRoles(address _user, uint256 _domainId) public view returns (bytes32) { + return ColonyAuthority(address(authority)).getUserRoles(_user, _domainId); + } + + function getCapabilityRoles(bytes4 _sig) public view returns (bytes32) { + return ColonyAuthority(address(authority)).getCapabilityRoles(address(this), _sig); } function getColonyNetwork() public view returns (address) { diff --git a/contracts/colony/ColonyDataTypes.sol b/contracts/colony/ColonyDataTypes.sol index b442028379..4c41747bb9 100755 --- a/contracts/colony/ColonyDataTypes.sol +++ b/contracts/colony/ColonyDataTypes.sol @@ -210,6 +210,7 @@ contract ColonyDataTypes { uint256 fundingPotId; uint256 domainId; uint256 finalizedTimestamp; + uint256 globalClaimDelay; } struct ExpenditureSlot { diff --git a/contracts/colony/ColonyExpenditure.sol b/contracts/colony/ColonyExpenditure.sol index 915bac783b..6a9871a32b 100644 --- a/contracts/colony/ColonyExpenditure.sol +++ b/contracts/colony/ColonyExpenditure.sol @@ -47,7 +47,8 @@ contract ColonyExpenditure is ColonyStorage { owner: msg.sender, fundingPotId: fundingPotCount, domainId: _domainId, - finalizedTimestamp: 0 + finalizedTimestamp: 0, + globalClaimDelay: 0 }); emit FundingPotAdded(fundingPotCount); @@ -144,6 +145,7 @@ contract ColonyExpenditure is ColonyStorage { emit ExpenditureSkillSet(_id, _slot, _skillId); } + // Deprecated function setExpenditurePayoutModifier( uint256 _permissionDomainId, uint256 _childSkillIndex, @@ -161,6 +163,7 @@ contract ColonyExpenditure is ColonyStorage { expenditureSlots[_id][_slot].payoutModifier = _payoutModifier; } + // Deprecated function setExpenditureClaimDelay( uint256 _permissionDomainId, uint256 _childSkillIndex, @@ -183,7 +186,7 @@ contract ColonyExpenditure is ColonyStorage { uint256 _permissionDomainId, uint256 _childSkillIndex, uint256 _id, - uint256 _slot, + uint256 _storageSlot, bool[] memory _mask, bytes32[] memory _keys, bytes32 _value @@ -193,23 +196,28 @@ contract ColonyExpenditure is ColonyStorage { expenditureExists(_id) authDomain(_permissionDomainId, _childSkillIndex, expenditures[_id].domainId) { - require(_keys.length > 0, "colony-expenditure-no-keys"); - - require( - _slot == EXPENDITURES_SLOT || - _slot == EXPENDITURESLOTS_SLOT || - _slot == EXPENDITURESLOTPAYOUTS_SLOT, - "colony-expenditure-bad-slot" - ); - // Only allow editing expenditure status, owner, and finalizedTimestamp // Note that status + owner occupy one slot - if (_slot == EXPENDITURES_SLOT) { - uint256 offset = uint256(_keys[_keys.length - 1]); - require(offset == 0 || offset == 3, "colony-expenditure-bad-offset"); + if (_storageSlot == EXPENDITURES_SLOT) { + require(_keys.length == 1, "colony-expenditure-bad-keys"); + uint256 offset = uint256(_keys[0]); + require(offset == 0 || offset == 3 || offset == 4, "colony-expenditure-bad-offset"); + + // Explicitly whitelist all slots, in case we add new slots in the future + } else if (_storageSlot == EXPENDITURESLOTS_SLOT) { + require(_keys.length >= 2, "colony-expenditure-bad-keys"); + uint256 offset = uint256(_keys[1]); + require(offset <= 3, "colony-expenditure-bad-offset"); + + // Should always be two mappings + } else if (_storageSlot == EXPENDITURESLOTPAYOUTS_SLOT) { + require(_keys.length == 2, "colony-expenditure-bad-keys"); + + } else { + require(false, "colony-expenditure-bad-slot"); } - executeStateChange(keccak256(abi.encode(_id, _slot)), _mask, _keys, _value); + executeStateChange(keccak256(abi.encode(_id, _storageSlot)), _mask, _keys, _value); } // Public view functions diff --git a/contracts/colony/ColonyFunding.sol b/contracts/colony/ColonyFunding.sol index 0c867a423b..b94e0933c8 100755 --- a/contracts/colony/ColonyFunding.sol +++ b/contracts/colony/ColonyFunding.sol @@ -95,6 +95,9 @@ contract ColonyFunding is ColonyStorage, PatriciaTreeProofs { // ignore-swc-123 } } + int256 constant MAX_PAYOUT_MODIFIER = int256(WAD); + int256 constant MIN_PAYOUT_MODIFIER = -int256(WAD); + function claimExpenditurePayout(uint256 _id, uint256 _slot, address _token) public stoppable expenditureExists(_id) @@ -102,17 +105,24 @@ contract ColonyFunding is ColonyStorage, PatriciaTreeProofs { // ignore-swc-123 { Expenditure storage expenditure = expenditures[_id]; ExpenditureSlot storage slot = expenditureSlots[_id][_slot]; - require(add(expenditure.finalizedTimestamp, slot.claimDelay) <= now, "colony-expenditure-cannot-claim"); + + require( + add(expenditure.finalizedTimestamp, add(expenditure.globalClaimDelay, slot.claimDelay)) <= now, + "colony-expenditure-cannot-claim" + ); FundingPot storage fundingPot = fundingPots[expenditure.fundingPotId]; assert(fundingPot.balance[_token] >= fundingPot.payouts[_token]); uint256 initialPayout = expenditureSlotPayouts[_id][_slot][_token]; - uint256 payoutScalar = uint256(slot.payoutModifier + int256(WAD)); + delete expenditureSlotPayouts[_id][_slot][_token]; + + int256 payoutModifier = imin(imax(slot.payoutModifier, MIN_PAYOUT_MODIFIER), MAX_PAYOUT_MODIFIER); + uint256 payoutScalar = uint256(payoutModifier + int256(WAD)); + uint256 repPayout = wmul(initialPayout, payoutScalar); uint256 tokenPayout = min(initialPayout, repPayout); uint256 tokenSurplus = sub(initialPayout, tokenPayout); - expenditureSlotPayouts[_id][_slot][_token] = 0; // Process reputation updates if own token if (_token == token) { diff --git a/contracts/colony/IColony.sol b/contracts/colony/IColony.sol index d50d9d4b6c..ce85de4209 100644 --- a/contracts/colony/IColony.sol +++ b/contracts/colony/IColony.sol @@ -122,10 +122,15 @@ contract IColony is ColonyDataTypes, IRecovery { public view returns (bool hasRole); /// @notice Gets the bytes32 representation of the roles for a user in a given domain - /// @param who The user whose roles we want to get - /// @param where The domain where we want to get roles for - /// @return roles bytes32 representation of the roles - function getUserRoles(address who, uint256 where) public view returns (bytes32 roles); + /// @param _user The user whose roles we want to get + /// @param _domain The domain we want to get roles in + /// @return roles bytes32 representation of the held roles + function getUserRoles(address _user, uint256 _domain) public view returns (bytes32 roles); + + /// @notice Gets the bytes32 representation of the roles authorized to call a function + /// @param _sig The function signature + /// @return roles bytes32 representation of the authorized roles + function getCapabilityRoles(bytes4 _sig) public view returns (bytes32 roles); /// @notice Emit a negative domain reputation update. Available only to Arbitration role holders /// @param _permissionDomainId The domainId in which I hold the Arbitration role @@ -223,6 +228,7 @@ contract IColony is ColonyDataTypes, IRecovery { function transferExpenditure(uint256 _id, address _newOwner) public; /// @notice DEPRECATED Updates the expenditure owner. Can only be called by Arbitration role. + /// @dev This is now deprecated and will be removed in a future version /// @param _permissionDomainId The domainId in which I have the permission to take this action /// @param _childSkillIndex The index that the `_domainId` is relative to `_permissionDomainId`, /// (only used if `_permissionDomainId` is different to `_domainId`) @@ -257,7 +263,8 @@ contract IColony is ColonyDataTypes, IRecovery { /// @param _skillId Id of the new skill to set function setExpenditureSkill(uint256 _id, uint256 _slot, uint256 _skillId) public; - /// @notice Set the payout modifier on an expenditure slot. Can only be called by Arbitration role. + /// @notice DEPRECATED Set the payout modifier on an expenditure slot. Can only be called by Arbitration role. + /// @dev This is now deprecated and will be removed in a future version /// @dev Note that when determining payouts the payoutModifier is incremented by WAD and converted into payoutScalar /// @param _permissionDomainId The domainId in which I have the permission to take this action /// @param _childSkillIndex The index that the `_domainId` is relative to `_permissionDomainId`, @@ -273,7 +280,8 @@ contract IColony is ColonyDataTypes, IRecovery { int256 _payoutModifier ) public; - /// @notice Set the claim delay on an expenditure slot. Can only be called by Arbitration role. + /// @notice DEPRECATED Set the claim delay on an expenditure slot. Can only be called by Arbitration role. + /// @dev This is now deprecated and will be removed in a future version /// @param _permissionDomainId The domainId in which I have the permission to take this action /// @param _childSkillIndex The index that the `_domainId` is relative to `_permissionDomainId`, /// (only used if `_permissionDomainId` is different to `_domainId`) @@ -293,15 +301,15 @@ contract IColony is ColonyDataTypes, IRecovery { /// @param _childSkillIndex The index that the `_domainId` is relative to `_permissionDomainId`, /// (only used if `_permissionDomainId` is different to `_domainId`) /// @param _id Expenditure identifier - /// @param _slot Number of the top-level storage slot - /// @param _mask Array of booleans indicated whether a key is a mapping (F) or offset (T). - /// @param _keys Array of additional keys (mappings & offsets) + /// @param _storageSlot Number of the top-level storage slot (25, 26, or 27) + /// @param _mask Array of booleans indicated whether a key is a mapping (F) or an array index (T). + /// @param _keys Array of additional keys (for mappings & arrays) /// @param _value Value to set at location function setExpenditureState( uint256 _permissionDomainId, uint256 _childSkillIndex, uint256 _id, - uint256 _slot, + uint256 _storageSlot, bool[] memory _mask, bytes32[] memory _keys, bytes32 _value diff --git a/contracts/extensions/VotingReputation.sol b/contracts/extensions/VotingReputation.sol new file mode 100644 index 0000000000..2e84bcdb61 --- /dev/null +++ b/contracts/extensions/VotingReputation.sol @@ -0,0 +1,1019 @@ +/* + This file is part of The Colony Network. + + The Colony Network is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + The Colony Network is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with The Colony Network. If not, see . +*/ + +pragma solidity 0.5.8; +pragma experimental ABIEncoderV2; + +import "./../../lib/dappsys/math.sol"; +import "./../../lib/dappsys/roles.sol"; +import "./../colony/ColonyDataTypes.sol"; +import "./../colony/IColony.sol"; +import "./../colonyNetwork/IColonyNetwork.sol"; +import "./../common/ERC20Extended.sol"; +import "./../patriciaTree/PatriciaTreeProofs.sol"; +import "./../tokenLocking/ITokenLocking.sol"; + + +contract VotingReputation is DSMath, PatriciaTreeProofs { + + // Events + event ExtensionInitialised(); + event ExtensionDeprecated(); + event MotionCreated(uint256 indexed motionId, address creator, uint256 indexed domainId); + event MotionStaked(uint256 indexed motionId, address indexed staker, uint256 indexed vote, uint256 amount); + event MotionVoteSubmitted(uint256 indexed motionId, address indexed voter); + event MotionVoteRevealed(uint256 indexed motionId, address indexed voter, uint256 indexed vote); + event MotionFinalized(uint256 indexed motionId, bytes action, bool executed); + event MotionEscalated(uint256 indexed motionId, address escalator, uint256 indexed domainId, uint256 indexed newDomainId); + event MotionRewardClaimed(uint256 indexed motionId, address indexed staker, uint256 indexed vote, uint256 amount); + event MotionEventSet(uint256 indexed motionId, uint256 eventIndex); + + // Constants + uint256 constant UINT256_MAX = 2**256 - 1; + uint256 constant UINT128_MAX = 2**128 - 1; + + uint256 constant NAY = 0; + uint256 constant YAY = 1; + + uint256 constant STAKE_END = 0; + uint256 constant SUBMIT_END = 1; + uint256 constant REVEAL_END = 2; + + bytes32 constant ROOT_ROLES = ( + bytes32(uint256(1)) << uint8(ColonyDataTypes.ColonyRole.Recovery) | + bytes32(uint256(1)) << uint8(ColonyDataTypes.ColonyRole.Root) + ); + + bytes4 constant CHANGE_FUNCTION = bytes4( + keccak256("setExpenditureState(uint256,uint256,uint256,uint256,bool[],bytes32[],bytes32)") + ); + + enum ExtensionState { Deployed, Active, Deprecated } + + // Initialization data + ExtensionState state; + + IColony colony; + IColonyNetwork colonyNetwork; + ITokenLocking tokenLocking; + address token; + + // All `Fraction` variables are stored as WADs i.e. fixed-point numbers with 18 digits after the radix. So + // 1 WAD = 10**18, which is interpreted as 1. + + uint256 totalStakeFraction; // Fraction of the domain's reputation needed to stake on each side in order to go to a motion. + // This can be set to a maximum of 0.5. + uint256 voterRewardFraction; // Fraction of staked tokens paid out to voters as rewards. This will be paid from the staked + // tokens of the losing side. This can be set to a maximum of 0.5. + + uint256 userMinStakeFraction; // Minimum stake as fraction of required stake. 1 means a single user will be required to + // provide the whole stake on each side, which may not be possible depending on totalStakeFraction and the distribution of + // reputation in a domain. + uint256 maxVoteFraction; // Fraction of total domain reputation that needs to commit votes before closing to further votes. + // Setting this to anything other than 1 will mean it is likely not all those eligible to vote will be able to do so. + + // All `Period` variables are second-denominated + + uint256 stakePeriod; // Length of time for staking + uint256 submitPeriod; // Length of time for submitting votes + uint256 revealPeriod; // Length of time for revealing votes + uint256 escalationPeriod; // Length of time for escalating after a vote + + constructor(address _colony) public { + colony = IColony(_colony); + colonyNetwork = IColonyNetwork(colony.getColonyNetwork()); + tokenLocking = ITokenLocking(colonyNetwork.getTokenLocking()); + token = colony.getToken(); + } + + /// @notice Initialise the extension + /// @param _totalStakeFraction The fraction of the domain's reputation we need to stake + /// @param _userMinStakeFraction The minimum per-user stake as fraction of total stake + /// @param _maxVoteFraction The fraction of the domain's reputation which must submit for quick-end + /// @param _voterRewardFraction The fraction of the total stake paid out to voters as rewards + /// @param _stakePeriod The length of the staking period in seconds + /// @param _submitPeriod The length of the submit period in seconds + /// @param _revealPeriod The length of the reveal period in seconds + /// @param _escalationPeriod The length of the escalation period in seconds + function initialise( + uint256 _totalStakeFraction, + uint256 _voterRewardFraction, + uint256 _userMinStakeFraction, + uint256 _maxVoteFraction, + uint256 _stakePeriod, + uint256 _submitPeriod, + uint256 _revealPeriod, + uint256 _escalationPeriod + ) + public + { + require(colony.hasUserRole(msg.sender, 1, ColonyDataTypes.ColonyRole.Root), "voting-rep-user-not-root"); + require(state == ExtensionState.Deployed, "voting-rep-already-initialised"); + + require(_totalStakeFraction <= WAD / 2, "voting-rep-greater-than-half-wad"); + require(_voterRewardFraction <= WAD / 2, "voting-rep-greater-than-half-wad"); + + require(_userMinStakeFraction <= WAD, "voting-rep-greater-than-wad"); + require(_maxVoteFraction <= WAD, "voting-rep-greater-than-wad"); + + require(_stakePeriod <= 365 days, "voting-rep-period-too-long"); + require(_submitPeriod <= 365 days, "voting-rep-period-too-long"); + require(_revealPeriod <= 365 days, "voting-rep-period-too-long"); + require(_escalationPeriod <= 365 days, "voting-rep-period-too-long"); + + state = ExtensionState.Active; + + totalStakeFraction = _totalStakeFraction; + voterRewardFraction = _voterRewardFraction; + + userMinStakeFraction = _userMinStakeFraction; + maxVoteFraction = _maxVoteFraction; + + stakePeriod = _stakePeriod; + submitPeriod = _submitPeriod; + revealPeriod = _revealPeriod; + escalationPeriod = _escalationPeriod; + + emit ExtensionInitialised(); + } + + /// @notice Deprecate the extension, prevening new motions from being created + function deprecate() public { + require(colony.hasUserRole(msg.sender, 1, ColonyDataTypes.ColonyRole.Root), "voting-rep-user-not-root"); + + state = ExtensionState.Deprecated; + + emit ExtensionDeprecated(); + } + + // Data structures + enum MotionState { Null, Staking, Submit, Reveal, Closed, Finalizable, Finalized, Failed } + + struct Motion { + uint64[3] events; // For recording motion lifecycle timestamps (STAKE, SUBMIT, REVEAL) + bytes32 rootHash; + uint256 domainId; + uint256 skillId; + uint256 skillRep; + uint256 repSubmitted; + uint256 paidVoterComp; + uint256[2] pastVoterComp; // [nay, yay] + uint256[2] stakes; // [nay, yay] + uint256[2] votes; // [nay, yay] + bool escalated; + bool finalized; + address altTarget; + bytes action; + } + + // Storage + uint256 motionCount; + mapping (uint256 => Motion) motions; + mapping (uint256 => mapping (address => mapping (uint256 => uint256))) stakes; + mapping (uint256 => mapping (address => bytes32)) voteSecrets; + + mapping (bytes32 => uint256) expenditurePastVotes; // expenditure slot signature => voting power + mapping (bytes32 => uint256) expenditureMotionCounts; // expenditure struct signature => count + + // Public functions (interface) + + /// @notice Create a motion in the root domain + /// @param _altTarget The contract to which we send the action (0x0 for the colony) + /// @param _action A bytes array encoding a function call + /// @param _key Reputation tree key for the root domain + /// @param _value Reputation tree value for the root domain + /// @param _branchMask The branchmask of the proof + /// @param _siblings The siblings of the proof + function createRootMotion( + address _altTarget, + bytes memory _action, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + public + { + uint256 rootSkillId = colony.getDomain(1).skillId; + createMotion(_altTarget, _action, 1, rootSkillId, _key, _value, _branchMask, _siblings); + } + + /// @notice Create a motion in any domain + /// @param _domainId The domain where we vote on the motion + /// @param _childSkillIndex The childSkillIndex pointing to the domain of the action + /// @param _action A bytes array encoding a function call + /// @param _key Reputation tree key for the domain + /// @param _value Reputation tree value for the domain + /// @param _branchMask The branchmask of the proof + /// @param _siblings The siblings of the proof + function createDomainMotion( + uint256 _domainId, + uint256 _childSkillIndex, + bytes memory _action, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + public + { + // Check the function requires a non-root permission (and thus a domain proof) + require( + colony.getCapabilityRoles(getSig(_action)) | ROOT_ROLES != ROOT_ROLES, + "voting-rep-invalid-function" + ); + + uint256 domainSkillId = colony.getDomain(_domainId).skillId; + uint256 actionDomainSkillId = getActionDomainSkillId(_action); + + if (domainSkillId != actionDomainSkillId) { + uint256 childSkillId = colonyNetwork.getChildSkillId(domainSkillId, _childSkillIndex); + require(childSkillId == actionDomainSkillId, "voting-rep-invalid-domain-id"); + } + + createMotion(address(0x0), _action, _domainId, domainSkillId, _key, _value, _branchMask, _siblings); + } + + /// @notice Stake on a motion + /// @param _motionId The id of the motion + /// @param _permissionDomainId The domain where the extension has the arbitration permission + /// @param _childSkillIndex For the domain in which the motion is occurring + /// @param _vote The side being supported (0 = NAY, 1 = YAY) + /// @param _amount The amount of tokens being staked + /// @param _key Reputation tree key for the staker/domain + /// @param _value Reputation tree value for the staker/domain + /// @param _branchMask The branchmask of the proof + /// @param _siblings The siblings of the proof + function stakeMotion( + uint256 _motionId, + uint256 _permissionDomainId, + uint256 _childSkillIndex, + uint256 _vote, + uint256 _amount, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + public + { + Motion storage motion = motions[_motionId]; + require(_vote <= 1, "voting-rep-bad-vote"); + require(getMotionState(_motionId) == MotionState.Staking, "voting-rep-motion-not-staking"); + + uint256 requiredStake = getRequiredStake(_motionId); + uint256 amount = min(_amount, sub(requiredStake, motion.stakes[_vote])); + require(amount > 0, "voting-rep-bad-amount"); + + uint256 stakerTotalAmount = add(stakes[_motionId][msg.sender][_vote], amount); + + require( + stakerTotalAmount <= getReputationFromProof(_motionId, msg.sender, _key, _value, _branchMask, _siblings), + "voting-rep-insufficient-rep" + ); + require( + stakerTotalAmount >= wmul(requiredStake, userMinStakeFraction) || + add(motion.stakes[_vote], amount) == requiredStake, // To prevent a residual stake from being un-stakable + "voting-rep-insufficient-stake" + ); + + colony.obligateStake(msg.sender, motion.domainId, amount); + colony.transferStake(_permissionDomainId, _childSkillIndex, address(this), msg.sender, motion.domainId, amount, address(this)); + tokenLocking.claim(token, true); + + // Update the stake + motion.stakes[_vote] = add(motion.stakes[_vote], amount); + stakes[_motionId][msg.sender][_vote] = stakerTotalAmount; + + // Increment counter & extend claim delay if staking for an expenditure state change + if ( + _vote == YAY && + !motion.escalated && + motion.stakes[YAY] == requiredStake && + getSig(motion.action) == CHANGE_FUNCTION && + motion.altTarget == address(0x0) + ) { + bytes32 structHash = hashExpenditureActionStruct(motion.action); + expenditureMotionCounts[structHash] = add(expenditureMotionCounts[structHash], 1); + // Set to UINT256_MAX / 3 to avoid overflow (finalizedTimestamp + globalClaimDelay + claimDelay) + bytes memory claimDelayAction = createClaimDelayAction(motion.action, UINT256_MAX / 3); + require(executeCall(_motionId, claimDelayAction), "voting-rep-expenditure-lock-failed"); + } + + emit MotionStaked(_motionId, msg.sender, _vote, amount); + + // Move to vote submission once both sides are fully staked + if (motion.stakes[NAY] == requiredStake && motion.stakes[YAY] == requiredStake) { + motion.events[STAKE_END] = uint64(now); + motion.events[SUBMIT_END] = motion.events[STAKE_END] + uint64(submitPeriod); + motion.events[REVEAL_END] = motion.events[SUBMIT_END] + uint64(revealPeriod); + + emit MotionEventSet(_motionId, STAKE_END); + + // Move to second staking window once one side is fully staked + } else if ( + (_vote == NAY && motion.stakes[NAY] == requiredStake) || + (_vote == YAY && motion.stakes[YAY] == requiredStake) + ) { + motion.events[STAKE_END] = uint64(now + stakePeriod); + motion.events[SUBMIT_END] = motion.events[STAKE_END] + uint64(submitPeriod); + motion.events[REVEAL_END] = motion.events[SUBMIT_END] + uint64(revealPeriod); + + // New stake supersedes prior votes + delete motion.votes; + delete motion.repSubmitted; + + emit MotionEventSet(_motionId, STAKE_END); + } + + } + + /// @notice Submit a vote secret for a motion + /// @param _motionId The id of the motion + /// @param _voteSecret The hashed vote secret + /// @param _key Reputation tree key for the staker/domain + /// @param _value Reputation tree value for the staker/domain + /// @param _branchMask The branchmask of the proof + /// @param _siblings The siblings of the proof + function submitVote( + uint256 _motionId, + bytes32 _voteSecret, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + public + { + Motion storage motion = motions[_motionId]; + require(getMotionState(_motionId) == MotionState.Submit, "voting-rep-motion-not-open"); + require(_voteSecret != bytes32(0), "voting-rep-invalid-secret"); + + uint256 userRep = getReputationFromProof(_motionId, msg.sender, _key, _value, _branchMask, _siblings); + + // Count reputation if first submission + if (voteSecrets[_motionId][msg.sender] == bytes32(0)) { + motion.repSubmitted = add(motion.repSubmitted, userRep); + } + + voteSecrets[_motionId][msg.sender] = _voteSecret; + + emit MotionVoteSubmitted(_motionId, msg.sender); + + if (motion.repSubmitted >= wmul(motion.skillRep, maxVoteFraction)) { + motion.events[SUBMIT_END] = uint64(now); + motion.events[REVEAL_END] = uint64(now + revealPeriod); + + emit MotionEventSet(_motionId, SUBMIT_END); + } + } + + /// @notice Reveal a vote secret for a motion + /// @param _motionId The id of the motion + /// @param _salt The salt used to hash the vote + /// @param _vote The side being supported (0 = NAY, 1 = YAY) + /// @param _key Reputation tree key for the staker/domain + /// @param _value Reputation tree value for the staker/domain + /// @param _branchMask The branchmask of the proof + /// @param _siblings The siblings of the proof + function revealVote( + uint256 _motionId, + bytes32 _salt, + uint256 _vote, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + public + { + Motion storage motion = motions[_motionId]; + require(getMotionState(_motionId) == MotionState.Reveal, "voting-rep-motion-not-reveal"); + require(_vote <= 1, "voting-rep-bad-vote"); + + uint256 userRep = getReputationFromProof(_motionId, msg.sender, _key, _value, _branchMask, _siblings); + motion.votes[_vote] = add(motion.votes[_vote], userRep); + + bytes32 voteSecret = voteSecrets[_motionId][msg.sender]; + require(voteSecret == getVoteSecret(_salt, _vote), "voting-rep-secret-no-match"); + delete voteSecrets[_motionId][msg.sender]; + + uint256 voterReward = getVoterReward(_motionId, userRep); + motion.paidVoterComp = add(motion.paidVoterComp, voterReward); + tokenLocking.transfer(token, voterReward, msg.sender, true); + + emit MotionVoteRevealed(_motionId, msg.sender, _vote); + + // See if reputation revealed matches reputation submitted + if (add(motion.votes[NAY], motion.votes[YAY]) == motion.repSubmitted) { + motion.events[REVEAL_END] = uint64(now); + + emit MotionEventSet(_motionId, REVEAL_END); + } + } + + /// @notice Escalate a motion to a higher domain + /// @param _motionId The id of the motion + /// @param _newDomainId The desired domain of escalation + /// @param _childSkillIndex For the current domain, relative to the escalated domain + /// @param _key Reputation tree key for the new domain + /// @param _value Reputation tree value for the new domain + /// @param _branchMask The branchmask of the proof + /// @param _siblings The siblings of the proof + function escalateMotion( + uint256 _motionId, + uint256 _newDomainId, + uint256 _childSkillIndex, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + public + { + Motion storage motion = motions[_motionId]; + require(getMotionState(_motionId) == MotionState.Closed, "voting-rep-motion-not-closed"); + + uint256 newDomainSkillId = colony.getDomain(_newDomainId).skillId; + uint256 childSkillId = colonyNetwork.getChildSkillId(newDomainSkillId, _childSkillIndex); + require(childSkillId == motion.skillId, "voting-rep-invalid-domain-proof"); + + uint256 domainId = motion.domainId; + motion.domainId = _newDomainId; + motion.skillId = newDomainSkillId; + motion.skillRep = getReputationFromProof(_motionId, address(0x0), _key, _value, _branchMask, _siblings); + + uint256 loser = (motion.votes[NAY] < motion.votes[YAY]) ? NAY : YAY; + motion.stakes[loser] = sub(motion.stakes[loser], motion.paidVoterComp); + motion.pastVoterComp[loser] = add(motion.pastVoterComp[loser], motion.paidVoterComp); + delete motion.paidVoterComp; + + uint256 requiredStake = getRequiredStake(_motionId); + motion.events[STAKE_END] = (motion.stakes[NAY] < requiredStake || motion.stakes[YAY] < requiredStake) ? + uint64(now + stakePeriod) : uint64(now); + + motion.events[SUBMIT_END] = motion.events[STAKE_END] + uint64(submitPeriod); + motion.events[REVEAL_END] = motion.events[SUBMIT_END] + uint64(revealPeriod); + + motion.escalated = true; + + emit MotionEscalated(_motionId, msg.sender, domainId, _newDomainId); + + if (motion.events[STAKE_END] == uint64(now)) { + emit MotionEventSet(_motionId, STAKE_END); + } + } + + function finalizeMotion(uint256 _motionId) public { + Motion storage motion = motions[_motionId]; + require(getMotionState(_motionId) == MotionState.Finalizable, "voting-rep-motion-not-finalizable"); + + assert( + motion.stakes[YAY] == getRequiredStake(_motionId) || + add(motion.votes[NAY], motion.votes[YAY]) > 0 + ); + + motion.finalized = true; + + bool canExecute = ( + motion.stakes[NAY] < motion.stakes[YAY] || + motion.votes[NAY] < motion.votes[YAY] + ); + + if (getSig(motion.action) == CHANGE_FUNCTION && motion.altTarget == address(0x0)) { + bytes32 structHash = hashExpenditureActionStruct(motion.action); + expenditureMotionCounts[structHash] = sub(expenditureMotionCounts[structHash], 1); + + // Release the claimDelay if this is the last active motion + if (expenditureMotionCounts[structHash] == 0) { + bytes memory claimDelayAction = createClaimDelayAction(motion.action, 0); + // No require this time, since we don't want stakes to be permanently locked + executeCall(_motionId, claimDelayAction); + } + + bytes32 actionHash = hashExpenditureAction(motion.action); + uint256 votePower = (add(motion.votes[NAY], motion.votes[YAY]) > 0) ? + motion.votes[YAY] : motion.stakes[YAY]; + + if (expenditurePastVotes[actionHash] < votePower) { + expenditurePastVotes[actionHash] = votePower; + canExecute = canExecute && true; + } else { + canExecute = canExecute && false; + } + } + + bool executed; + + if (canExecute) { + executed = executeCall(_motionId, motion.action); + } + + emit MotionFinalized(_motionId, motion.action, executed); + } + + /// @notice Claim the staker's reward + /// @param _motionId The id of the motion + /// @param _permissionDomainId The domain where the extension has the arbitration permission + /// @param _childSkillIndex For the domain in which the motion is occurring + /// @param _staker The staker whose reward is being claimed + /// @param _vote The side being supported (0 = NAY, 1 = YAY) + function claimReward( + uint256 _motionId, + uint256 _permissionDomainId, + uint256 _childSkillIndex, + address _staker, + uint256 _vote + ) + public + { + Motion storage motion = motions[_motionId]; + require( + getMotionState(_motionId) == MotionState.Finalized || + getMotionState(_motionId) == MotionState.Failed, + "voting-rep-motion-not-claimable" + ); + + (uint256 stakerReward, uint256 repPenalty) = getStakerReward(_motionId, _staker, _vote); + + require(stakerReward > 0, "voting-rep-nothing-to-claim"); + delete stakes[_motionId][_staker][_vote]; + + tokenLocking.transfer(token, stakerReward, _staker, true); + + if (repPenalty > 0) { + colony.emitDomainReputationPenalty( + _permissionDomainId, + _childSkillIndex, + motion.domainId, + _staker, + -int256(repPenalty) + ); + } + + emit MotionRewardClaimed(_motionId, _staker, _vote, stakerReward); + } + + // Public view functions + + /// @notice Get the total stake fraction + /// @return The total stake fraction + function getTotalStakeFraction() public view returns (uint256) { + return totalStakeFraction; + } + + /// @notice Get the voter reward fraction + /// @return The voter reward fraction + function getVoterRewardFraction() public view returns (uint256) { + return voterRewardFraction; + } + + /// @notice Get the user min stake fraction + /// @return The user min stake fraction + function getUserMinStakeFraction() public view returns (uint256) { + return userMinStakeFraction; + } + + /// @notice Get the max vote fraction + /// @return The max vote fraction + function getMaxVoteFraction() public view returns (uint256) { + return maxVoteFraction; + } + + /// @notice Get the stake period + /// @return The stake period + function getStakePeriod() public view returns (uint256) { + return stakePeriod; + } + + /// @notice Get the submit period + /// @return The submit period + function getSubmitPeriod() public view returns (uint256) { + return submitPeriod; + } + + /// @notice Get the reveal period + /// @return The reveal period + function getRevealPeriod() public view returns (uint256) { + return revealPeriod; + } + + /// @notice Get the escalation period + /// @return The escalation period + function getEscalationPeriod() public view returns (uint256) { + return escalationPeriod; + } + + /// @notice Get the total motion count + /// @return The total motion count + function getMotionCount() public view returns (uint256) { + return motionCount; + } + + /// @notice Get the data for a single motion + /// @param _motionId The id of the motion + /// @return motion The motion struct + function getMotion(uint256 _motionId) public view returns (Motion memory motion) { + motion = motions[_motionId]; + } + + /// @notice Get a user's stake on a motion + /// @param _motionId The id of the motion + /// @param _staker The staker address + /// @param _vote The side being supported (0 = NAY, 1 = YAY) + /// @return The user's stake + function getStake(uint256 _motionId, address _staker, uint256 _vote) public view returns (uint256) { + return stakes[_motionId][_staker][_vote]; + } + + /// @notice Get the number of ongoing motions for a single expenditure / expenditure slot + /// @param _structHash The hash of the expenditureId or expenditureId*expenditureSlot + /// @return The number of ongoing motions + function getExpenditureMotionCount(bytes32 _structHash) public view returns (uint256) { + return expenditureMotionCounts[_structHash]; + } + + /// @notice Get the largest past vote on a single expenditure variable + /// @param _actionHash The hash of the particular expenditure action + /// @return The largest past vote on this variable + function getExpenditurePastVote(bytes32 _actionHash) public view returns (uint256) { + return expenditurePastVotes[_actionHash]; + } + + /// @notice Get the current state of the motion + /// @return The current motion state + function getMotionState(uint256 _motionId) public view returns (MotionState) { + Motion storage motion = motions[_motionId]; + uint256 requiredStake = getRequiredStake(_motionId); + + // Check for valid motion Id + if (_motionId == 0 || _motionId > motionCount) { + + return MotionState.Null; + + // If finalized, we're done + } else if (motion.finalized) { + + return MotionState.Finalized; + + // Not fully staked + } else if ( + motion.stakes[YAY] < requiredStake || + motion.stakes[NAY] < requiredStake + ) { + + // Are we still staking? + if (now < motion.events[STAKE_END]) { + return MotionState.Staking; + // If not, did the YAY side stake? + } else if (motion.stakes[YAY] == requiredStake) { + return MotionState.Finalizable; + // If not, was there a prior vote we can fall back on? + } else if (add(motion.votes[NAY], motion.votes[YAY]) > 0) { + return MotionState.Finalizable; + // Otherwise, the motion failed + } else { + return MotionState.Failed; + } + + // Fully staked, go to a vote + } else { + + if (now < motion.events[SUBMIT_END]) { + return MotionState.Submit; + } else if (now < motion.events[REVEAL_END]) { + return MotionState.Reveal; + } else if ( + now < motion.events[REVEAL_END] + escalationPeriod && + motion.domainId > 1 + ) { + return MotionState.Closed; + } else { + return MotionState.Finalizable; + } + + } + } + + /// @notice Get the voter reward + /// @param _motionId The id of the motion + /// @param _voterRep The reputation the voter has in the domain + /// @return The voter reward + function getVoterReward(uint256 _motionId, uint256 _voterRep) public view returns (uint256) { + Motion storage motion = motions[_motionId]; + uint256 fractionUserReputation = wdiv(_voterRep, motion.skillRep); + uint256 totalStake = add(motion.stakes[YAY], motion.stakes[NAY]); + return wmul(wmul(fractionUserReputation, totalStake), voterRewardFraction); + } + + /// @notice Get the staker reward + /// @param _motionId The id of the motion + /// @param _staker The staker's address + /// @param _vote The vote (0 = NAY, 1 = YAY) + /// @return The staker reward and the reputation penalty (if any) + function getStakerReward(uint256 _motionId, address _staker, uint256 _vote) public view returns (uint256, uint256) { + Motion storage motion = motions[_motionId]; + + uint256 stakeFraction = wdiv( + stakes[_motionId][_staker][_vote], + add(motion.stakes[_vote], motion.pastVoterComp[_vote]) + ); + + uint256 realStake = wmul(stakeFraction, motion.stakes[_vote]); + uint256 requiredStake = getRequiredStake(_motionId); + + uint256 stakerReward; + uint256 repPenalty; + + // Went to a vote, use vote to determine reward or penalty + if (add(motion.votes[NAY], motion.votes[YAY]) > 0) { + + uint256 loserStake = sub(requiredStake, motion.paidVoterComp); + uint256 totalVotes = add(motion.votes[NAY], motion.votes[YAY]); + uint256 winFraction = wdiv(motion.votes[_vote], totalVotes); + uint256 winShare = wmul(winFraction, 2 * WAD); // On a scale of 0-2 WAD + + if (winShare > WAD || (winShare == WAD && _vote == NAY)) { + stakerReward = wmul(stakeFraction, add(requiredStake, wmul(loserStake, winShare - WAD))); + } else { + stakerReward = wmul(stakeFraction, wmul(loserStake, winShare)); + repPenalty = sub(realStake, stakerReward); + } + + // Determine rewards based on stakes alone + } else { + assert(motion.paidVoterComp == 0); + + // Your side fully staked, receive 10% (proportional) of loser's stake + if ( + motion.stakes[_vote] == requiredStake && + motion.stakes[flip(_vote)] < requiredStake + ) { + + uint256 loserStake = motion.stakes[flip(_vote)]; + uint256 totalPenalty = wmul(loserStake, WAD / 10); + stakerReward = wmul(stakeFraction, add(requiredStake, totalPenalty)); + + // Opponent's side fully staked, pay 10% penalty + } else if ( + motion.stakes[_vote] < requiredStake && + motion.stakes[flip(_vote)] == requiredStake + ) { + + uint256 loserStake = motion.stakes[_vote]; + uint256 totalPenalty = wmul(loserStake, WAD / 10); + stakerReward = wmul(stakeFraction, sub(loserStake, totalPenalty)); + repPenalty = sub(realStake, stakerReward); + + // Neither side fully staked (or no votes were revealed), no reward or penalty + } else { + + stakerReward = realStake; + + } + } + + return (stakerReward, repPenalty); + } + + // Internal functions + + function createMotion( + address _altTarget, + bytes memory _action, + uint256 _domainId, + uint256 _skillId, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + internal + { + require(state == ExtensionState.Active, "voting-rep-not-active"); + require(_altTarget != address(colony), "voting-rep-alt-target-cannot-be-base-colony"); + + motionCount += 1; + Motion storage motion = motions[motionCount]; + + motion.events[STAKE_END] = uint64(now + stakePeriod); + motion.events[SUBMIT_END] = motion.events[STAKE_END] + uint64(submitPeriod); + motion.events[REVEAL_END] = motion.events[SUBMIT_END] + uint64(revealPeriod); + + motion.rootHash = colonyNetwork.getReputationRootHash(); + motion.domainId = _domainId; + motion.skillId = _skillId; + + motion.skillRep = getReputationFromProof(motionCount, address(0x0), _key, _value, _branchMask, _siblings); + motion.altTarget = _altTarget; + motion.action = _action; + + emit MotionCreated(motionCount, msg.sender, _domainId); + } + + function getVoteSecret(bytes32 _salt, uint256 _vote) internal pure returns (bytes32) { + return keccak256(abi.encodePacked(_salt, _vote)); + } + + function getRequiredStake(uint256 _motionId) internal view returns (uint256) { + return wmul(motions[_motionId].skillRep, totalStakeFraction); + } + + function flip(uint256 _vote) internal pure returns (uint256) { + return sub(1, _vote); + } + + function getReputationFromProof( + uint256 _motionId, + address _who, + bytes memory _key, + bytes memory _value, + uint256 _branchMask, + bytes32[] memory _siblings + ) + internal view returns (uint256) + { + bytes32 impliedRoot = getImpliedRootHashKey(_key, _value, _branchMask, _siblings); + require(motions[_motionId].rootHash == impliedRoot, "voting-rep-invalid-root-hash"); + + uint256 reputationValue; + address keyColonyAddress; + uint256 keySkill; + address keyUserAddress; + + assembly { + reputationValue := mload(add(_value, 32)) + keyColonyAddress := mload(add(_key, 20)) + keySkill := mload(add(_key, 52)) + keyUserAddress := mload(add(_key, 72)) + } + + require(keyColonyAddress == address(colony), "voting-rep-invalid-colony-address"); + require(keySkill == motions[_motionId].skillId, "voting-rep-invalid-skill-id"); + require(keyUserAddress == _who, "voting-rep-invalid-user-address"); + + return reputationValue; + } + + function getActionDomainSkillId(bytes memory _action) internal view returns (uint256) { + uint256 permissionDomainId; + uint256 childSkillIndex; + + assembly { + permissionDomainId := mload(add(_action, 0x24)) + childSkillIndex := mload(add(_action, 0x44)) + } + + uint256 permissionSkillId = colony.getDomain(permissionDomainId).skillId; + + if (childSkillIndex == UINT256_MAX) { + return permissionSkillId; + } else { + return colonyNetwork.getChildSkillId(permissionSkillId, childSkillIndex); + } + } + + function executeCall(uint256 motionId, bytes memory action) internal returns (bool success) { + address altTarget = motions[motionId].altTarget; + address to = (altTarget == address(0x0)) ? address(colony) : altTarget; + + assembly { + // call contract at address a with input mem[in…(in+insize)) + // providing g gas and v wei and output area mem[out…(out+outsize)) + // returning 0 on error (eg. out of gas) and 1 on success + + // call(g, a, v, in, insize, out, outsize) + success := call(gas, to, 0, add(action, 0x20), mload(action), 0, 0) + } + + return success; + } + + function getSig(bytes memory action) internal returns (bytes4 sig) { + assembly { + sig := mload(add(action, 0x20)) + } + } + + function hashExpenditureAction(bytes memory action) internal returns (bytes32 hash) { + assembly { + // Hash all but the domain proof and value, so actions for the same + // storage slot return the same value. + // Recall: mload(action) gives length of bytes array + // So skip past the three bytes32 (length + domain proof), + // plus 4 bytes for the sig. Subtract the same from the end, less + // the length bytes32. The value itself is located at 0xe4, zero it out. + mstore(add(action, 0xe4), 0x0) + hash := keccak256(add(action, 0x64), sub(mload(action), 0x44)) + } + } + + function hashExpenditureActionStruct(bytes memory action) internal returns (bytes32 hash) { + assert(getSig(action) == CHANGE_FUNCTION); + + uint256 expenditureId; + uint256 storageSlot; + uint256 expenditureSlot; + + assembly { + expenditureId := mload(add(action, 0x64)) + storageSlot := mload(add(action, 0x84)) + expenditureSlot := mload(add(action, 0x184)) + } + + if (storageSlot == 25) { + hash = keccak256(abi.encodePacked(expenditureId)); + } else { + hash = keccak256(abi.encodePacked(expenditureId, expenditureSlot)); + } + } + + function createClaimDelayAction(bytes memory action, uint256 value) + public + returns (bytes memory) + { + // See https://solidity.readthedocs.io/en/develop/abi-spec.html#use-of-dynamic-types + // for documentation on how the action `bytes` is encoded + // In brief, the first byte32 is the length of the array. Then we have + // 4 bytes of function signature, following by an arbitrary number of + // additional byte32 arguments. 32 in hex is 0x20, so every increment + // of 0x20 represents advancing one byte, 4 is the function signature. + // So: 0x[length][sig][args...] + + bytes32 functionSignature; + uint256 permissionDomainId; + uint256 childSkillIndex; + uint256 expenditureId; + uint256 storageSlot; + + assembly { + functionSignature := mload(add(action, 0x20)) + permissionDomainId := mload(add(action, 0x24)) + childSkillIndex := mload(add(action, 0x44)) + expenditureId := mload(add(action, 0x64)) + storageSlot := mload(add(action, 0x84)) + } + + // If we are editing the main expenditure struct + if (storageSlot == 25) { + + bytes memory claimDelayAction = new bytes(4 + 32 * 11); // 356 bytes + assembly { + mstore(add(claimDelayAction, 0x20), functionSignature) + mstore(add(claimDelayAction, 0x24), permissionDomainId) + mstore(add(claimDelayAction, 0x44), childSkillIndex) + mstore(add(claimDelayAction, 0x64), expenditureId) + mstore(add(claimDelayAction, 0x84), 25) // expenditure storage slot + mstore(add(claimDelayAction, 0xa4), 0xe0) // mask location + mstore(add(claimDelayAction, 0xc4), 0x120) // keys location + mstore(add(claimDelayAction, 0xe4), value) + mstore(add(claimDelayAction, 0x104), 1) // mask length + mstore(add(claimDelayAction, 0x124), 1) // offset + mstore(add(claimDelayAction, 0x144), 1) // keys length + mstore(add(claimDelayAction, 0x164), 4) // globalClaimDelay offset + } + return claimDelayAction; + + // If we are editing an expenditure slot + } else { + + bytes memory claimDelayAction = new bytes(4 + 32 * 13); // 420 bytes + uint256 expenditureSlot; + + assembly { + expenditureSlot := mload(add(action, 0x184)) + + mstore(add(claimDelayAction, 0x20), functionSignature) + mstore(add(claimDelayAction, 0x24), permissionDomainId) + mstore(add(claimDelayAction, 0x44), childSkillIndex) + mstore(add(claimDelayAction, 0x64), expenditureId) + mstore(add(claimDelayAction, 0x84), 26) // expenditureSlot storage slot + mstore(add(claimDelayAction, 0xa4), 0xe0) // mask location + mstore(add(claimDelayAction, 0xc4), 0x140) // keys location + mstore(add(claimDelayAction, 0xe4), value) + mstore(add(claimDelayAction, 0x104), 2) // mask length + mstore(add(claimDelayAction, 0x124), 0) // mapping + mstore(add(claimDelayAction, 0x144), 1) // offset + mstore(add(claimDelayAction, 0x164), 2) // keys length + mstore(add(claimDelayAction, 0x184), expenditureSlot) + mstore(add(claimDelayAction, 0x1a4), 1) // claimDelay offset + } + return claimDelayAction; + + } + } +} diff --git a/contracts/extensions/VotingReputationFactory.sol b/contracts/extensions/VotingReputationFactory.sol new file mode 100644 index 0000000000..211deeb24a --- /dev/null +++ b/contracts/extensions/VotingReputationFactory.sol @@ -0,0 +1,48 @@ +/* + This file is part of The Colony Network. + + The Colony Network is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + The Colony Network is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with The Colony Network. If not, see . +*/ + +pragma solidity 0.5.8; +pragma experimental ABIEncoderV2; + +import "./../colony/ColonyDataTypes.sol"; +import "./../colony/IColony.sol"; +import "./ExtensionFactory.sol"; +import "./VotingReputation.sol"; + + +contract VotingReputationFactory is ExtensionFactory, ColonyDataTypes { // ignore-swc-123 + mapping (address => VotingReputation) public deployedExtensions; + + modifier isRoot(address _colony) { + require(IColony(_colony).hasUserRole(msg.sender, 1, ColonyRole.Root), "colony-extension-user-not-root"); // ignore-swc-123 + _; + } + + function deployExtension(address _colony) external isRoot(_colony) { + require(deployedExtensions[_colony] == VotingReputation(0x00), "colony-extension-already-deployed"); + VotingReputation newExtensionAddress = new VotingReputation(_colony); + deployedExtensions[_colony] = newExtensionAddress; + + emit ExtensionDeployed("VotingReputation", _colony, address(newExtensionAddress)); + } + + function removeExtension(address _colony) external isRoot(_colony) { + deployedExtensions[_colony] = VotingReputation(0x00); + + emit ExtensionRemoved("VotingReputation", _colony); + } +} diff --git a/docs/_Interface_IColony.md b/docs/_Interface_IColony.md index 2badfa4699..1c5239e48c 100644 --- a/docs/_Interface_IColony.md +++ b/docs/_Interface_IColony.md @@ -367,6 +367,23 @@ View an approval to obligate tokens. |---|---|---| |approval|uint256|The amount the user has approved +### `getCapabilityRoles` + +Gets the bytes32 representation of the roles authorized to call a function + + +**Parameters** + +|Name|Type|Description| +|---|---|---| +|_sig|bytes4|The function signature + +**Return Parameters** + +|Name|Type|Description| +|---|---|---| +|roles|bytes32|bytes32 representation of the authorized roles + ### `getColonyNetwork` Returns the colony network address set on the Colony. @@ -801,14 +818,14 @@ Gets the bytes32 representation of the roles for a user in a given domain |Name|Type|Description| |---|---|---| -|who|address|The user whose roles we want to get -|where|uint256|The domain where we want to get roles for +|_user|address|The user whose roles we want to get +|_domain|uint256|The_domain domain where we want to get roles for **Return Parameters** |Name|Type|Description| |---|---|---| -|roles|bytes32|bytes32 representation of the roles +|roles|bytes32|bytes32 representation of the held roles ### `hasInheritedUserRole` @@ -1090,8 +1107,9 @@ Set new colony architecture role. Can be called by root role or architecture rol ### `setExpenditureClaimDelay` -Set the claim delay on an expenditure slot. Can only be called by Arbitration role. +DEPRECATED Set the claim delay on an expenditure slot. Can only be called by Arbitration role. +*Note: This is now deprecated and will be removed in a future version* **Parameters** @@ -1121,9 +1139,9 @@ Set the token payout on an expenditure slot. Can only be called by expenditure o ### `setExpenditurePayoutModifier` -Set the payout modifier on an expenditure slot. Can only be called by Arbitration role. +DEPRECATED Set the payout modifier on an expenditure slot. Can only be called by Arbitration role. -*Note: Note that when determining payouts the payoutModifier is incremented by WAD and converted into payoutScalar* +*Note: This is now deprecated and will be removed in a future version* **Parameters** @@ -1176,9 +1194,9 @@ Set arbitrary state on an expenditure slot. Can only be called by Arbitration ro |_permissionDomainId|uint256|The domainId in which I have the permission to take this action |_childSkillIndex|uint256|The index that the `_domainId` is relative to `_permissionDomainId`, (only used if `_permissionDomainId` is different to `_domainId`) |_id|uint256|Expenditure identifier -|_slot|uint256|Number of the top-level storage slot -|_mask|bool[]|Array of booleans indicated whether a key is a mapping (F) or offset (T). -|_keys|bytes32[]|Array of additional keys (mappings & offsets) +|_storageSlot|uint256|Number of the top-level storage slot (25, 26, or 27) +|_mask|bool[]|Array of booleans indicated whether a key is a mapping (F) or an array index (T). +|_keys|bytes32[]|Array of additional keys (for mappings & arrays) |_value|bytes32|Value to set at location @@ -1471,6 +1489,7 @@ Updates the expenditure owner. Can only be called by expenditure owner. DEPRECATED Updates the expenditure owner. Can only be called by Arbitration role. +*Note: This is now deprecated and will be removed in a future version* **Parameters** diff --git a/helpers/task-review-signing.js b/helpers/task-review-signing.js index 99fbe7cea7..96f4893f6e 100644 --- a/helpers/task-review-signing.js +++ b/helpers/task-review-signing.js @@ -1,8 +1,8 @@ -import { soliditySha3, padLeft, isBN } from "web3-utils"; +import { soliditySha3, padLeft } from "web3-utils"; import { hashPersonalMessage, ecsign } from "ethereumjs-util"; import fs from "fs"; import { ethers } from "ethers"; -import { BigNumber } from "bignumber.js"; +import { encodeTxData } from "./test-helper"; export async function executeSignedTaskChange({ colony, taskId, functionName, signers, privKeys, sigTypes, args }) { const { sigV, sigR, sigS, txData } = await getSigsAndTransactionData({ colony, taskId, functionName, signers, privKeys, sigTypes, args }); @@ -17,22 +17,8 @@ export async function executeSignedRoleAssignment({ colony, taskId, functionName export async function getSigsAndTransactionData({ colony, taskId, functionName, signers, privKeys, sigTypes, args }) { // We have to pass in an ethers BN because of https://github.com/ethereum/web3.js/issues/1920 // and https://github.com/ethereum/web3.js/issues/2077 + const txData = await encodeTxData(colony, functionName, args); const ethersBNTaskId = ethers.BigNumber.from(taskId.toString()); - const convertedArgs = []; - args.forEach((arg) => { - if (Number.isInteger(arg)) { - const convertedArg = ethers.BigNumber.from(arg); - convertedArgs.push(convertedArg); - } else if (isBN(arg) || BigNumber.isBigNumber(arg)) { - // Can use isBigNumber from utils once https://github.com/ethereum/web3.js/issues/2835 sorted - const convertedArg = ethers.BigNumber.from(arg.toString()); - convertedArgs.push(convertedArg); - } else { - convertedArgs.push(arg); - } - }); - - const txData = await colony.contract.methods[functionName](...convertedArgs).encodeABI(); const sigsPromises = sigTypes.map((type, i) => { let privKey = []; if (privKeys) { diff --git a/helpers/test-helper.js b/helpers/test-helper.js index 85b3f1110d..3ccca4001c 100644 --- a/helpers/test-helper.js +++ b/helpers/test-helper.js @@ -1,8 +1,10 @@ /* globals artifacts */ import shortid from "shortid"; import chai from "chai"; -import { asciiToHex } from "web3-utils"; +import { asciiToHex, isBN } from "web3-utils"; import BN from "bn.js"; +import { ethers } from "ethers"; +import { BigNumber } from "bignumber.js"; import { UINT256_MAX, MIN_STAKE, MINING_CYCLE_DURATION, DEFAULT_STAKE, SUBMITTER_ONLY_WINDOW } from "./constants"; @@ -827,6 +829,25 @@ export async function getWaitForNSubmissionsPromise(repCycleEthers, rootHash, nL }); } +export async function encodeTxData(colony, functionName, args) { + const convertedArgs = []; + args.forEach((arg) => { + if (Number.isInteger(arg)) { + const convertedArg = ethers.BigNumber.from(arg); + convertedArgs.push(convertedArg); + } else if (isBN(arg) || BigNumber.isBigNumber(arg)) { + // Can use isBigNumber from utils once https://github.com/ethereum/web3.js/issues/2835 sorted + const convertedArg = ethers.BigNumber.from(arg.toString()); + convertedArgs.push(convertedArg); + } else { + convertedArgs.push(arg); + } + }); + + const txData = await colony.contract.methods[functionName](...convertedArgs).encodeABI(); + return txData; +} + export async function getRewardClaimSquareRootsAndProofs(client, tokenLocking, colony, payoutId, userAddress) { const payout = await colony.getRewardPayoutInfo(payoutId); @@ -858,3 +879,7 @@ export async function getRewardClaimSquareRootsAndProofs(client, tokenLocking, c return { squareRoots, userProof }; } + +export function bn2bytes32(x, size = 64) { + return `0x${x.toString(16, size)}`; +} diff --git a/scripts/check-recovery.js b/scripts/check-recovery.js index 774f43690b..8308ac101c 100644 --- a/scripts/check-recovery.js +++ b/scripts/check-recovery.js @@ -46,6 +46,8 @@ walkSync("./contracts/").forEach((contractName) => { "contracts/extensions/FundingQueueFactory.sol", "contracts/extensions/OneTxPayment.sol", "contracts/extensions/OneTxPaymentFactory.sol", + "contracts/extensions/VotingReputation.sol", + "contracts/extensions/VotingReputationFactory.sol", "contracts/gnosis/MultiSigWallet.sol", "contracts/patriciaTree/Bits.sol", "contracts/patriciaTree/Data.sol", diff --git a/scripts/check-storage.js b/scripts/check-storage.js index ce02762b2b..0d2a44b653 100644 --- a/scripts/check-storage.js +++ b/scripts/check-storage.js @@ -30,6 +30,8 @@ walkSync("./contracts/").forEach((contractName) => { "contracts/extensions/FundingQueueFactory.sol", "contracts/extensions/OneTxPayment.sol", "contracts/extensions/OneTxPaymentFactory.sol", + "contracts/extensions/VotingReputation.sol", + "contracts/extensions/VotingReputationFactory.sol", "contracts/gnosis/MultiSigWallet.sol", // Not directly used by any colony contracts "contracts/patriciaTree/PatriciaTreeBase.sol", // Only used by mining clients "contracts/reputationMiningCycle/ReputationMiningCycleStorage.sol", diff --git a/test-smoke/colony-storage-consistent.js b/test-smoke/colony-storage-consistent.js index 8576618507..903f4e6c2b 100644 --- a/test-smoke/colony-storage-consistent.js +++ b/test-smoke/colony-storage-consistent.js @@ -153,15 +153,15 @@ contract("Contract Storage", (accounts) => { console.log("miningCycleStateHash:", miningCycleAccount.stateRoot.toString("hex")); console.log("tokenLockingStateHash:", tokenLockingAccount.stateRoot.toString("hex")); - expect(colonyNetworkAccount.stateRoot.toString("hex")).to.equal("0941ada3434f80dfd130d0a2dc07fbc2a13b73e415f14e650bb725a9089a061f"); + expect(colonyNetworkAccount.stateRoot.toString("hex")).to.equal("4795c6cf36580719d2b3122e8a2d314024e5eb67ef0925dc35c5bbbcb26e20c9"); - expect(colonyAccount.stateRoot.toString("hex")).to.equal("f015594ef3fa0c15991fa41d255cfb7709f477545021b8fba487a50f6e8b404a"); + expect(colonyAccount.stateRoot.toString("hex")).to.equal("d11be7ccfed823de8fff1713f0ed3c3cc25572ab32d3a05db8d02e28b6b19271"); - expect(metaColonyAccount.stateRoot.toString("hex")).to.equal("33454eeb259439cf54a923c76de531d18954bdafcf29a6ccf0be586a73a7dbd5"); + expect(metaColonyAccount.stateRoot.toString("hex")).to.equal("004cce93f8bca95ddf05b7737bc758804c0d200a361638c372910849f6ca9b63"); - expect(miningCycleAccount.stateRoot.toString("hex")).to.equal("9b743931645356d469af52165654a497ee4af95ec1029601d10162d5d2d377c0"); + expect(miningCycleAccount.stateRoot.toString("hex")).to.equal("47ed02166271709fee6816f42d511e3d0c56e4ee5fc1f2e24c5f05a3954d0292"); - expect(tokenLockingAccount.stateRoot.toString("hex")).to.equal("90f687f776283dc8c84d7de3e9d233974cdf218e2e51536643d125ae0ae43ebf"); + expect(tokenLockingAccount.stateRoot.toString("hex")).to.equal("97a15b06a12c2300869568a1b32f6f60c9b87d0102ee5de7f52290b49c0eb891"); }); }); }); diff --git a/test/contracts-network/colony-expenditure.js b/test/contracts-network/colony-expenditure.js index 505aaaebdd..eef6a2d01d 100644 --- a/test/contracts-network/colony-expenditure.js +++ b/test/contracts-network/colony-expenditure.js @@ -4,7 +4,7 @@ import bnChai from "bn-chai"; import { BN } from "bn.js"; import { UINT256_MAX, INT128_MAX, WAD, SECONDS_PER_DAY, MAX_PAYOUT, GLOBAL_SKILL_ID } from "../../helpers/constants"; -import { checkErrorRevert, getTokenArgs, forwardTime, getBlockTime } from "../../helpers/test-helper"; +import { checkErrorRevert, getTokenArgs, forwardTime, getBlockTime, bn2bytes32 } from "../../helpers/test-helper"; import { fundColonyWithTokens, setupRandomColony } from "../../helpers/test-data-generator"; const { expect } = chai; @@ -27,6 +27,9 @@ contract("Colony Expenditure", (accounts) => { const CANCELLED = 1; const FINALIZED = 2; + const MAPPING = false; + const ARRAY = true; + const RECIPIENT = accounts[3]; const ADMIN = accounts[4]; const ARBITRATOR = accounts[5]; @@ -502,14 +505,18 @@ contract("Colony Expenditure", (accounts) => { it("should delay claims by claimDelay", async () => { await colony.setExpenditurePayout(expenditureId, SLOT0, token.address, WAD, { from: ADMIN }); - await colony.setExpenditureClaimDelay(1, UINT256_MAX, expenditureId, SLOT0, SECONDS_PER_DAY); + + const day32 = bn2bytes32(new BN(SECONDS_PER_DAY)); + await colony.setExpenditureState(1, UINT256_MAX, expenditureId, EXPENDITURES_SLOT, [ARRAY], [bn2bytes32(new BN(4))], day32); + await colony.setExpenditureState(1, UINT256_MAX, expenditureId, EXPENDITURESLOTS_SLOT, [MAPPING, ARRAY], ["0x0", bn2bytes32(new BN(1))], day32); const expenditure = await colony.getExpenditure(expenditureId); await colony.moveFundsBetweenPots(1, UINT256_MAX, UINT256_MAX, domain1.fundingPotId, expenditure.fundingPotId, WAD, token.address); await colony.finalizeExpenditure(expenditureId, { from: ADMIN }); await checkErrorRevert(colony.claimExpenditurePayout(expenditureId, SLOT0, token.address), "colony-expenditure-cannot-claim"); - + await forwardTime(SECONDS_PER_DAY, this); + await checkErrorRevert(colony.claimExpenditurePayout(expenditureId, SLOT0, token.address), "colony-expenditure-cannot-claim"); await forwardTime(SECONDS_PER_DAY, this); await colony.claimExpenditurePayout(expenditureId, SLOT0, token.address); }); @@ -552,20 +559,13 @@ contract("Colony Expenditure", (accounts) => { describe("when arbitrating expenditures", () => { let expenditureId; - const MAPPING = false; - const OFFSET = true; - - function bn2bytes32(x, size = 64) { - return `0x${x.toString(16, size)}`; - } - beforeEach(async () => { await colony.makeExpenditure(1, UINT256_MAX, 1, { from: ADMIN }); expenditureId = await colony.getExpenditureCount(); }); it("should allow arbitration users to update expenditure status/owner", async () => { - const mask = [OFFSET]; + const mask = [ARRAY]; const keys = [bn2bytes32(new BN(0))]; const value = bn2bytes32(new BN(USER.slice(2), 16), 62) + new BN(CANCELLED).toString(16, 2); @@ -577,7 +577,7 @@ contract("Colony Expenditure", (accounts) => { }); it("should not allow arbitration users to update expenditure fundingPotId", async () => { - const mask = [OFFSET]; + const mask = [ARRAY]; const keys = [bn2bytes32(new BN(1))]; const value = "0x0"; @@ -588,7 +588,7 @@ contract("Colony Expenditure", (accounts) => { }); it("should not allow arbitration users to update expenditure domainId", async () => { - const mask = [OFFSET]; + const mask = [ARRAY]; const keys = [bn2bytes32(new BN(2))]; const value = "0x0"; @@ -599,7 +599,7 @@ contract("Colony Expenditure", (accounts) => { }); it("should allow arbitration users to update expenditure finalizedTimestamp", async () => { - const mask = [OFFSET]; + const mask = [ARRAY]; const keys = [bn2bytes32(new BN(3))]; const value = bn2bytes32(new BN(100)); @@ -610,8 +610,8 @@ contract("Colony Expenditure", (accounts) => { }); it("should allow arbitration users to update expenditure slot recipient", async () => { - const mask = [MAPPING]; - const keys = ["0x0"]; + const mask = [MAPPING, ARRAY]; + const keys = ["0x0", "0x0"]; const value = bn2bytes32(new BN(USER.slice(2), 16)); await colony.setExpenditureState(1, UINT256_MAX, expenditureId, EXPENDITURESLOTS_SLOT, mask, keys, value, { from: ARBITRATOR }); @@ -621,7 +621,7 @@ contract("Colony Expenditure", (accounts) => { }); it("should allow arbitration users to update expenditure slot claimDelay", async () => { - const mask = [MAPPING, OFFSET]; + const mask = [MAPPING, ARRAY]; const keys = ["0x0", bn2bytes32(new BN(1))]; const value = bn2bytes32(new BN(100)); @@ -632,7 +632,7 @@ contract("Colony Expenditure", (accounts) => { }); it("should allow arbitration users to update expenditure slot payoutModifier", async () => { - const mask = [MAPPING, OFFSET]; + const mask = [MAPPING, ARRAY]; const keys = ["0x0", bn2bytes32(new BN(2))]; const value = bn2bytes32(new BN(100)); @@ -645,7 +645,7 @@ contract("Colony Expenditure", (accounts) => { it("should allow arbitration users to update expenditure slot skills", async () => { await colony.setExpenditureSkill(expenditureId, 0, GLOBAL_SKILL_ID, { from: ADMIN }); - const mask = [MAPPING, OFFSET, OFFSET]; + const mask = [MAPPING, ARRAY, ARRAY]; const keys = ["0x0", bn2bytes32(new BN(3)), bn2bytes32(new BN(0))]; const value = bn2bytes32(new BN(100)); @@ -663,14 +663,14 @@ contract("Colony Expenditure", (accounts) => { expect(expenditureSlot.skills[0]).to.eq.BN(GLOBAL_SKILL_ID); // Lengthen the array - let mask = [MAPPING, OFFSET]; + let mask = [MAPPING, ARRAY]; let keys = ["0x0", bn2bytes32(new BN(3))]; let value = bn2bytes32(new BN(2)); await colony.setExpenditureState(1, UINT256_MAX, expenditureId, EXPENDITURESLOTS_SLOT, mask, keys, value, { from: ARBITRATOR }); // Set the new skillId - mask = [MAPPING, OFFSET, OFFSET]; + mask = [MAPPING, ARRAY, ARRAY]; keys = ["0x0", bn2bytes32(new BN(3)), bn2bytes32(new BN(1))]; value = bn2bytes32(new BN(100)); @@ -682,7 +682,7 @@ contract("Colony Expenditure", (accounts) => { expect(expenditureSlot.skills[1]).to.eq.BN(100); // Shrink the array - mask = [MAPPING, OFFSET]; + mask = [MAPPING, ARRAY]; keys = ["0x0", bn2bytes32(new BN(3))]; value = bn2bytes32(new BN(1)); @@ -704,19 +704,8 @@ contract("Colony Expenditure", (accounts) => { expect(expenditureSlotPayout).to.eq.BN(100); }); - it("should not allow arbitration users to pass empty keys", async () => { - const mask = []; - const keys = []; - const value = "0x0"; - - await checkErrorRevert( - colony.setExpenditureState(1, UINT256_MAX, expenditureId, EXPENDITURES_SLOT, mask, keys, value, { from: ARBITRATOR }), - "colony-expenditure-no-keys" - ); - }); - it("should not allow arbitration users to pass invalid slots", async () => { - const mask = [OFFSET]; + const mask = [ARRAY]; const keys = ["0x0"]; const value = "0x0"; const invalidSlot = 10; @@ -739,8 +728,8 @@ contract("Colony Expenditure", (accounts) => { }); it("should not allow arbitration users to pass offsets greater than 1024", async () => { - const mask = [OFFSET]; - const keys = [bn2bytes32(new BN(1025))]; + const mask = [MAPPING, ARRAY, ARRAY]; + const keys = ["0x0", bn2bytes32(new BN(3)), bn2bytes32(new BN(1025))]; const value = bn2bytes32(new BN(100)); await checkErrorRevert( diff --git a/test/extensions/voting-rep.js b/test/extensions/voting-rep.js new file mode 100644 index 0000000000..9d2069d26d --- /dev/null +++ b/test/extensions/voting-rep.js @@ -0,0 +1,1751 @@ +/* globals artifacts */ + +import BN from "bn.js"; +import chai from "chai"; +import bnChai from "bn-chai"; +import shortid from "shortid"; +import { ethers } from "ethers"; +import { soliditySha3 } from "web3-utils"; + +import { UINT256_MAX, WAD, MINING_CYCLE_DURATION, SECONDS_PER_DAY, DEFAULT_STAKE, SUBMITTER_ONLY_WINDOW } from "../../helpers/constants"; +import { + checkErrorRevert, + makeReputationKey, + makeReputationValue, + getActiveRepCycle, + forwardTime, + encodeTxData, + bn2bytes32, +} from "../../helpers/test-helper"; + +import { + setupColonyNetwork, + setupMetaColonyWithLockedCLNYToken, + setupRandomColony, + giveUserCLNYTokensAndStake, +} from "../../helpers/test-data-generator"; + +import PatriciaTree from "../../packages/reputation-miner/patricia"; + +const { expect } = chai; +chai.use(bnChai(web3.utils.BN)); + +const TokenLocking = artifacts.require("TokenLocking"); +const IReputationMiningCycle = artifacts.require("IReputationMiningCycle"); +const VotingReputation = artifacts.require("VotingReputation"); +const VotingReputationFactory = artifacts.require("VotingReputationFactory"); + +contract("Voting Reputation", (accounts) => { + let colony; + let token; + let domain1; + let domain2; + let domain3; + let metaColony; + let colonyNetwork; + let tokenLocking; + + let voting; + let votingFactory; + + let reputationTree; + + let domain1Key; + let domain1Value; + let domain1Mask; + let domain1Siblings; + + let user0Key; + let user0Value; + let user0Mask; + let user0Siblings; + + let user1Key; + let user1Value; + let user1Mask; + let user1Siblings; + + const TOTAL_STAKE_FRACTION = WAD.divn(1000); // 0.1 % + const USER_MIN_STAKE_FRACTION = WAD.divn(10); // 10 % + + const MAX_VOTE_FRACTION = WAD.divn(10).muln(8); // 80 % + const VOTER_REWARD_FRACTION = WAD.divn(10); // 10 % + + const STAKE_PERIOD = SECONDS_PER_DAY * 3; + const SUBMIT_PERIOD = SECONDS_PER_DAY * 2; + const REVEAL_PERIOD = SECONDS_PER_DAY * 2; + const ESCALATION_PERIOD = SECONDS_PER_DAY; + + const USER0 = accounts[0]; + const USER1 = accounts[1]; + const USER2 = accounts[2]; + const MINER = accounts[5]; + + const SALT = soliditySha3(shortid.generate()); + const FAKE = soliditySha3(shortid.generate()); + + const NAY = 0; + const YAY = 1; + + // const NULL = 0; + const STAKING = 1; + const SUBMIT = 2; + // const REVEAL = 3; + // const CLOSED = 4; + const EXECUTABLE = 5; + // const EXECUTED = 6; + const FAILED = 7; + + const ADDRESS_ZERO = ethers.constants.AddressZero; + const REQUIRED_STAKE = WAD.muln(3).divn(1000); + const WAD32 = bn2bytes32(WAD); + const HALF = WAD.divn(2); + const YEAR = SECONDS_PER_DAY * 365; + + before(async () => { + colonyNetwork = await setupColonyNetwork(); + ({ metaColony } = await setupMetaColonyWithLockedCLNYToken(colonyNetwork)); + + await giveUserCLNYTokensAndStake(colonyNetwork, MINER, DEFAULT_STAKE); + await colonyNetwork.initialiseReputationMining(); + await colonyNetwork.startNextCycle(); + + const tokenLockingAddress = await colonyNetwork.getTokenLocking(); + tokenLocking = await TokenLocking.at(tokenLockingAddress); + + votingFactory = await VotingReputationFactory.new(); + }); + + beforeEach(async () => { + ({ colony, token } = await setupRandomColony(colonyNetwork)); + + // 1 => { 2, 3 } + await colony.addDomain(1, UINT256_MAX, 1); + await colony.addDomain(1, UINT256_MAX, 1); + domain1 = await colony.getDomain(1); + domain2 = await colony.getDomain(2); + domain3 = await colony.getDomain(3); + + await votingFactory.deployExtension(colony.address); + const votingAddress = await votingFactory.deployedExtensions(colony.address); + voting = await VotingReputation.at(votingAddress); + + await voting.initialise( + TOTAL_STAKE_FRACTION, + VOTER_REWARD_FRACTION, + USER_MIN_STAKE_FRACTION, + MAX_VOTE_FRACTION, + STAKE_PERIOD, + SUBMIT_PERIOD, + REVEAL_PERIOD, + ESCALATION_PERIOD + ); + + await colony.setArbitrationRole(1, UINT256_MAX, voting.address, 1, true); + await colony.setAdministrationRole(1, UINT256_MAX, voting.address, 1, true); + + await token.mint(USER0, WAD); + await token.mint(USER1, WAD); + await token.mint(USER2, WAD); + await token.approve(tokenLocking.address, WAD, { from: USER0 }); + await token.approve(tokenLocking.address, WAD, { from: USER1 }); + await token.approve(tokenLocking.address, WAD, { from: USER2 }); + await tokenLocking.deposit(token.address, WAD, { from: USER0 }); + await tokenLocking.deposit(token.address, WAD, { from: USER1 }); + await tokenLocking.deposit(token.address, WAD, { from: USER2 }); + await colony.approveStake(voting.address, 1, WAD, { from: USER0 }); + await colony.approveStake(voting.address, 1, WAD, { from: USER1 }); + await colony.approveStake(voting.address, 1, WAD, { from: USER2 }); + + reputationTree = new PatriciaTree(); + await reputationTree.insert( + makeReputationKey(colony.address, domain1.skillId), // Colony total + makeReputationValue(WAD.muln(3), 1) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain1.skillId, USER0), // User0 + makeReputationValue(WAD, 2) + ); + await reputationTree.insert( + makeReputationKey(metaColony.address, domain1.skillId, USER0), // Wrong colony + makeReputationValue(WAD, 3) + ); + await reputationTree.insert( + makeReputationKey(colony.address, 1234, USER0), // Wrong skill + makeReputationValue(WAD, 4) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain1.skillId, USER1), // User1 (and 2x value) + makeReputationValue(WAD.muln(2), 5) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain2.skillId), // Colony total, domain 2 + makeReputationValue(WAD, 6) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain3.skillId), // Colony total, domain 3 + makeReputationValue(WAD.muln(3), 7) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain1.skillId, USER2), // User2, very little rep + makeReputationValue(REQUIRED_STAKE.subn(1), 8) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain2.skillId, USER0), // User0, domain 2 + makeReputationValue(WAD.divn(3), 9) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain2.skillId, USER1), // User1, domain 2 + makeReputationValue(WAD.divn(3).muln(2), 10) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain3.skillId, USER0), // User0, domain 3 + makeReputationValue(WAD, 11) + ); + await reputationTree.insert( + makeReputationKey(colony.address, domain3.skillId, USER1), // User1, domain 3 + makeReputationValue(WAD.muln(2), 12) + ); + + domain1Key = makeReputationKey(colony.address, domain1.skillId); + domain1Value = makeReputationValue(WAD.muln(3), 1); + [domain1Mask, domain1Siblings] = await reputationTree.getProof(domain1Key); + + user0Key = makeReputationKey(colony.address, domain1.skillId, USER0); + user0Value = makeReputationValue(WAD, 2); + [user0Mask, user0Siblings] = await reputationTree.getProof(user0Key); + + user1Key = makeReputationKey(colony.address, domain1.skillId, USER1); + user1Value = makeReputationValue(WAD.muln(2), 5); + [user1Mask, user1Siblings] = await reputationTree.getProof(user1Key); + + const rootHash = await reputationTree.getRootHash(); + const repCycle = await getActiveRepCycle(colonyNetwork); + await forwardTime(MINING_CYCLE_DURATION, this); + await repCycle.submitRootHash(rootHash, 0, "0x00", 10, { from: MINER }); + await forwardTime(SUBMITTER_ONLY_WINDOW + 1, this); + await repCycle.confirmNewHash(0); + }); + + function hashExpenditureSlot(action) { + const preamble = 2 + 8 + 64 * 2; + return soliditySha3(`0x${action.slice(preamble, preamble + 64 * 4)}${"0".repeat(64)}${action.slice(preamble + 64 * 5, action.length)}`); + } + + describe("deploying the extension", async () => { + it("can install the extension factory once if root and uninstall", async () => { + ({ colony } = await setupRandomColony(colonyNetwork)); + await checkErrorRevert(votingFactory.deployExtension(colony.address, { from: USER1 }), "colony-extension-user-not-root"); + await votingFactory.deployExtension(colony.address, { from: USER0 }); + await checkErrorRevert(votingFactory.deployExtension(colony.address, { from: USER0 }), "colony-extension-already-deployed"); + await votingFactory.removeExtension(colony.address, { from: USER0 }); + }); + + it("can query for initisalisation values", async () => { + const totalStakeFraction = await voting.getTotalStakeFraction(); + const voterRewardFraction = await voting.getVoterRewardFraction(); + const userMinStakeFraction = await voting.getUserMinStakeFraction(); + const maxVoteFraction = await voting.getMaxVoteFraction(); + + const stakePeriod = await voting.getStakePeriod(); + const submitPeriod = await voting.getSubmitPeriod(); + const revealPeriod = await voting.getRevealPeriod(); + const escalationPeriod = await voting.getEscalationPeriod(); + + expect(totalStakeFraction).to.eq.BN(TOTAL_STAKE_FRACTION); + expect(voterRewardFraction).to.eq.BN(VOTER_REWARD_FRACTION); + expect(userMinStakeFraction).to.eq.BN(USER_MIN_STAKE_FRACTION); + expect(maxVoteFraction).to.eq.BN(MAX_VOTE_FRACTION); + + expect(stakePeriod).to.eq.BN(STAKE_PERIOD); + expect(submitPeriod).to.eq.BN(SUBMIT_PERIOD); + expect(revealPeriod).to.eq.BN(REVEAL_PERIOD); + expect(escalationPeriod).to.eq.BN(ESCALATION_PERIOD); + }); + + it("can deprecate the extension if root", async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + + // Must be root + await checkErrorRevert(voting.deprecate({ from: USER2 }), "voting-rep-user-not-root"); + + await voting.deprecate(); + + // Cant make new motions! + await checkErrorRevert( + voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings), + "voting-rep-not-active" + ); + }); + + it("cannot initialise twice or if not root", async () => { + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD, YEAR, YEAR, YEAR, YEAR), "voting-rep-already-initialised"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD, YEAR, YEAR, YEAR, YEAR, { from: USER2 }), "voting-rep-user-not-root"); + }); + + it("cannot initialise with invalid values", async () => { + await votingFactory.removeExtension(colony.address, { from: USER0 }); + await votingFactory.deployExtension(colony.address); + const votingAddress = await votingFactory.deployedExtensions(colony.address); + voting = await VotingReputation.at(votingAddress); + + await checkErrorRevert(voting.initialise(HALF.addn(1), HALF, WAD, WAD, YEAR, YEAR, YEAR, YEAR), "voting-rep-greater-than-half-wad"); + await checkErrorRevert(voting.initialise(HALF, HALF.addn(1), WAD, WAD, YEAR, YEAR, YEAR, YEAR), "voting-rep-greater-than-half-wad"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD.addn(1), WAD, YEAR, YEAR, YEAR, YEAR), "voting-rep-greater-than-wad"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD.addn(1), YEAR, YEAR, YEAR, YEAR), "voting-rep-greater-than-wad"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD, YEAR + 1, YEAR, YEAR, YEAR), "voting-rep-period-too-long"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD, YEAR, YEAR + 1, YEAR, YEAR), "voting-rep-period-too-long"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD, YEAR, YEAR, YEAR + 1, YEAR), "voting-rep-period-too-long"); + await checkErrorRevert(voting.initialise(HALF, HALF, WAD, WAD, YEAR, YEAR, YEAR, YEAR + 1), "voting-rep-period-too-long"); + + await voting.initialise(HALF, HALF, WAD, WAD, YEAR, YEAR, YEAR, YEAR); + }); + }); + + describe("creating motions", async () => { + it("can create a root motion", async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + + const motionId = await voting.getMotionCount(); + const motion = await voting.getMotion(motionId); + expect(motion.skillId).to.eq.BN(domain1.skillId); + }); + + it("can create a domain motion in the root domain", async () => { + // Create motion in domain of action (1) + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + + const motionId = await voting.getMotionCount(); + const motion = await voting.getMotion(motionId); + expect(motion.skillId).to.eq.BN(domain1.skillId); + }); + + it("can create a domain motion in a child domain", async () => { + const key = makeReputationKey(colony.address, domain2.skillId); + const value = makeReputationValue(WAD, 6); + const [mask, siblings] = await reputationTree.getProof(key); + + // Create motion in domain of action (2) + const action = await encodeTxData(colony, "makeTask", [1, 0, FAKE, 2, 0, 0]); + await voting.createDomainMotion(2, UINT256_MAX, action, key, value, mask, siblings); + + const motionId = await voting.getMotionCount(); + const motion = await voting.getMotion(motionId); + expect(motion.skillId).to.eq.BN(domain2.skillId); + }); + + it("can externally escalate a domain motion", async () => { + // Create motion in parent domain (1) of action (2) + const action = await encodeTxData(colony, "makeTask", [1, 0, FAKE, 2, 0, 0]); + await voting.createDomainMotion(1, 0, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + + const motionId = await voting.getMotionCount(); + const motion = await voting.getMotion(motionId); + expect(motion.skillId).to.eq.BN(domain1.skillId); + }); + + it("can create a motion with an alternative target", async () => { + const action = await encodeTxData(colony, "makeTask", [1, 0, FAKE, 2, 0, 0]); + await voting.createRootMotion(voting.address, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + }); + + it("cannot create a motion with the colony as the alternative target", async () => { + const action = await encodeTxData(colony, "makeTask", [1, 0, FAKE, 2, 0, 0]); + await checkErrorRevert( + voting.createRootMotion(colony.address, action, domain1Key, domain1Value, domain1Mask, domain1Siblings), + "voting-rep-alt-target-cannot-be-base-colony" + ); + }); + + it("cannot create a domain motion with a non-domain-permissioned function as the action", async () => { + // Unpermissioned action + const action1 = await encodeTxData(colony, "claimColonyFunds", [token.address]); + + // Root permissioned action + const action2 = await encodeTxData(colony, "upgrade", [2]); + + await checkErrorRevert( + voting.createDomainMotion(1, UINT256_MAX, action1, domain1Key, domain1Value, domain1Mask, domain1Siblings), + "voting-rep-invalid-function" + ); + + await checkErrorRevert( + voting.createDomainMotion(1, UINT256_MAX, action2, domain1Key, domain1Value, domain1Mask, domain1Siblings), + "voting-rep-invalid-function" + ); + }); + + it("cannot externally escalate a domain motion with an invalid domain proof", async () => { + const key = makeReputationKey(colony.address, domain3.skillId); + const value = makeReputationValue(WAD.muln(3), 7); + const [mask, siblings] = await reputationTree.getProof(key); + + // Provide proof for (3) instead of (2) + const action = await encodeTxData(colony, "makeTask", [1, 0, FAKE, 2, 0, 0]); + await checkErrorRevert(voting.createDomainMotion(1, 1, action, key, value, mask, siblings), "voting-rep-invalid-domain-id"); + }); + }); + + describe("staking on motions", async () => { + let motionId; + + beforeEach(async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + }); + + it("can stake on a motion", async () => { + const half = REQUIRED_STAKE.divn(2); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, half, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, half, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + const motion = await voting.getMotion(motionId); + expect(motion.stakes[0]).to.be.zero; + expect(motion.stakes[1]).to.eq.BN(REQUIRED_STAKE); + + const stake0 = await voting.getStake(motionId, USER0, YAY); + const stake1 = await voting.getStake(motionId, USER1, YAY); + expect(stake0).to.eq.BN(half); + expect(stake1).to.eq.BN(half); + }); + + it("can update the motion states correctly", async () => { + let motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(STAKING); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(STAKING); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(SUBMIT); + }); + + it("can stake even with a locked token", async () => { + await token.mint(colony.address, WAD); + await colony.setRewardInverse(100); + await colony.claimColonyFunds(token.address); + await colony.startNextRewardPayout(token.address, domain1Key, domain1Value, domain1Mask, domain1Siblings); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + const lock = await tokenLocking.getUserLock(token.address, voting.address); + expect(lock.balance).to.eq.BN(REQUIRED_STAKE.muln(2)); + }); + + it("cannot stake on a non-existent motion", async () => { + await checkErrorRevert( + voting.stakeMotion(0, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-motion-not-staking" + ); + }); + + it("cannot stake 0", async () => { + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, 0, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-bad-amount" + ); + }); + + it("cannot stake a nonexistent side", async () => { + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, 2, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-bad-vote" + ); + }); + + it("cannot stake less than the minStake, unless there is less than minStake to go", async () => { + const minStake = REQUIRED_STAKE.divn(10); + + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, minStake.subn(1), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-insufficient-stake" + ); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, minStake, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + // Unless there's less than the minStake to go! + + const stake = REQUIRED_STAKE.sub(minStake.muln(2)).addn(1); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, stake, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, minStake.subn(1), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + }); + + it("can update the expenditure globalClaimDelay if voting on expenditure state", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + await colony.finalizeExpenditure(expenditureId); + + // Set finalizedTimestamp to WAD + const action = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], [bn2bytes32(new BN(3))], WAD32]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + let expenditureMotionCount; + expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId)); + expect(expenditureMotionCount).to.be.zero; + + let expenditure; + expenditure = await colony.getExpenditure(expenditureId); + expect(expenditure.globalClaimDelay).to.be.zero; + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId)); + expect(expenditureMotionCount).to.eq.BN(1); + + expenditure = await colony.getExpenditure(expenditureId); + expect(expenditure.globalClaimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + await checkErrorRevert(colony.claimExpenditurePayout(expenditureId, 0, token.address), "colony-expenditure-cannot-claim"); + }); + + it("does not update the expenditure globalClaimDelay if the target is another colony", async () => { + const { colony: otherColony } = await setupRandomColony(colonyNetwork); + await otherColony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await otherColony.getExpenditureCount(); + await otherColony.finalizeExpenditure(expenditureId); + + // Set finalizedTimestamp to WAD + const action = await encodeTxData(otherColony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 25, + [true], + [bn2bytes32(new BN(3))], + WAD32, + ]); + + await voting.createRootMotion(otherColony.address, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + const expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId)); + expect(expenditureMotionCount).to.be.zero; + + const expenditure = await otherColony.getExpenditure(expenditureId); + expect(expenditure.globalClaimDelay).to.be.zero; + }); + + it("can update the expenditure slot claimDelay if voting on expenditure slot state", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + await colony.finalizeExpenditure(expenditureId); + + // Set payoutModifier to 1 for expenditure slot 0 + const action = await encodeTxData(colony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 26, + [false, true], + ["0x0", bn2bytes32(new BN(2))], + WAD32, + ]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + let expenditureMotionCount; + expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId, 0)); + expect(expenditureMotionCount).to.be.zero; + + let expenditureSlot; + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.be.zero; + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId, 0)); + expect(expenditureMotionCount).to.eq.BN(1); + + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + await checkErrorRevert(colony.claimExpenditurePayout(expenditureId, 0, token.address), "colony-expenditure-cannot-claim"); + }); + + it("can update the expenditure slot claimDelay if voting on expenditure payout state", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + await colony.finalizeExpenditure(expenditureId); + + // Set payout to WAD for expenditure slot 0, internal token + const action = await encodeTxData(colony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 27, + [false, false], + ["0x0", bn2bytes32(new BN(token.address.slice(2), 16))], + WAD32, + ]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + let expenditureMotionCount; + expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId, 0)); + expect(expenditureMotionCount).to.be.zero; + + let expenditureSlot; + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.be.zero; + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + expenditureMotionCount = await voting.getExpenditureMotionCount(soliditySha3(expenditureId, 0)); + expect(expenditureMotionCount).to.eq.BN(1); + + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + await checkErrorRevert(colony.claimExpenditurePayout(expenditureId, 0, token.address), "colony-expenditure-cannot-claim"); + }); + + it("can update the expenditure slot claimDelay if voting on multiple expenditure states", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + await colony.finalizeExpenditure(expenditureId); + + let action; + + // Motion 1 + // Set finalizedTimestamp to WAD + action = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], [bn2bytes32(new BN(3))], WAD32]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + // Motion 2 + // Set payoutModifier to 1 for expenditure slot 0 + action = await encodeTxData(colony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 26, + [false, true], + ["0x0", bn2bytes32(new BN(2))], + WAD32, + ]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + // Motion 2 + // Set payout to WAD for expenditure slot 0, internal token + action = await encodeTxData(colony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 27, + [false, false], + ["0x0", bn2bytes32(new BN(token.address.slice(2), 16))], + WAD32, + ]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + const expenditure = await colony.getExpenditure(expenditureId); + expect(expenditure.globalClaimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + const expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + await checkErrorRevert(colony.claimExpenditurePayout(expenditureId, 0, token.address), "colony-expenditure-cannot-claim"); + }); + + it("cannot update the expenditure slot claimDelay if given an invalid action", async () => { + // Create a poorly-formed action (no keys) + const action = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, 1, 0, [], [], ethers.constants.HashZero]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-expenditure-lock-failed" + ); + }); + + it("can accurately track the number of motions for a single expenditure", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + const expenditureHash = soliditySha3(expenditureId, 0); + + // Set payoutModifier to 1 for expenditure slot 0 + const action1 = await encodeTxData(colony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 26, + [false, true], + ["0x0", bn2bytes32(new BN(2))], + WAD32, + ]); + + // Set payout to WAD for expenditure slot 0, internal token + const action2 = await encodeTxData(colony, "setExpenditureState", [ + 1, + UINT256_MAX, + expenditureId, + 27, + [false, false], + ["0x0", bn2bytes32(new BN(token.address.slice(2), 16))], + WAD32, + ]); + + await voting.createDomainMotion(1, UINT256_MAX, action1, domain1Key, domain1Value, domain1Mask, domain1Siblings); + const motionId1 = await voting.getMotionCount(); + + await voting.createDomainMotion(1, UINT256_MAX, action2, domain1Key, domain1Value, domain1Mask, domain1Siblings); + const motionId2 = await voting.getMotionCount(); + + let expenditureMotionCount; + expenditureMotionCount = await voting.getExpenditureMotionCount(expenditureHash); + expect(expenditureMotionCount).to.be.zero; + + let expenditureSlot; + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.be.zero; + + await voting.stakeMotion(motionId1, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId2, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + expenditureMotionCount = await voting.getExpenditureMotionCount(expenditureHash); + expect(expenditureMotionCount).to.eq.BN(2); + + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + await forwardTime(STAKE_PERIOD, this); + await voting.finalizeMotion(motionId1); + + expenditureMotionCount = await voting.getExpenditureMotionCount(expenditureHash); + expect(expenditureMotionCount).to.eq.BN(1); + + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.eq.BN(UINT256_MAX.divn(3)); + + await voting.finalizeMotion(motionId2); + + expenditureMotionCount = await voting.getExpenditureMotionCount(expenditureHash); + expect(expenditureMotionCount).to.be.zero; + + expenditureSlot = await colony.getExpenditureSlot(expenditureId, 0); + expect(expenditureSlot.claimDelay).to.be.zero; + }); + + it("cannot stake with someone else's reputation", async () => { + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER1 }), + "voting-rep-invalid-user-address" + ); + }); + + it("cannot stake with insufficient reputation", async () => { + const user2Key = makeReputationKey(colony.address, domain1.skillId, USER2); + const user2Value = makeReputationValue(REQUIRED_STAKE.subn(1), 8); + const [user2Mask, user2Siblings] = await reputationTree.getProof(user2Key); + + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user2Key, user2Value, user2Mask, user2Siblings, { from: USER2 }), + "voting-rep-insufficient-rep" + ); + }); + + it("cannot stake once time runs out", async () => { + await forwardTime(STAKE_PERIOD, this); + + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-motion-not-staking" + ); + + await checkErrorRevert( + voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }), + "voting-rep-motion-not-staking" + ); + }); + }); + + describe("voting on motions", async () => { + let motionId; + + beforeEach(async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + }); + + it("can rate and reveal for a motion", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId, SALT, NAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + }); + + it("can tally votes from two users", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId, SALT, YAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + // See final counts + const { votes } = await voting.getMotion(motionId); + expect(votes[0]).to.be.zero; + expect(votes[1]).to.eq.BN(WAD.muln(3)); + }); + + it("can update votes, but just the last one counts", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + // Revealing first vote fails + await checkErrorRevert( + voting.revealVote(motionId, SALT, NAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-secret-no-match" + ); + + // Revealing second succeeds + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + }); + + it("can update votes, but the total reputation does not change", async () => { + let motion = await voting.getMotion(motionId); + expect(motion.repSubmitted).to.be.zero; + + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + motion = await voting.getMotion(motionId); + expect(motion.repSubmitted).to.eq.BN(WAD); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + motion = await voting.getMotion(motionId); + expect(motion.repSubmitted).to.eq.BN(WAD); + }); + + it("cannot reveal an invalid vote", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, 2), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await checkErrorRevert( + voting.revealVote(motionId, SALT, 2, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-bad-vote" + ); + }); + + it("cannot reveal a vote twice, and so cannot vote twice", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await checkErrorRevert( + voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-secret-no-match" + ); + }); + + it("can vote in two motions with two reputation states, with different proofs", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + const oldRootHash = await reputationTree.getRootHash(); + + // Update reputation state + const user0Value2 = makeReputationValue(WAD.muln(2), 2); + await reputationTree.insert(user0Key, user0Value2); + + const [domain1Mask2, domain1Siblings2] = await reputationTree.getProof(domain1Key); + const [user0Mask2, user0Siblings2] = await reputationTree.getProof(user0Key); + const [user1Mask2, user1Siblings2] = await reputationTree.getProof(user1Key); + + // Set new rootHash + const rootHash = await reputationTree.getRootHash(); + expect(oldRootHash).to.not.equal(rootHash); + + await forwardTime(MINING_CYCLE_DURATION, this); + + const repCycle = await getActiveRepCycle(colonyNetwork); + await repCycle.submitRootHash(rootHash, 0, "0x00", 10, { from: MINER }); + await forwardTime(SUBMITTER_ONLY_WINDOW + 1, this); + await repCycle.confirmNewHash(0); + + // Create new motion with new reputation state + await voting.createRootMotion(ADDRESS_ZERO, FAKE, domain1Key, domain1Value, domain1Mask2, domain1Siblings2); + const motionId2 = await voting.getMotionCount(); + await voting.stakeMotion(motionId2, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value2, user0Mask2, user0Siblings2, { from: USER0 }); + await voting.stakeMotion(motionId2, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask2, user1Siblings2, { from: USER1 }); + + await voting.submitVote(motionId2, soliditySha3(SALT, NAY), user0Key, user0Value2, user0Mask2, user0Siblings2, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId, SALT, NAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId2, SALT, NAY, user0Key, user0Value2, user0Mask2, user0Siblings2, { from: USER0 }); + }); + + it("cannot submit a vote on a non-existent motion", async () => { + await checkErrorRevert( + voting.submitVote(0, "0x0", user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-motion-not-open" + ); + }); + + it("cannot submit a null vote", async () => { + await checkErrorRevert( + voting.submitVote(motionId, "0x0", user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-invalid-secret" + ); + }); + + it("cannot submit a vote if voting is closed", async () => { + await forwardTime(SUBMIT_PERIOD, this); + + await checkErrorRevert( + voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-motion-not-open" + ); + }); + + it("cannot reveal a vote on a non-existent motion", async () => { + await forwardTime(SUBMIT_PERIOD, this); + + await checkErrorRevert( + voting.revealVote(0, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-motion-not-reveal" + ); + }); + + it("cannot reveal a vote during the submit period", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await checkErrorRevert(voting.revealVote(motionId, SALT, YAY, FAKE, FAKE, 0, [], { from: USER0 }), "voting-rep-motion-not-reveal"); + }); + + it("cannot reveal a vote after the reveal period ends", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + await forwardTime(REVEAL_PERIOD, this); + + await checkErrorRevert(voting.revealVote(motionId, SALT, NAY, FAKE, FAKE, 0, [], { from: USER0 }), "voting-rep-motion-not-reveal"); + }); + + it("cannot reveal a vote with a bad secret", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await checkErrorRevert( + voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }), + "voting-rep-secret-no-match" + ); + }); + + it("cannot reveal a vote with a bad proof", async () => { + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + // Invalid proof (wrong root hash) + await checkErrorRevert(voting.revealVote(motionId, SALT, NAY, FAKE, FAKE, 0, [], { from: USER0 }), "voting-rep-invalid-root-hash"); + + // Invalid colony address + let key, value, mask, siblings; // eslint-disable-line one-var + key = makeReputationKey(metaColony.address, domain1.skillId, USER0); + value = makeReputationValue(WAD, 3); + [mask, siblings] = await reputationTree.getProof(key); + + await checkErrorRevert( + voting.revealVote(motionId, SALT, NAY, key, value, mask, siblings, { from: USER0 }), + "voting-rep-invalid-colony-address" + ); + + // Invalid skill id + key = makeReputationKey(colony.address, 1234, USER0); + value = makeReputationValue(WAD, 4); + [mask, siblings] = await reputationTree.getProof(key); + await checkErrorRevert(voting.revealVote(motionId, SALT, NAY, key, value, mask, siblings, { from: USER0 }), "voting-rep-invalid-skill-id"); + + // Invalid user address + await checkErrorRevert( + voting.revealVote(motionId, SALT, NAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER0 }), + "voting-rep-invalid-user-address" + ); + }); + }); + + describe("executing motions", async () => { + let motionId; + + beforeEach(async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + }); + + it("cannot execute a non-existent motion", async () => { + await checkErrorRevert(voting.finalizeMotion(0), "voting-rep-motion-not-finalizable"); + }); + + it("cannot take an action if there is insufficient support", async () => { + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE.subn(1), user0Key, user0Value, user0Mask, user0Siblings, { + from: USER0, + }); + + await forwardTime(STAKE_PERIOD, this); + + await checkErrorRevert(voting.finalizeMotion(motionId), "voting-rep-motion-not-finalizable"); + }); + + it("can take an action if there is insufficient opposition", async () => { + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE.subn(1), user1Key, user1Value, user1Mask, user1Siblings, { + from: USER1, + }); + + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.true; + }); + + it("can take an action with a return value", async () => { + // Returns a uint256 + const action = await encodeTxData(colony, "version", []); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.true; + }); + + it("can take an action with an arbitrary target", async () => { + const { colony: otherColony } = await setupRandomColony(colonyNetwork); + await token.mint(otherColony.address, WAD, { from: USER0 }); + + const action = await encodeTxData(colony, "claimColonyFunds", [token.address]); + await voting.createRootMotion(otherColony.address, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + const balanceBefore = await otherColony.getFundingPotBalance(1, token.address); + expect(balanceBefore).to.be.zero; + + await voting.finalizeMotion(motionId); + + const balanceAfter = await otherColony.getFundingPotBalance(1, token.address); + expect(balanceAfter).to.eq.BN(WAD); + }); + + it("can take a nonexistent action", async () => { + const action = soliditySha3("foo"); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.false; + }); + + it("cannot take an action during staking or voting", async () => { + let motionState; + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(STAKING); + await checkErrorRevert(voting.finalizeMotion(motionId), "voting-rep-motion-not-finalizable"); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(SUBMIT); + await checkErrorRevert(voting.finalizeMotion(motionId), "voting-rep-motion-not-finalizable"); + }); + + it("cannot take an action twice", async () => { + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.true; + + await checkErrorRevert(voting.finalizeMotion(motionId), "voting-rep-motion-not-finalizable"); + }); + + it("can take an action if the motion passes", async () => { + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + // Don't need to wait for the reveal period, since 100% of the secret is revealed + + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.true; + }); + + it("cannot take an action if the motion fails", async () => { + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId, SALT, NAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(REVEAL_PERIOD, this); + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.false; + }); + + it("cannot take an action if there is insufficient voting power (state change actions)", async () => { + // Set globalClaimDelay to WAD + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + const action = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], [bn2bytes32(new BN(4))], WAD32]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + const motionId1 = await voting.getMotionCount(); + + await voting.stakeMotion(motionId1, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId1, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId1, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId1, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(REVEAL_PERIOD, this); + await forwardTime(STAKE_PERIOD, this); + + let logs; + ({ logs } = await voting.finalizeMotion(motionId1)); + expect(logs[0].args.executed).to.be.true; + + // Create another motion for the same variable + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + const motionId2 = await voting.getMotionCount(); + + await voting.stakeMotion(motionId2, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId2, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId2, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId2, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(REVEAL_PERIOD, this); + await forwardTime(STAKE_PERIOD, this); + + ({ logs } = await voting.finalizeMotion(motionId2)); + expect(logs[0].args.executed).to.be.false; + }); + + it("can set vote power correctly after a vote", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + + const action = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], ["0x0"], WAD32]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(REVEAL_PERIOD, this); + await forwardTime(ESCALATION_PERIOD, this); + + await voting.finalizeMotion(motionId); + const slotHash = hashExpenditureSlot(action); + const pastVote = await voting.getExpenditurePastVote(slotHash); + expect(pastVote).to.eq.BN(WAD); // USER0 had 1 WAD of reputation + }); + + it("can use vote power correctly for different values of the same variable", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + + // Set finalizedTimestamp + const action1 = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], [bn2bytes32(new BN(3))], WAD32]); + const action2 = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], [bn2bytes32(new BN(3))], "0x0"]); + + await voting.createRootMotion(ADDRESS_ZERO, action1, domain1Key, domain1Value, domain1Mask, domain1Siblings); + const motionId1 = await voting.getMotionCount(); + + await voting.createRootMotion(ADDRESS_ZERO, action2, domain1Key, domain1Value, domain1Mask, domain1Siblings); + const motionId2 = await voting.getMotionCount(); + + await voting.stakeMotion(motionId1, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId2, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + // First motion goes through + await voting.finalizeMotion(motionId1); + let expenditure = await colony.getExpenditure(expenditureId); + expect(expenditure.finalizedTimestamp).to.eq.BN(WAD); + + // Second motion does not because of insufficient vote power + expenditure = await colony.getExpenditure(expenditureId); + expect(expenditure.finalizedTimestamp).to.eq.BN(WAD); + }); + + it("can set vote power correctly if there is insufficient opposition", async () => { + await colony.makeExpenditure(1, UINT256_MAX, 1); + const expenditureId = await colony.getExpenditureCount(); + + const action = await encodeTxData(colony, "setExpenditureState", [1, UINT256_MAX, expenditureId, 25, [true], ["0x0"], WAD32]); + + await voting.createDomainMotion(1, UINT256_MAX, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + await voting.finalizeMotion(motionId); + const slotHash = hashExpenditureSlot(action); + const pastVote = await voting.getExpenditurePastVote(slotHash); + expect(pastVote).to.eq.BN(REQUIRED_STAKE); + }); + }); + + describe("claiming rewards", async () => { + let motionId; + + beforeEach(async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + }); + + it("cannot claim rewards from a non-existent motion", async () => { + await checkErrorRevert(voting.claimReward(0, 1, UINT256_MAX, USER0, YAY), "voting-rep-motion-not-claimable"); + }); + + it("can let stakers claim rewards, based on the stake outcome", async () => { + const addr = await colonyNetwork.getReputationMiningCycle(false); + const repCycle = await IReputationMiningCycle.at(addr); + const numEntriesPrev = await repCycle.getReputationUpdateLogLength(); + + const nayStake = REQUIRED_STAKE.divn(2); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, nayStake, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(STAKE_PERIOD, this); + + await voting.finalizeMotion(motionId); + + const user0LockPre = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + + const user0LockPost = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + + // Note that no voter rewards were paid out + const expectedReward0 = REQUIRED_STAKE.add(REQUIRED_STAKE.divn(20)); // 110% of stake + const expectedReward1 = REQUIRED_STAKE.divn(20).muln(9); // 90% of stake + + expect(new BN(user0LockPost.balance).sub(new BN(user0LockPre.balance))).to.eq.BN(expectedReward0); + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(expectedReward1); + + // Now check that user0 has no penalty, while user1 has a 10% penalty + const numEntriesPost = await repCycle.getReputationUpdateLogLength(); + expect(numEntriesPost.sub(numEntriesPrev)).to.eq.BN(1); + + const repUpdate = await repCycle.getReputationUpdateLogEntry(numEntriesPost.subn(1)); + expect(repUpdate.user).to.equal(USER1); + expect(repUpdate.amount).to.eq.BN(REQUIRED_STAKE.divn(20).neg()); + }); + + it("can let stakers claim rewards, based on the vote outcome", async () => { + const addr = await colonyNetwork.getReputationMiningCycle(false); + const repCycle = await IReputationMiningCycle.at(addr); + const numEntriesPrev = await repCycle.getReputationUpdateLogLength(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId, SALT, NAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(ESCALATION_PERIOD, this); + + await voting.finalizeMotion(motionId); + + const user0LockPre = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + + const user0LockPost = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + + const loserStake = REQUIRED_STAKE.divn(10).muln(8); // Take out voter comp + const expectedReward0 = loserStake.divn(3).muln(2); // (stake * .8) * (winPct = 1/3 * 2) + const expectedReward1 = REQUIRED_STAKE.add(loserStake.divn(3)); // stake + ((stake * .8) * (1 - (winPct = 2/3 * 2)) + + expect(new BN(user0LockPost.balance).sub(new BN(user0LockPre.balance))).to.eq.BN(expectedReward0); + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(expectedReward1); + + // Now check that user1 has no penalty, while user0 has a 1/3 penalty + const numEntriesPost = await repCycle.getReputationUpdateLogLength(); + expect(numEntriesPost.sub(numEntriesPrev)).to.eq.BN(1); + + const repUpdate = await repCycle.getReputationUpdateLogEntry(numEntriesPost.subn(1)); + expect(repUpdate.user).to.equal(USER0); + expect(repUpdate.amount).to.eq.BN(REQUIRED_STAKE.sub(expectedReward0).neg()); + }); + + it("can let stakers claim rewards, based on the vote outcome, with multiple losing stakers", async () => { + const user2Key = makeReputationKey(colony.address, domain1.skillId, USER2); + const user2Value = makeReputationValue(REQUIRED_STAKE.subn(1), 8); + const [user2Mask, user2Siblings] = await reputationTree.getProof(user2Key); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE.divn(3).muln(2), user1Key, user1Value, user1Mask, user1Siblings, { + from: USER1, + }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE.divn(3), user2Key, user2Value, user2Mask, user2Siblings, { + from: USER2, + }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId, SALT, NAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(ESCALATION_PERIOD, this); + + await voting.finalizeMotion(motionId); + + const user0LockPre = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + const user2LockPre = await tokenLocking.getUserLock(token.address, USER2); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER2, NAY); + + const user0LockPost = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + const user2LockPost = await tokenLocking.getUserLock(token.address, USER2); + + const loserStake = REQUIRED_STAKE.divn(10).muln(8); // Take out voter comp + const expectedReward0 = loserStake.divn(3).muln(2); // (stake * .8) * (winPct = 1/3 * 2) + const expectedReward1 = REQUIRED_STAKE.add(loserStake.divn(3)).divn(3).muln(2); // stake + ((stake * .8) * (1 - (winPct = 2/3 * 2)) + const expectedReward2 = REQUIRED_STAKE.add(loserStake.divn(3)).divn(3); // stake + ((stake * .8) * (1 - (winPct = 2/3 * 2)) + + expect(new BN(user0LockPost.balance).sub(new BN(user0LockPre.balance))).to.eq.BN(expectedReward0); + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(expectedReward1.addn(1)); // Rounding + expect(new BN(user2LockPost.balance).sub(new BN(user2LockPre.balance))).to.eq.BN(expectedReward2.addn(1)); // Rounding + }); + + it("can let stakers claim rewards, based on the vote outcome, with multiple winning stakers", async () => { + const user2Key = makeReputationKey(colony.address, domain1.skillId, USER2); + const user2Value = makeReputationValue(REQUIRED_STAKE.subn(1), 8); + const [user2Mask, user2Siblings] = await reputationTree.getProof(user2Key); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE.divn(3).muln(2), user0Key, user0Value, user0Mask, user0Siblings, { + from: USER0, + }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE.divn(3), user2Key, user2Value, user2Mask, user2Siblings, { + from: USER2, + }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId, SALT, NAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(ESCALATION_PERIOD, this); + + await voting.finalizeMotion(motionId); + + const user0LockPre = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + const user2LockPre = await tokenLocking.getUserLock(token.address, USER2); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER2, YAY); + + const user0LockPost = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + const user2LockPost = await tokenLocking.getUserLock(token.address, USER2); + + const loserStake = REQUIRED_STAKE.divn(10).muln(8); // Take out voter comp + const expectedReward0 = loserStake.divn(3).muln(2).divn(3).muln(2); // (stake * .8) * (winPct = 1/3 * 2) + const expectedReward1 = REQUIRED_STAKE.add(loserStake.divn(3)); // stake + ((stake * .8) * (1 - (winPct = 2/3 * 2)) + const expectedReward2 = loserStake.divn(3).muln(2).divn(3); // (stake * .8) * (winPct = 1/3 * 2) + + expect(new BN(user0LockPost.balance).sub(new BN(user0LockPre.balance))).to.eq.BN(expectedReward0.addn(1)); // Rounding + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(expectedReward1); + expect(new BN(user2LockPost.balance).sub(new BN(user2LockPre.balance))).to.eq.BN(expectedReward2); + }); + + it("can let stakers claim their original stake if neither side fully staked", async () => { + const addr = await colonyNetwork.getReputationMiningCycle(false); + const repCycle = await IReputationMiningCycle.at(addr); + const numEntriesPrev = await repCycle.getReputationUpdateLogLength(); + + const half = REQUIRED_STAKE.divn(2); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, half, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, half, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(STAKE_PERIOD, this); + + const user0LockPre = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + + const numEntriesPost = await repCycle.getReputationUpdateLogLength(); + + const user0LockPost = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + + expect(numEntriesPrev).to.eq.BN(numEntriesPost); + expect(new BN(user0LockPost.balance).sub(new BN(user0LockPre.balance))).to.eq.BN(half); + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(half); + }); + + it("cannot claim rewards twice", async () => { + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(SUBMIT_PERIOD, this); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(REVEAL_PERIOD, this); + await forwardTime(ESCALATION_PERIOD, this); + + await voting.finalizeMotion(motionId); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + + await checkErrorRevert(voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY), "voting-rep-nothing-to-claim"); + }); + + it("cannot claim rewards before a motion is finalized", async () => { + await checkErrorRevert(voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY), "voting-rep-motion-not-claimable"); + }); + }); + + describe("escalating motions", async () => { + let motionId; + + beforeEach(async () => { + const domain2Key = makeReputationKey(colony.address, domain2.skillId); + const domain2Value = makeReputationValue(WAD, 6); + const [domain2Mask, domain2Siblings] = await reputationTree.getProof(domain2Key); + + const user0Key2 = makeReputationKey(colony.address, domain2.skillId, USER0); + const user0Value2 = makeReputationValue(WAD.divn(3), 9); + const [user0Mask2, user0Siblings2] = await reputationTree.getProof(user0Key2); + + const user1Key2 = makeReputationKey(colony.address, domain2.skillId, USER1); + const user1Value2 = makeReputationValue(WAD.divn(3).muln(2), 10); + const [user1Mask2, user1Siblings2] = await reputationTree.getProof(user1Key2); + + const action = await encodeTxData(colony, "makeTask", [1, 0, FAKE, 2, 0, 0]); + await voting.createDomainMotion(2, UINT256_MAX, action, domain2Key, domain2Value, domain2Mask, domain2Siblings); + motionId = await voting.getMotionCount(); + + await colony.approveStake(voting.address, 2, WAD, { from: USER0 }); + await colony.approveStake(voting.address, 2, WAD, { from: USER1 }); + + await voting.stakeMotion(motionId, 1, 0, NAY, WAD.divn(1000), user0Key2, user0Value2, user0Mask2, user0Siblings2, { from: USER0 }); + await voting.stakeMotion(motionId, 1, 0, YAY, WAD.divn(1000), user1Key2, user1Value2, user1Mask2, user1Siblings2, { from: USER1 }); + + // Note that this is a passing vote + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key2, user0Value2, user0Mask2, user0Siblings2, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user1Key2, user1Value2, user1Mask2, user1Siblings2, { from: USER1 }); + + await voting.revealVote(motionId, SALT, NAY, user0Key2, user0Value2, user0Mask2, user0Siblings2, { from: USER0 }); + await voting.revealVote(motionId, SALT, YAY, user1Key2, user1Value2, user1Mask2, user1Siblings2, { from: USER1 }); + }); + + it("can internally escalate a domain motion after a vote", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + }); + + it("can internally escalate a domain motion after a vote", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER1 }); + }); + + it("cannot internally escalate a domain motion if not in a 'closed' state", async () => { + await forwardTime(ESCALATION_PERIOD, this); + + await voting.finalizeMotion(motionId); + + await checkErrorRevert( + voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER2 }), + "voting-rep-motion-not-closed" + ); + }); + + it("cannot internally escalate a domain motion with an invalid domain proof", async () => { + await checkErrorRevert( + voting.escalateMotion(motionId, 1, 1, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }), + "voting-rep-invalid-domain-proof" + ); + }); + + it("cannot internally escalate a domain motion with an invalid reputation proof", async () => { + await checkErrorRevert(voting.escalateMotion(motionId, 1, 0, "0x0", "0x0", "0x0", [], { from: USER0 }), "voting-rep-invalid-root-hash"); + }); + + it("can stake after internally escalating a domain motion", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + const yayStake = REQUIRED_STAKE.sub(WAD.divn(1000)); + const nayStake = yayStake.add(REQUIRED_STAKE.divn(10)); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, yayStake, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, nayStake, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + const motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(SUBMIT); + }); + + it("can execute after internally escalating a domain motion, if there is insufficient opposition", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + const yayStake = REQUIRED_STAKE.sub(WAD.divn(1000)); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, yayStake, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.true; + }); + + it("cannot execute after internally escalating a domain motion, if there is insufficient support", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(STAKE_PERIOD, this); + + const motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(FAILED); + }); + + it("can fall back on the previous vote if both sides fail to stake", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + await forwardTime(STAKE_PERIOD, this); + + // Note that the previous vote succeeded + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.true; + }); + + it("can use the result of a new stake after internally escalating a domain motion", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + const yayStake = REQUIRED_STAKE.sub(WAD.divn(1000)); + const nayStake = yayStake.add(REQUIRED_STAKE.divn(10)); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, nayStake, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(STAKE_PERIOD, this); + + const motionState = await voting.getMotionState(motionId); + expect(motionState).to.eq.BN(FAILED); + + // Now check that the rewards come out properly + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + + await checkErrorRevert(voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY), "voting-rep-nothing-to-claim"); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + + const expectedReward1 = (REQUIRED_STAKE.add(WAD.divn(1000 * 10))).divn(32).muln(22); // eslint-disable-line prettier/prettier + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(expectedReward1); + }); + + it("can use the result of a new vote after internally escalating a domain motion", async () => { + await voting.escalateMotion(motionId, 1, 0, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + const yayStake = REQUIRED_STAKE.sub(WAD.divn(1000)); + const nayStake = yayStake.add(REQUIRED_STAKE.divn(10)); + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, yayStake, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, nayStake, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + // Vote fails + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId, SALT, NAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await forwardTime(ESCALATION_PERIOD, this); + + const { logs } = await voting.finalizeMotion(motionId); + expect(logs[0].args.executed).to.be.false; + + // Now check that the rewards come out properly + // 1st voter reward paid by YAY (user0), 2nd paid by NAY (user1) + const user0LockPre = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPre = await tokenLocking.getUserLock(token.address, USER1); + + await voting.claimReward(motionId, 1, UINT256_MAX, USER0, YAY); + await voting.claimReward(motionId, 1, UINT256_MAX, USER1, NAY); + + const user0LockPost = await tokenLocking.getUserLock(token.address, USER0); + const user1LockPost = await tokenLocking.getUserLock(token.address, USER1); + + const loserStake = REQUIRED_STAKE.divn(10).muln(8); + // (stake * .8) * (winPct = 1/3 * 2) * 2/3 (since 1/3 of stake is from other user!) + const expectedReward0 = loserStake.divn(3).muln(2).divn(3).muln(2); + // stake + ((stake * .8) * (1 - (winPct = 2/3 * 2)) * 22/32) (since 10/32 of stake is from other user!) + const expectedReward1 = REQUIRED_STAKE.add(loserStake.divn(3)).divn(32).muln(22); + + expect(new BN(user0LockPost.balance).sub(new BN(user0LockPre.balance))).to.eq.BN(expectedReward0.addn(1)); // Rounding + expect(new BN(user1LockPost.balance).sub(new BN(user1LockPre.balance))).to.eq.BN(expectedReward1); + }); + + it("cannot escalate a motion in the root domain", async () => { + const action = await encodeTxData(colony, "makeTask", [1, UINT256_MAX, FAKE, 1, 0, 0]); + await voting.createRootMotion(ADDRESS_ZERO, action, domain1Key, domain1Value, domain1Mask, domain1Siblings); + motionId = await voting.getMotionCount(); + + await voting.stakeMotion(motionId, 1, UINT256_MAX, YAY, REQUIRED_STAKE, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.stakeMotion(motionId, 1, UINT256_MAX, NAY, REQUIRED_STAKE, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + await voting.revealVote(motionId, SALT, YAY, user0Key, user0Value, user0Mask, user0Siblings, { from: USER0 }); + await voting.revealVote(motionId, SALT, NAY, user1Key, user1Value, user1Mask, user1Siblings, { from: USER1 }); + + const state = await voting.getMotionState(motionId); + expect(state).to.eq.BN(EXECUTABLE); + }); + + it("can skip the staking phase if no new stake is required", async () => { + // Deploy a new extension with no voter compensation + await votingFactory.removeExtension(colony.address, { from: USER0 }); + await votingFactory.deployExtension(colony.address, { from: USER0 }); + const votingAddress = await votingFactory.deployedExtensions(colony.address); + voting = await VotingReputation.at(votingAddress); + + await colony.setArbitrationRole(1, UINT256_MAX, voting.address, 1, true); + + await voting.initialise( + TOTAL_STAKE_FRACTION, + 0, // No voter compensation + USER_MIN_STAKE_FRACTION, + MAX_VOTE_FRACTION, + STAKE_PERIOD, + SUBMIT_PERIOD, + REVEAL_PERIOD, + ESCALATION_PERIOD + ); + + // Run a vote in domain 3, same rep as domain 1 + const domain3Key = makeReputationKey(colony.address, domain3.skillId); + const domain3Value = makeReputationValue(WAD.muln(3), 7); + const [domain3Mask, domain3Siblings] = await reputationTree.getProof(domain3Key); + + const user0Key3 = makeReputationKey(colony.address, domain3.skillId, USER0); + const user0Value3 = makeReputationValue(WAD, 11); + const [user0Mask3, user0Siblings3] = await reputationTree.getProof(user0Key3); + + const user1Key3 = makeReputationKey(colony.address, domain3.skillId, USER1); + const user1Value3 = makeReputationValue(WAD.muln(2), 12); + const [user1Mask3, user1Siblings3] = await reputationTree.getProof(user1Key3); + + const action = await encodeTxData(colony, "makeTask", [1, 1, FAKE, 3, 0, 0]); + await voting.createDomainMotion(3, UINT256_MAX, action, domain3Key, domain3Value, domain3Mask, domain3Siblings); + motionId = await voting.getMotionCount(); + + await colony.approveStake(voting.address, 3, WAD, { from: USER0 }); + await colony.approveStake(voting.address, 3, WAD, { from: USER1 }); + + await voting.stakeMotion(motionId, 1, 1, NAY, REQUIRED_STAKE, user0Key3, user0Value3, user0Mask3, user0Siblings3, { from: USER0 }); + await voting.stakeMotion(motionId, 1, 1, YAY, REQUIRED_STAKE, user1Key3, user1Value3, user1Mask3, user1Siblings3, { from: USER1 }); + + // Note that this is a passing vote + await voting.submitVote(motionId, soliditySha3(SALT, NAY), user0Key3, user0Value3, user0Mask3, user0Siblings3, { from: USER0 }); + await voting.submitVote(motionId, soliditySha3(SALT, YAY), user1Key3, user1Value3, user1Mask3, user1Siblings3, { from: USER1 }); + + await voting.revealVote(motionId, SALT, NAY, user0Key3, user0Value3, user0Mask3, user0Siblings3, { from: USER0 }); + await voting.revealVote(motionId, SALT, YAY, user1Key3, user1Value3, user1Mask3, user1Siblings3, { from: USER1 }); + + // Now escalate, should go directly into submit phase + await voting.escalateMotion(motionId, 1, 1, domain1Key, domain1Value, domain1Mask, domain1Siblings, { from: USER0 }); + + const state = await voting.getMotionState(motionId); + expect(state).to.eq.BN(SUBMIT); + }); + }); +});