/** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.25; import "@laborx/solidity-storage-contracts/contracts/Storage.sol"; import "../common/initializable/InitializableOwned.sol"; import "./LaborContractCore.sol"; import "./LaborContractBase.sol"; import "../libs/DataParser.sol"; import "../libs/SafeMath.sol"; import "./LaborLib.sol"; /// @title Part of LaborContract functionality that provides termination implementation. /// @dev Should be used as a library extension contract LaborContractTerminatable is LaborContractBaseTerminatable, InitializableOwned, LaborContractAbstract { /// @dev Indices for contract terminatable details values uint constant internal CONTRACT_TERMINATABLE_DETAILS_AMOUNT = 0; uint constant internal CONTRACT_TERMINATABLE_DETAILS_EMPLOYER_AMOUNT = 1; uint constant internal CONTRACT_TERMINATABLE_DETAILS_ASSIGNEE_AMOUNT = 2; uint constant internal CONTRACT_TERMINATABLE_DETAILS_INITIATOR_TYPE = 3; uint constant internal CONTRACT_TERMINATABLE_DETAILS_RECEIVER_TYPE = 4; uint constant internal CONTRACT_TERMINATABLE_DETAILS_UNSPENT_UPFRONT_REFUND_AMOUNT = 5; uint constant internal CONTRACT_TERMINATABLE_DETAILS_NEED_TO_INIT_DEPOSIT_AMOUNT = 6; uint constant internal CONTRACT_TERMINATABLE_DETAILS_NEED_TO_CONFIRM_DEPOSIT_AMOUNT = 7; uint constant internal CONTRACT_TERMINATABLE_DETAILS_NEED_TO_PAY_TASKS_AMOUNT = 8; uint constant internal CONTRACT_TERMINATABLE_DETAILS_ASSIGNEE_WITHDRAW_FEE_AMOUNT = 9; uint constant internal CONTRACT_TERMINATABLE_DETAILS_LENGTH = 10; constructor() StorageAdapter(Storage(0x0), "") public { // NOTE: don't need to initialize anything } function version() public pure returns (string) { return "0.2.1"; } function getTerminationPaymentAmounts( bytes32 _contractId, uint _terminationId ) external view returns (uint _employerValue, uint _assigneeValue) { (DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _terminationInfo) = _fetchTerminationContextInfo( _contractId, _terminationId ); return _getTerminationAmounts(_contractId, _contractInfo, _terminationInfo, false); } function getTerminationContractDetails(bytes32 _contractId, uint _terminationId) external view returns (uint[] _values) { _values = new uint[](CONTRACT_TERMINATABLE_DETAILS_LENGTH); (DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _terminationInfo) = _fetchTerminationContextInfo( _contractId, _terminationId ); uint _totalBudget = _getContractTotalBudgetAmount(_contractId); _values[CONTRACT_TERMINATABLE_DETAILS_AMOUNT] = DataParser.getTerminationResultValue( _terminationInfo, _totalBudget, TERMINATION_PERCENT_PRECISION ); (uint _employerAmount, uint _assigneeAmount) = _getTerminationAmounts( _contractId, _contractInfo, _terminationInfo, false ); _values[CONTRACT_TERMINATABLE_DETAILS_EMPLOYER_AMOUNT] = _employerAmount; _values[CONTRACT_TERMINATABLE_DETAILS_ASSIGNEE_AMOUNT] = _assigneeAmount; _values[CONTRACT_TERMINATABLE_DETAILS_INITIATOR_TYPE] = _terminationInfo.initiatorType; _values[CONTRACT_TERMINATABLE_DETAILS_RECEIVER_TYPE] = _terminationInfo.payToType; uint _unspentUpfrontRefundAmount = _calculateContractTerminationRefund(_contractId, _contractInfo); _values[CONTRACT_TERMINATABLE_DETAILS_UNSPENT_UPFRONT_REFUND_AMOUNT] = _unspentUpfrontRefundAmount; _values[CONTRACT_TERMINATABLE_DETAILS_NEED_TO_INIT_DEPOSIT_AMOUNT] = getTerminationInitiateDepositDetails(_contractId, _terminationId); _values[CONTRACT_TERMINATABLE_DETAILS_NEED_TO_CONFIRM_DEPOSIT_AMOUNT] = getTerminationConfirmDepositDetails(_contractId, _terminationId); _values[CONTRACT_TERMINATABLE_DETAILS_NEED_TO_PAY_TASKS_AMOUNT] = _contractInfo.paymentTimeline == uint8(DataParser.PaymentTimeline.PAY_BY_PROJECT) ? _getLeftToPayAmount(_contractId) : 0; (, uint _assigneePercent, uint _percentPrecision) = getServiceSurchargePercent(_contractId); _values[CONTRACT_TERMINATABLE_DETAILS_ASSIGNEE_WITHDRAW_FEE_AMOUNT] = PercentCalculator.getPercent( _values[CONTRACT_TERMINATABLE_DETAILS_NEED_TO_PAY_TASKS_AMOUNT], _assigneePercent, _percentPrecision ); } function getTerminationInitiateDepositDetails(bytes32 _contractId, uint _terminationId) public view returns (uint) { return _getTerminationDepositDetails( _contractId, _terminationId, false, LaborLib._calculateContractInitiateTerminationExcessFare ); } function getTerminationCancelDepositDetails(bytes32 _contractId, uint _terminationId) public view returns (uint) { return _getTerminationDepositDetails( _contractId, _terminationId, false, LaborLib._calculateContractCancelTerminationExcessFare ); } function getTerminationConfirmDepositDetails(bytes32 _contractId, uint _terminationId) public view returns (uint) { return _getTerminationDepositDetails( _contractId, _terminationId, true, LaborLib._calculateContractConfirmTerminationExcessFare ); } function _getTerminationDepositDetails( bytes32 _contractId, uint _terminationId, bool _isOppositeParty, function (DataParser.ContractData memory, DataParser.TerminationData memory, DataParser.TerminationParty, uint, uint, uint, uint, uint) internal pure returns (uint, uint, uint) _calculateFareFunc ) private view returns (uint _depositAmount) { (DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _terminationInfo) = _fetchTerminationContextInfo( _contractId, _terminationId ); DataParser.TerminationParty _terminationParty = _isOppositeParty ? DataParser.getOppositeTerminationParty( DataParser.TerminationParty(_terminationInfo.initiatorType) ) : DataParser.TerminationParty(_terminationInfo.initiatorType); uint _escrowBalance = _getUnlockedEscrowBalance(_contractId, _contractInfo); (_depositAmount,,) = _calculateTerminationFares( _contractId, _contractInfo, _terminationInfo, _terminationParty, _escrowBalance, _calculateFareFunc ); return _depositAmount; } function _getUnlockedEscrowBalance( bytes32 _contractId, DataParser.ContractData memory _contractInfo ) private view returns (uint) { uint _escrowBalance = _getFullEscrowBalance(_contractId, _contractInfo); return _escrowBalance.sub(_getContractLockedTerminationAmount(_contractId)); } function _getFullEscrowBalance( bytes32 _contractId, DataParser.ContractData memory _contractInfo ) private view returns (uint) { EscrowBaseInterface _escrow = getEscrow(_contractId); (, uint _escrowBalance) = _escrow.getBalanceOf(_contractId, _contractInfo.employer, _contractInfo.assignee); return _escrowBalance; } function initiateTermination( bytes32 _contractId, uint32 _terminationId, uint _value, string _comment ) external payable onlyInState(_contractId, State.STARTED) returns (uint) { /** 1. Find appropriate termination condition */ DataParser.TerminationData memory _termination = DataParser.getTerminationById(_terminationId, _getTerminationsInfoBytes(_contractId)); require(_termination.id != 0, "C_TI"); /** 2. Termination available only for ContractType.JOB contract type */ DataParser.ContractData memory _contractInfo = DataParser.parseContractDataCleanInput(_getContractInfoBytes(_contractId)); require(_contractInfo.contractType == uint8(DataParser.ContractType.JOB), "C_CJ"); /** 3. Initiator should refer to correct termination condition */ DataParser.TerminationParty _initiatorParty = DataParser.getTerminationParty(_contractInfo, msg.sender); require(_termination.initiatorType == uint8(_initiatorParty), "C_I"); /** 4. Take required deposit amount from an termination initiator. Deposit procedure is intended to cover cases when: - assignee wants to terminate and should refund upfront amount of unfinished tasks (if applicable) - assignee wants to terminate and should pay termination amount to an employer - employer wants to terminate in case of PAY_BY_PROJECT payment timeline so he should provide full payment for finished tasks */ _depositTerminationToEscrow( _contractId, _contractInfo, _termination, _initiatorParty, _value, LaborLib._calculateContractInitiateTerminationExcessFare ); /** 4. Save termination data */ if (bytes(_comment).length > 0) { store.set(terminationReasonStorage, _contractId, _comment); } store.set(terminationRequestIdStorage, _contractId, _terminationId); /** 5. Move contract state to TERMINATION_REQUESTED */ _setContractStateTo(_contractId, State.TERMINATION_REQUESTED); emit ContractTerminationRequested(_contractId, _terminationId, msg.sender, _comment); return OK; } function cancelTerminationRequest( bytes32 _contractId ) external returns (uint) { // NOTE: this call in only valid when no payback (withdrawal) is needed for any of requester. // If payback is needed then call `cancelTerminationRequestWithApproval` function return _cancelTerminationRequest(_contractId, 0, 0, new bytes(0)); } function cancelTerminationRequestWithApproval( bytes32 _contractId, uint _expireAtBlock, uint _salt, bytes _signature ) external returns (uint) { return _cancelTerminationRequest(_contractId, _expireAtBlock, _salt, _signature); } function _cancelTerminationRequest( bytes32 _contractId, uint _expireAtBlock, uint _salt, bytes _signature ) internal onlyInState(_contractId, State.TERMINATION_REQUESTED) returns (uint) { /** 1. Check that an initiator of cancelling termination is the same as termination initiator */ (DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination) = _fetchCurrentTerminationContextInfo( _contractId ); DataParser.TerminationParty _initiatorParty = DataParser.getTerminationParty(_contractInfo, msg.sender); require(_termination.initiatorType == uint8(_initiatorParty), "C_I"); /** 2. Withdraw back to a termination requester an amount of deposited currency on initination stage. */ _withdrawOnCancelledTerminationFromEscrow( _contractId, _contractInfo, _termination, _initiatorParty, _expireAtBlock, _salt, _signature ); /** 3. Clean termination data */ if (bytes(store.get(terminationReasonStorage, _contractId)).length > 0) { store.set(terminationReasonStorage, _contractId, ""); } store.set(terminationRequestIdStorage, _contractId, 0); /** 4. Move contract state to STARTED */ _setContractStateTo(_contractId, State.STARTED); emit ContractTerminationRequestCancelled(_contractId, _termination.id); return OK; } function confirmTermination( bytes32 _contractId, uint _value, uint _expireAtBlock, uint _tasksSalt, bytes _tasksSignature, uint _salt, bytes _signatures ) external payable onlyInState(_contractId, State.TERMINATION_REQUESTED) returns (uint) { (DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination) = _prepareTerminationConfirmation( _contractId, _value, _expireAtBlock, _tasksSalt, _tasksSignature ); _releaseTerminationToEscrow(_contractId, _contractInfo, _termination, _expireAtBlock, _salt, _signatures); _setContractStateTo(_contractId, State.TERMINATED); emit ContractTerminated( _contractId, _termination.id ); return OK; } function _prepareTerminationConfirmation( bytes32 _contractId, uint _value, uint _expireAtBlock, uint _tasksSalt, bytes _tasksSignature ) private returns ( DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination ) { (_contractInfo, _termination) = _fetchCurrentTerminationContextInfo( _contractId ); /** 1. Ensure that a confirmation party is an opposite party that initiated the termination */ DataParser.TerminationParty _confirmationParty = DataParser.getTerminationParty(_contractInfo, msg.sender); require(_termination.initiatorType != uint8(_confirmationParty), "C_OI"); /** 2. Take required deposit amount from an termination confirmation party. Deposit procedure is intended to cover cases when: - assignee wants to terminate and should refund upfront amount of unfinished tasks (if applicable) - assignee wants to terminate and should pay termination amount to an employer - employer wants to terminate in case of PAY_BY_PROJECT payment timeline so he should provide full payment for finished tasks */ _depositTerminationToEscrow( _contractId, _contractInfo, _termination, _confirmationParty, _value, LaborLib._calculateContractConfirmTerminationExcessFare ); /** 3. Send tasks payment directly to an assignee taking system service fee */ _sendPaymentForTasksFromEscrow(_contractId, _contractInfo, _expireAtBlock, _tasksSalt, _tasksSignature); } /** PRIVATE */ function _releaseTerminationToEscrow( bytes32 _contractId, DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination, uint _expireAtBlock, uint _salt, bytes _signatures ) private { (uint _employerValue, uint _assigneeValue) = _getTerminationAmounts(_contractId, _contractInfo, _termination, true); EscrowBaseInterface _escrow = getEscrow(_contractId); if (_employerValue.add(_assigneeValue) > 0) { require( OK == _escrow.releaseNegotiatedPayment( _contractId, _contractInfo.employer, _contractInfo.assignee, _employerValue, _assigneeValue, _expireAtBlock, _salt, _signatures, _getNoFeeFlag() ), "C_RNE" ); } _incrementTransferredBalance(_contractId, _assigneeValue); require( OK == _escrow.deleteEscrow(_contractId, _contractInfo.employer, _contractInfo.assignee), "C_DTE" ); } /// @dev There is no need to calculate fee on deposit process because: /// - if it is an employer's deposit -> tasks budget -> already paid fee on sign /// - if it is an assignee's deposit -> termination and upfront refund -> no need to take fee from a termination value /// In case of PAY_BY_PROJECT payment timeline we transfer all employer's deposit to the assignee and take service fee. function _depositTerminationToEscrow( bytes32 _contractId, DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination, DataParser.TerminationParty _forParty, uint _value, function (DataParser.ContractData memory, DataParser.TerminationData memory, DataParser.TerminationParty, uint, uint, uint, uint, uint) internal pure returns (uint, uint, uint) _calculateFareFunc ) private { uint _balance = _getUnlockedEscrowBalance(_contractId, _contractInfo); (uint _depositAmount, uint _depositToEscrow, uint _terminationLockAmount) = _calculateTerminationFares( _contractId, _contractInfo, _termination, _forParty, _balance, _calculateFareFunc ); require(_value == _depositAmount, "C_TDV"); // Termination invalid deposit value _executeDepositTerminationToEscrow( _contractId, _contractInfo, _forParty, _depositAmount, _depositToEscrow, _terminationLockAmount ); } function _executeDepositTerminationToEscrow( bytes32 _contractId, DataParser.ContractData memory _contractInfo, DataParser.TerminationParty _forParty, uint _depositAmount, uint _depositToEscrow, uint _terminationLockAmount ) private { if (_depositAmount == 0) { return; } EscrowBaseInterface _escrow = getEscrow(_contractId); require( OK == _escrow.deposit.value(SafeMath.min(msg.value, _depositAmount)) ( _contractId, _contractInfo.employer, _contractInfo.assignee, _depositAmount, 0, _getBuyerFeeFlag() | _getDepositInitiatorFlagForTerminationParty(_forParty) ), "C_DE" ); _incrementLockedTerminationAmount(_contractId, _terminationLockAmount); if (_forParty == DataParser.TerminationParty.TERMINATION_ASSIGNEE) { _decrementCompletedPaymentValue(_contractId, _depositToEscrow.sub(_terminationLockAmount)); _decrementTransferredBalance(_contractId, _depositToEscrow.sub(_terminationLockAmount)); } } function _sendPaymentForTasksFromEscrow( bytes32 _contractId, DataParser.ContractData memory _contractInfo, uint _expireAtBlock, uint _salt, bytes _signature ) private { uint _leftToPay = _getLeftToPayAmount(_contractId); if (_leftToPay <= 0) { return; } EscrowBaseInterface _escrow = getEscrow(_contractId); require(OK == _escrow.releaseBuyerPayment( _contractId, _contractInfo.employer, _contractInfo.assignee, _leftToPay, _expireAtBlock, _salt, _signature, _getBuyerFeeFlag() ), "C_BPE" // Buyer payment error ); _incrementTransferredBalance(_contractId, _leftToPay); } function _withdrawOnCancelledTerminationFromEscrow( bytes32 _contractId, DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination, DataParser.TerminationParty _forParty, uint _expireAtBlock, uint _salt, bytes _signature ) private { uint _balance = _getUnlockedEscrowBalance(_contractId, _contractInfo); (, uint _escrowedAmount, uint _terminationLockAmount) = _calculateTerminationFares( _contractId, _contractInfo, _termination, _forParty, _balance, LaborLib._calculateContractCancelTerminationExcessFare ); if (_escrowedAmount <= 0) { return; } _decrementLockedTerminationAmount(_contractId, _terminationLockAmount); EscrowBaseInterface _escrow = getEscrow(_contractId); if (_termination.initiatorType == uint8(DataParser.TerminationParty.TERMINATION_EMPLOYER)) { require(OK == _escrow.sendSellerPayback( _contractId, _contractInfo.employer, _contractInfo.assignee, _escrowedAmount, _expireAtBlock, _salt, _signature ), "C_SPE" // Seller payback error ); } else if (_termination.initiatorType == uint8(DataParser.TerminationParty.TERMINATION_ASSIGNEE)) { require(OK == _escrow.releaseBuyerPayment( _contractId, _contractInfo.employer, _contractInfo.assignee, _escrowedAmount, _expireAtBlock, _salt, _signature, _getNoFeeFlag() ), "C_BPE" // Buyer payment error ); _incrementTransferredBalance(_contractId, _escrowedAmount.sub(_terminationLockAmount)); _incrementCompletedPaymentValue(_contractId, _escrowedAmount.sub(_terminationLockAmount)); } else { revert("C_TUT"); // Termination Unhandled party type } } function _fetchCurrentTerminationContextInfo( bytes32 _contractId ) private view returns ( DataParser.ContractData memory, DataParser.TerminationData memory ) { return _fetchTerminationContextInfo(_contractId, _getCurrentTerminationId(_contractId)); } function _fetchTerminationContextInfo( bytes32 _contractId, uint _terminationId ) private view returns ( DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _terminationInfo ) { _contractInfo = DataParser.parseContractDataCleanInput(_getContractInfoBytes(_contractId)); _terminationInfo = DataParser.getTerminationById( _terminationId, _getTerminationsInfoBytes(_contractId) ); } function _calculateTerminationFares( bytes32 _contractId, DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _termination, DataParser.TerminationParty _forParty, uint _balance, function (DataParser.ContractData memory, DataParser.TerminationData memory, DataParser.TerminationParty, uint, uint, uint, uint, uint) internal pure returns (uint, uint, uint) _calculateFareFunc ) private view returns (uint _depositAmount, uint _depositToEscrow, uint _terminationReserveAmount) { uint _leftToTransferAmount = _getLeftToPayAmount(_contractId); uint _totalBudget = _getContractTotalBudgetAmount(_contractId); uint _upfrontRefundAmount = _calculateContractTerminationRefund(_contractId, _contractInfo); (_depositAmount, _depositToEscrow, _terminationReserveAmount) = _calculateFareFunc( _contractInfo, _termination, _forParty, _leftToTransferAmount, _balance, _totalBudget, _upfrontRefundAmount, TERMINATION_PERCENT_PRECISION ); } function _getTerminationAmounts( bytes32 _contractId, DataParser.ContractData memory _contractInfo, DataParser.TerminationData memory _terminationInfo, bool _finalized ) private view returns (uint _employerValue, uint _assigneeValue) { State _contractState = _getContractState(_contractId); uint _escrowBalance = _getUnlockedEscrowBalance(_contractId, _contractInfo); uint _depositToEscrow; uint _depositEscrowAccumulator; uint _terminationLockAmount; if ( _contractState == State.STARTED ) { (, _depositToEscrow, _terminationLockAmount) = _calculateTerminationFares( _contractId, _contractInfo, _terminationInfo, DataParser.TerminationParty(_terminationInfo.initiatorType), _escrowBalance, LaborLib._calculateContractInitiateTerminationExcessFare ); _escrowBalance = _escrowBalance.add(_depositToEscrow).sub(_terminationLockAmount); _depositEscrowAccumulator = _depositEscrowAccumulator.add(_depositToEscrow); } if ( _contractState == State.STARTED || (_contractState == State.TERMINATION_REQUESTED && !_finalized) ) { (, _depositToEscrow, _terminationLockAmount) = _calculateTerminationFares( _contractId, _contractInfo, _terminationInfo, DataParser.getOppositeTerminationParty(DataParser.TerminationParty(_terminationInfo.initiatorType)), _escrowBalance, LaborLib._calculateContractConfirmTerminationExcessFare ); _escrowBalance = _escrowBalance.add(_depositToEscrow).sub(_terminationLockAmount); _depositEscrowAccumulator = _depositEscrowAccumulator.add(_depositToEscrow); } _escrowBalance = _getFullEscrowBalance(_contractId, _contractInfo); // NOTE: we should pay any debts for tasks before this point, so we assume that should leftToPay == 0. // In case when leftToPay !== 0 it is a situation when 'State == STARTED || State == TERMINATION_REQUESTED (before payment)' // because there is no termination request or it hasn't been confirmed yet. _escrowBalance = _escrowBalance.add(_depositEscrowAccumulator).sub(_getLeftToPayAmount(_contractId)); return LaborLib._calculateContractTermination( _contractInfo, _terminationInfo, _getContractTotalBudgetAmount(_contractId), _escrowBalance, 0, TERMINATION_PERCENT_PRECISION ); } function _calculateContractTerminationRefund( bytes32 _contractId, DataParser.ContractData memory _contractInfo ) private view returns (uint) { if (!_contractInfo.refundUpfrontOnTermination) { return 0; } WorkflowBase _workflow = getWorkflow(_contractId); uint _unspentUpfrontAmount = _workflow.getUnspentUpfrontAmount(_contractId, address(this)); return _unspentUpfrontAmount; } function _getCurrentTerminationId(bytes32 _contractId) private view returns (uint) { return store.get(terminationRequestIdStorage, _contractId); } function _getDepositInitiatorFlagForTerminationParty(DataParser.TerminationParty _forParty) private pure returns (uint8) { if (_forParty == DataParser.TerminationParty.TERMINATION_EMPLOYER) { return 0; } else if (_forParty == DataParser.TerminationParty.TERMINATION_ASSIGNEE) { return _getBuyerDepositInitiatorFlag(); } assert(true); } }