{
    "Function": "slitherConstructorConstantVariables",
    "File": "src/Drips.sol",
    "Parent Contracts": [],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "abstract contract Drips {\n    /// @notice Maximum number of drips receivers of a single user.\n    /// Limits cost of changes in drips configuration.\n    uint256 internal constant _MAX_DRIPS_RECEIVERS = 100;\n    /// @notice The additional decimals for all amtPerSec values.\n    uint8 internal constant _AMT_PER_SEC_EXTRA_DECIMALS = 9;\n    /// @notice The multiplier for all amtPerSec values. It's `10 ** _AMT_PER_SEC_EXTRA_DECIMALS`.\n    uint256 internal constant _AMT_PER_SEC_MULTIPLIER = 1_000_000_000;\n    /// @notice The total amount the contract can keep track of each asset.\n    uint256 internal constant _MAX_TOTAL_DRIPS_BALANCE = uint128(type(int128).max);\n    /// @notice On every timestamp `T`, which is a multiple of `cycleSecs`, the receivers\n    /// gain access to drips received during `T - cycleSecs` to `T - 1`.\n    /// Always higher than 1.\n    // slither-disable-next-line naming-convention\n    uint32 internal immutable _cycleSecs;\n    /// @notice The storage slot holding a single `DripsStorage` structure.\n    bytes32 private immutable _dripsStorageSlot;\n\n    /// @notice Emitted when the drips configuration of a user is updated.\n    /// @param userId The user ID.\n    /// @param assetId The used asset ID\n    /// @param receiversHash The drips receivers list hash\n    /// @param dripsHistoryHash The drips history hash which was valid right before the update.\n    /// @param balance The new drips balance. These funds will be dripped to the receivers.\n    /// @param maxEnd The maximum end time of drips, when funds run out.\n    /// If funds run out after the timestamp `type(uint32).max`, it's set to `type(uint32).max`.\n    /// If the balance is 0 or there are no receivers, it's set to the current timestamp.\n    event DripsSet(\n        uint256 indexed userId,\n        uint256 indexed assetId,\n        bytes32 indexed receiversHash,\n        bytes32 dripsHistoryHash,\n        uint128 balance,\n        uint32 maxEnd\n    );\n\n    /// @notice Emitted when a user is seen in a drips receivers list.\n    /// @param receiversHash The drips receivers list hash\n    /// @param userId The user ID.\n    /// @param config The drips configuration.\n    event DripsReceiverSeen(\n        bytes32 indexed receiversHash, uint256 indexed userId, DripsConfig config\n    );\n\n    /// @notice Emitted when drips are received.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @param amt The received amount.\n    /// @param receivableCycles The number of cycles which still can be received.\n    event ReceivedDrips(\n        uint256 indexed userId, uint256 indexed assetId, uint128 amt, uint32 receivableCycles\n    );\n\n    /// @notice Emitted when drips are squeezed.\n    /// @param userId The squeezing user ID.\n    /// @param assetId The used asset ID.\n    /// @param senderId The ID of the user sending drips which are squeezed.\n    /// @param amt The squeezed amount.\n    /// @param dripsHistoryHashes The history hashes of all squeezed drips history entries.\n    /// Each history hash matches `dripsHistoryHash` emitted in its `DripsSet`\n    /// when the squeezed drips configuration was set.\n    /// Sorted in the oldest drips configuration to the newest.\n    event SqueezedDrips(\n        uint256 indexed userId,\n        uint256 indexed assetId,\n        uint256 indexed senderId,\n        uint128 amt,\n        bytes32[] dripsHistoryHashes\n    );\n\n    struct DripsStorage {\n        /// @notice User drips states.\n        /// The keys are the asset ID and the user ID.\n        mapping(uint256 => mapping(uint256 => DripsState)) states;\n    }\n\n    struct DripsState {\n        /// @notice The drips history hash, see `_hashDripsHistory`.\n        bytes32 dripsHistoryHash;\n        /// @notice The next squeezable timestamps. The key is the sender's user ID.\n        /// Each `N`th element of the array is the next squeezable timestamp\n        /// of the `N`th sender's drips configuration in effect in the current cycle.\n        mapping(uint256 => uint32[2 ** 32]) nextSqueezed;\n        /// @notice The drips receivers list hash, see `_hashDrips`.\n        bytes32 dripsHash;\n        /// @notice The next cycle to be received\n        uint32 nextReceivableCycle;\n        /// @notice The time when drips have been configured for the last time\n        uint32 updateTime;\n        /// @notice The maximum end time of drips\n        uint32 maxEnd;\n        /// @notice The balance when drips have been configured for the last time\n        uint128 balance;\n        /// @notice The number of drips configurations seen in the current cycle\n        uint32 currCycleConfigs;\n        /// @notice The changes of received amounts on specific cycle.\n        /// The keys are cycles, each cycle `C` becomes receivable on timestamp `C * cycleSecs`.\n        /// Values for cycles before `nextReceivableCycle` are guaranteed to be zeroed.\n        /// This means that the value of `amtDeltas[nextReceivableCycle].thisCycle` is always\n        /// relative to 0 or in other words it's an absolute value independent from other cycles.\n        mapping(uint32 => AmtDelta) amtDeltas;\n    }\n\n    struct AmtDelta {\n        /// @notice Amount delta applied on this cycle\n        int128 thisCycle;\n        /// @notice Amount delta applied on the next cycle\n        int128 nextCycle;\n    }\n\n    /// @param cycleSecs The length of cycleSecs to be used in the contract instance.\n    /// Low value makes funds more available by shortening the average time of funds being frozen\n    /// between being taken from the users' drips balances and being receivable by their receivers.\n    /// High value makes receiving cheaper by making it process less cycles for a given time range.\n    /// Must be higher than 1.\n    /// @param dripsStorageSlot The storage slot to holding a single `DripsStorage` structure.\n    constructor(uint32 cycleSecs, bytes32 dripsStorageSlot) {\n        require(cycleSecs > 1, \"Cycle length too low\");\n        _cycleSecs = cycleSecs;\n        _dripsStorageSlot = dripsStorageSlot;\n    }\n\n    /// @notice Receive drips from unreceived cycles of the user.\n    /// Received drips cycles won't need to be analyzed ever again.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @param maxCycles The maximum number of received drips cycles.\n    /// If too low, receiving will be cheap, but may not cover many cycles.\n    /// If too high, receiving may become too expensive to fit in a single transaction.\n    /// @return receivedAmt The received amount\n    function _receiveDrips(uint256 userId, uint256 assetId, uint32 maxCycles)\n        internal\n        returns (uint128 receivedAmt)\n    {\n        uint32 receivableCycles;\n        uint32 fromCycle;\n        uint32 toCycle;\n        int128 finalAmtPerCycle;\n        (receivedAmt, receivableCycles, fromCycle, toCycle, finalAmtPerCycle) =\n            _receiveDripsResult(userId, assetId, maxCycles);\n        if (fromCycle != toCycle) {\n            DripsState storage state = _dripsStorage().states[assetId][userId];\n            state.nextReceivableCycle = toCycle;\n            mapping(uint32 => AmtDelta) storage amtDeltas = state.amtDeltas;\n            for (uint32 cycle = fromCycle; cycle < toCycle; cycle++) {\n                delete amtDeltas[cycle];\n            }\n            // The next cycle delta must be relative to the last received cycle, which got zeroed.\n            // In other words the next cycle delta must be an absolute value.\n            if (finalAmtPerCycle != 0) {\n                amtDeltas[toCycle].thisCycle += finalAmtPerCycle;\n            }\n        }\n        emit ReceivedDrips(userId, assetId, receivedAmt, receivableCycles);\n    }\n\n    /// @notice Calculate effects of calling `_receiveDrips` with the given parameters.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @param maxCycles The maximum number of received drips cycles.\n    /// If too low, receiving will be cheap, but may not cover many cycles.\n    /// If too high, receiving may become too expensive to fit in a single transaction.\n    /// @return receivedAmt The amount which would be received\n    /// @return receivableCycles The number of cycles which would still be receivable after the call\n    /// @return fromCycle The cycle from which funds would be received\n    /// @return toCycle The cycle to which funds would be received\n    /// @return amtPerCycle The amount per cycle when `toCycle` starts.\n    function _receiveDripsResult(uint256 userId, uint256 assetId, uint32 maxCycles)\n        internal\n        view\n        returns (\n            uint128 receivedAmt,\n            uint32 receivableCycles,\n            uint32 fromCycle,\n            uint32 toCycle,\n            int128 amtPerCycle\n        )\n    {\n        (fromCycle, toCycle) = _receivableDripsCyclesRange(userId, assetId);\n        if (toCycle - fromCycle > maxCycles) {\n            receivableCycles = toCycle - fromCycle - maxCycles;\n            toCycle -= receivableCycles;\n        }\n        DripsState storage state = _dripsStorage().states[assetId][userId];\n        for (uint32 cycle = fromCycle; cycle < toCycle; cycle++) {\n            amtPerCycle += state.amtDeltas[cycle].thisCycle;\n            receivedAmt += uint128(amtPerCycle);\n            amtPerCycle += state.amtDeltas[cycle].nextCycle;\n        }\n    }\n\n    /// @notice Counts cycles from which drips can be received.\n    /// This function can be used to detect that there are\n    /// too many cycles to analyze in a single transaction.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @return cycles The number of cycles which can be flushed\n    function _receivableDripsCycles(uint256 userId, uint256 assetId)\n        internal\n        view\n        returns (uint32 cycles)\n    {\n        (uint32 fromCycle, uint32 toCycle) = _receivableDripsCyclesRange(userId, assetId);\n        return toCycle - fromCycle;\n    }\n\n    /// @notice Calculates the cycles range from which drips can be received.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @return fromCycle The cycle from which funds can be received\n    /// @return toCycle The cycle to which funds can be received\n    function _receivableDripsCyclesRange(uint256 userId, uint256 assetId)\n        private\n        view\n        returns (uint32 fromCycle, uint32 toCycle)\n    {\n        fromCycle = _dripsStorage().states[assetId][userId].nextReceivableCycle;\n        toCycle = _cycleOf(_currTimestamp());\n        // slither-disable-next-line timestamp\n        if (fromCycle == 0 || toCycle < fromCycle) {\n            toCycle = fromCycle;\n        }\n    }\n\n    /// @notice Receive drips from the currently running cycle from a single sender.\n    /// It doesn't receive drips from the previous, finished cycles, to do that use `_receiveDrips`.\n    /// Squeezed funds won't be received in the next calls to `_squeezeDrips` or `_receiveDrips`.\n    /// Only funds dripped before `block.timestamp` can be squeezed.\n    /// @param userId The ID of the user receiving drips to squeeze funds for.\n    /// @param assetId The used asset ID.\n    /// @param senderId The ID of the user sending drips to squeeze funds from.\n    /// @param historyHash The sender's history hash which was valid right before\n    /// they set up the sequence of configurations described by `dripsHistory`.\n    /// @param dripsHistory The sequence of the sender's drips configurations.\n    /// It can start at an arbitrary past configuration, but must describe all the configurations\n    /// which have been used since then including the current one, in the chronological order.\n    /// Only drips described by `dripsHistory` will be squeezed.\n    /// If `dripsHistory` entries have no receivers, they won't be squeezed.\n    /// @return amt The squeezed amount.\n    function _squeezeDrips(\n        uint256 userId,\n        uint256 assetId,\n        uint256 senderId,\n        bytes32 historyHash,\n        DripsHistory[] memory dripsHistory\n    ) internal returns (uint128 amt) {\n        uint256 squeezedNum;\n        uint256[] memory squeezedRevIdxs;\n        bytes32[] memory historyHashes;\n        uint256 currCycleConfigs;\n        (amt, squeezedNum, squeezedRevIdxs, historyHashes, currCycleConfigs) =\n            _squeezeDripsResult(userId, assetId, senderId, historyHash, dripsHistory);\n        bytes32[] memory squeezedHistoryHashes = new bytes32[](squeezedNum);\n        DripsState storage state = _dripsStorage().states[assetId][userId];\n        uint32[2 ** 32] storage nextSqueezed = state.nextSqueezed[senderId];\n        for (uint256 i = 0; i < squeezedNum; i++) {\n            // `squeezedRevIdxs` are sorted from the newest configuration to the oldest,\n            // but we need to consume them from the oldest to the newest.\n            uint256 revIdx = squeezedRevIdxs[squeezedNum - i - 1];\n            squeezedHistoryHashes[i] = historyHashes[historyHashes.length - revIdx];\n            nextSqueezed[currCycleConfigs - revIdx] = _currTimestamp();\n        }\n        uint32 cycleStart = _currCycleStart();\n        _addDeltaRange(state, cycleStart, cycleStart + 1, -int256(amt * _AMT_PER_SEC_MULTIPLIER));\n        emit SqueezedDrips(userId, assetId, senderId, amt, squeezedHistoryHashes);\n    }\n\n    /// @notice Calculate effects of calling `_squeezeDrips` with the given parameters.\n    /// See its documentation for more details.\n    /// @param userId The ID of the user receiving drips to squeeze funds for.\n    /// @param assetId The used asset ID.\n    /// @param senderId The ID of the user sending drips to squeeze funds from.\n    /// @param historyHash The sender's history hash which was valid right before `dripsHistory`.\n    /// @param dripsHistory The sequence of the sender's drips configurations.\n    /// @return amt The squeezed amount.\n    /// @return squeezedNum The number of squeezed history entries.\n    /// @return squeezedRevIdxs The indexes of the squeezed history entries.\n    /// The indexes are reversed, meaning that to get the actual index in an array,\n    /// they must counted from the end of arrays, as in `arrayLength - squeezedRevIdxs[i]`.\n    /// These indexes can be safely used to access `dripsHistory`, `historyHashes`\n    /// and `nextSqueezed` regardless of their lengths.\n    /// `squeezeRevIdxs` is sorted ascending, from pointing at the most recent entry to the oldest.\n    /// @return historyHashes The history hashes valid for squeezing each of `dripsHistory` entries.\n    /// In other words history hashes which had been valid right before each drips\n    /// configuration was set, matching `dripsHistoryHash` emitted in its `DripsSet`.\n    /// The first item is always equal to `historyHash`.\n    /// @return currCycleConfigs The number of the sender's\n    /// drips configurations which have been seen in the current cycle.\n    /// This is also the number of used entries in each of the sender's `nextSqueezed` arrays.\n    function _squeezeDripsResult(\n        uint256 userId,\n        uint256 assetId,\n        uint256 senderId,\n        bytes32 historyHash,\n        DripsHistory[] memory dripsHistory\n    )\n        internal\n        view\n        returns (\n            uint128 amt,\n            uint256 squeezedNum,\n            uint256[] memory squeezedRevIdxs,\n            bytes32[] memory historyHashes,\n            uint256 currCycleConfigs\n        )\n    {\n        {\n            DripsState storage sender = _dripsStorage().states[assetId][senderId];\n            historyHashes = _verifyDripsHistory(historyHash, dripsHistory, sender.dripsHistoryHash);\n            // If the last update was not in the current cycle,\n            // there's only the single latest history entry to squeeze in the current cycle.\n            currCycleConfigs = 1;\n            // slither-disable-next-line timestamp\n            if (sender.updateTime >= _currCycleStart()) currCycleConfigs = sender.currCycleConfigs;\n        }\n        squeezedRevIdxs = new uint256[](dripsHistory.length);\n        uint32[2 ** 32] storage nextSqueezed =\n            _dripsStorage().states[assetId][userId].nextSqueezed[senderId];\n        uint32 squeezeEndCap = _currTimestamp();\n        for (uint256 i = 1; i <= dripsHistory.length && i <= currCycleConfigs; i++) {\n            DripsHistory memory drips = dripsHistory[dripsHistory.length - i];\n            if (drips.receivers.length != 0) {\n                uint32 squeezeStartCap = nextSqueezed[currCycleConfigs - i];\n                if (squeezeStartCap < _currCycleStart()) squeezeStartCap = _currCycleStart();\n                if (squeezeStartCap < squeezeEndCap) {\n                    squeezedRevIdxs[squeezedNum++] = i;\n                    amt += _squeezedAmt(userId, drips, squeezeStartCap, squeezeEndCap);\n                }\n            }\n            squeezeEndCap = drips.updateTime;\n        }\n    }\n\n    /// @notice Verify a drips history and revert if it's invalid.\n    /// @param historyHash The user's history hash which was valid right before `dripsHistory`.\n    /// @param dripsHistory The sequence of the user's drips configurations.\n    /// @param finalHistoryHash The history hash at the end of `dripsHistory`.\n    /// @return historyHashes The history hashes valid for squeezing each of `dripsHistory` entries.\n    /// In other words history hashes which had been valid right before each drips\n    /// configuration was set, matching `dripsHistoryHash`es emitted in `DripsSet`.\n    /// The first item is always equal to `historyHash` and `finalHistoryHash` is never included.\n    function _verifyDripsHistory(\n        bytes32 historyHash,\n        DripsHistory[] memory dripsHistory,\n        bytes32 finalHistoryHash\n    ) private pure returns (bytes32[] memory historyHashes) {\n        historyHashes = new bytes32[](dripsHistory.length);\n        for (uint256 i = 0; i < dripsHistory.length; i++) {\n            DripsHistory memory drips = dripsHistory[i];\n            bytes32 dripsHash = drips.dripsHash;\n            if (drips.receivers.length != 0) {\n                require(dripsHash == 0, \"Drips history entry with hash and receivers\");\n                dripsHash = _hashDrips(drips.receivers);\n            }\n            historyHashes[i] = historyHash;\n            historyHash = _hashDripsHistory(historyHash, dripsHash, drips.updateTime, drips.maxEnd);\n        }\n        // slither-disable-next-line incorrect-equality,timestamp\n        require(historyHash == finalHistoryHash, \"Invalid drips history\");\n    }\n\n    /// @notice Calculate the amount squeezable by a user from a single drips history entry.\n    /// @param userId The ID of the user to squeeze drips for.\n    /// @param dripsHistory The squeezed history entry.\n    /// @param squeezeStartCap The squeezed time range start.\n    /// @param squeezeEndCap The squeezed time range end.\n    /// @return squeezedAmt The squeezed amount.\n    function _squeezedAmt(\n        uint256 userId,\n        DripsHistory memory dripsHistory,\n        uint32 squeezeStartCap,\n        uint32 squeezeEndCap\n    ) private view returns (uint128 squeezedAmt) {\n        DripsReceiver[] memory receivers = dripsHistory.receivers;\n        // Binary search for the `idx` of the first occurrence of `userId`\n        uint256 idx = 0;\n        for (uint256 idxCap = receivers.length; idx < idxCap;) {\n            uint256 idxMid = (idx + idxCap) / 2;\n            if (receivers[idxMid].userId < userId) {\n                idx = idxMid + 1;\n            } else {\n                idxCap = idxMid;\n            }\n        }\n        uint32 updateTime = dripsHistory.updateTime;\n        uint32 maxEnd = dripsHistory.maxEnd;\n        uint256 amt = 0;\n        for (; idx < receivers.length; idx++) {\n            DripsReceiver memory receiver = receivers[idx];\n            if (receiver.userId != userId) break;\n            (uint32 start, uint32 end) =\n                _dripsRange(receiver, updateTime, maxEnd, squeezeStartCap, squeezeEndCap);\n            amt += _drippedAmt(receiver.config.amtPerSec(), start, end);\n        }\n        return uint128(amt);\n    }\n\n    /// @notice Current user drips state.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @return dripsHash The current drips receivers list hash, see `_hashDrips`\n    /// @return dripsHistoryHash The current drips history hash, see `_hashDripsHistory`.\n    /// @return updateTime The time when drips have been configured for the last time\n    /// @return balance The balance when drips have been configured for the last time\n    /// @return maxEnd The current maximum end time of drips\n    function _dripsState(uint256 userId, uint256 assetId)\n        internal\n        view\n        returns (\n            bytes32 dripsHash,\n            bytes32 dripsHistoryHash,\n            uint32 updateTime,\n            uint128 balance,\n            uint32 maxEnd\n        )\n    {\n        DripsState storage state = _dripsStorage().states[assetId][userId];\n        return\n            (state.dripsHash, state.dripsHistoryHash, state.updateTime, state.balance, state.maxEnd);\n    }\n\n    /// @notice User drips balance at a given timestamp\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @param receivers The current drips receivers list\n    /// @param timestamp The timestamps for which balance should be calculated.\n    /// It can't be lower than the timestamp of the last call to `setDrips`.\n    /// If it's bigger than `block.timestamp`, then it's a prediction assuming\n    /// that `setDrips` won't be called before `timestamp`.\n    /// @return balance The user balance on `timestamp`\n    function _balanceAt(\n        uint256 userId,\n        uint256 assetId,\n        DripsReceiver[] memory receivers,\n        uint32 timestamp\n    ) internal view returns (uint128 balance) {\n        DripsState storage state = _dripsStorage().states[assetId][userId];\n        require(timestamp >= state.updateTime, \"Timestamp before last drips update\");\n        require(_hashDrips(receivers) == state.dripsHash, \"Invalid current drips list\");\n        return _balanceAt(state.balance, state.updateTime, state.maxEnd, receivers, timestamp);\n    }\n\n    /// @notice Calculates the drips balance at a given timestamp.\n    /// @param lastBalance The balance when drips have started\n    /// @param lastUpdate The timestamp when drips have started.\n    /// @param maxEnd The maximum end time of drips\n    /// @param receivers The list of drips receivers.\n    /// @param timestamp The timestamps for which balance should be calculated.\n    /// It can't be lower than `lastUpdate`.\n    /// If it's bigger than `block.timestamp`, then it's a prediction assuming\n    /// that `setDrips` won't be called before `timestamp`.\n    /// @return balance The user balance on `timestamp`\n    function _balanceAt(\n        uint128 lastBalance,\n        uint32 lastUpdate,\n        uint32 maxEnd,\n        DripsReceiver[] memory receivers,\n        uint32 timestamp\n    ) private view returns (uint128 balance) {\n        balance = lastBalance;\n        for (uint256 i = 0; i < receivers.length; i++) {\n            DripsReceiver memory receiver = receivers[i];\n            (uint32 start, uint32 end) = _dripsRange({\n                receiver: receiver,\n                updateTime: lastUpdate,\n                maxEnd: maxEnd,\n                startCap: lastUpdate,\n                endCap: timestamp\n            });\n            balance -= uint128(_drippedAmt(receiver.config.amtPerSec(), start, end));\n        }\n    }\n\n    /// @notice Sets the user's drips configuration.\n    /// @param userId The user ID\n    /// @param assetId The used asset ID\n    /// @param currReceivers The list of the drips receivers set in the last drips update\n    /// of the user.\n    /// If this is the first update, pass an empty array.\n    /// @param balanceDelta The drips balance change being applied.\n    /// Positive when adding funds to the drips balance, negative to removing them.\n    /// @param newReceivers The list of the drips receivers of the user to be set.\n    /// Must be sorted, deduplicated and without 0 amtPerSecs.\n    /// @param maxEndHint1 An optional parameter allowing gas optimization, pass `0` to ignore it.\n    /// The first hint for finding the maximum end time when all drips stop due to funds\n    /// running out after the balance is updated and the new receivers list is applied.\n    /// Hints have no effect on the results of calling this function, except potentially saving gas.\n    /// Hints are Unix timestamps used as the starting points for binary search for the time\n    /// when funds run out in the range of timestamps from the current block's to `2^32`.\n    /// Hints lower than the current timestamp are ignored.\n    /// You can provide zero, one or two hints. The order of hints doesn't matter.\n    /// Hints are the most effective when one of them is lower than or equal to\n    /// the last timestamp when funds are still dripping, and the other one is strictly larger\n    /// than that timestamp,the smaller the difference between such hints, the higher gas savings.\n    /// The savings are the highest possible when one of the hints is equal to\n    /// the last timestamp when funds are still dripping, and the other one is larger by 1.\n    /// It's worth noting that the exact timestamp of the block in which this function is executed\n    /// may affect correctness of the hints, especially if they're precise.\n    /// Hints don't provide any benefits when balance is not enough to cover\n    /// a single second of dripping or is enough to cover all drips until timestamp `2^32`.\n    /// Even inaccurate hints can be useful, and providing a single hint\n    /// or two hints that don't enclose the time when funds run out can still save some gas.\n    /// Providing poor hints that don't reduce the number of binary search steps\n    /// may cause slightly higher gas usage than not providing any hints.\n    /// @param maxEndHint2 An optional parameter allowing gas optimization, pass `0` to ignore it.\n    /// The second hint for finding the maximum end time, see `maxEndHint1` docs for more details.\n    /// @return realBalanceDelta The actually applied drips balance change.\n    function _setDrips(\n        uint256 userId,\n        uint256 assetId,\n        DripsReceiver[] memory currReceivers,\n        int128 balanceDelta,\n        DripsReceiver[] memory newReceivers,\n        // slither-disable-next-line similar-names\n        uint32 maxEndHint1,\n        uint32 maxEndHint2\n    ) internal returns (int128 realBalanceDelta) {\n        DripsState storage state = _dripsStorage().states[assetId][userId];\n        // slither-disable-next-line timestamp\n        require(_hashDrips(currReceivers) == state.dripsHash, \"Invalid current drips list\");\n        uint32 lastUpdate = state.updateTime;\n        uint128 newBalance;\n        uint32 newMaxEnd;\n        {\n            uint32 currMaxEnd = state.maxEnd;\n            int128 currBalance = int128(\n                _balanceAt(state.balance, lastUpdate, currMaxEnd, currReceivers, _currTimestamp())\n            );\n            realBalanceDelta = balanceDelta;\n            // Cap `realBalanceDelta` at withdrawal of the entire `currBalance`\n            if (realBalanceDelta < -currBalance) {\n                realBalanceDelta = -currBalance;\n            }\n            newBalance = uint128(currBalance + realBalanceDelta);\n            newMaxEnd = _calcMaxEnd(newBalance, newReceivers, maxEndHint1, maxEndHint2);\n            _updateReceiverStates(\n                _dripsStorage().states[assetId],\n                currReceivers,\n                lastUpdate,\n                currMaxEnd,\n                newReceivers,\n                newMaxEnd\n            );\n        }\n        state.updateTime = _currTimestamp();\n        state.maxEnd = newMaxEnd;\n        state.balance = newBalance;\n        bytes32 dripsHistory = state.dripsHistoryHash;\n        // slither-disable-next-line timestamp\n        if (dripsHistory != 0 && _cycleOf(lastUpdate) != _cycleOf(_currTimestamp())) {\n            state.currCycleConfigs = 2;\n        } else {\n            state.currCycleConfigs++;\n        }\n        bytes32 newDripsHash = _hashDrips(newReceivers);\n        state.dripsHistoryHash =\n            _hashDripsHistory(dripsHistory, newDripsHash, _currTimestamp(), newMaxEnd);\n        emit DripsSet(userId, assetId, newDripsHash, dripsHistory, newBalance, newMaxEnd);\n        // slither-disable-next-line timestamp\n        if (newDripsHash != state.dripsHash) {\n            state.dripsHash = newDripsHash;\n            for (uint256 i = 0; i < newReceivers.length; i++) {\n                DripsReceiver memory receiver = newReceivers[i];\n                emit DripsReceiverSeen(newDripsHash, receiver.userId, receiver.config);\n            }\n        }\n    }\n\n    /// @notice Calculates the maximum end time of drips.\n    /// @param balance The balance when drips have started\n    /// @param receivers The list of drips receivers.\n    /// Must be sorted, deduplicated and without 0 amtPerSecs.\n    /// @param hint1 The first hint for finding the maximum end time.\n    /// See `_setDrips` docs for `maxEndHint1` for more details.\n    /// @param hint2 The second hint for finding the maximum end time.\n    /// See `_setDrips` docs for `maxEndHint2` for more details.\n    /// @return maxEnd The maximum end time of drips\n    function _calcMaxEnd(\n        uint128 balance,\n        DripsReceiver[] memory receivers,\n        uint32 hint1,\n        uint32 hint2\n    ) private view returns (uint32 maxEnd) {\n        unchecked {\n            (uint256[] memory configs, uint256 configsLen) = _buildConfigs(receivers);\n\n            uint256 enoughEnd = _currTimestamp();\n            // slither-disable-start incorrect-equality,timestamp\n            if (configsLen == 0 || balance == 0) {\n                return uint32(enoughEnd);\n            }\n\n            uint256 notEnoughEnd = type(uint32).max;\n            if (_isBalanceEnough(balance, configs, configsLen, notEnoughEnd)) {\n                return uint32(notEnoughEnd);\n            }\n\n            if (hint1 > enoughEnd && hint1 < notEnoughEnd) {\n                if (_isBalanceEnough(balance, configs, configsLen, hint1)) {\n                    enoughEnd = hint1;\n                } else {\n                    notEnoughEnd = hint1;\n                }\n            }\n\n            if (hint2 > enoughEnd && hint2 < notEnoughEnd) {\n                if (_isBalanceEnough(balance, configs, configsLen, hint2)) {\n                    enoughEnd = hint2;\n                } else {\n                    notEnoughEnd = hint2;\n                }\n            }\n\n            while (true) {\n                uint256 end = (enoughEnd + notEnoughEnd) / 2;\n                if (end == enoughEnd) {\n                    return uint32(end);\n                }\n                if (_isBalanceEnough(balance, configs, configsLen, end)) {\n                    enoughEnd = end;\n                } else {\n                    notEnoughEnd = end;\n                }\n            }\n            // slither-disable-end incorrect-equality,timestamp\n        }\n    }\n\n    /// @notice Check if a given balance is enough to cover drips with the given `maxEnd`.\n    /// @param balance The balance when drips have started\n    /// @param configs The list of drips configurations\n    /// @param configsLen The length of `configs`\n    /// @param maxEnd The maximum end time of drips\n    /// @return isEnough `true` if the balance is enough, `false` otherwise\n    function _isBalanceEnough(\n        uint256 balance,\n        uint256[] memory configs,\n        uint256 configsLen,\n        uint256 maxEnd\n    ) private view returns (bool isEnough) {\n        unchecked {\n            uint256 spent = 0;\n            for (uint256 i = 0; i < configsLen; i++) {\n                (uint256 amtPerSec, uint256 start, uint256 end) = _getConfig(configs, i);\n                // slither-disable-next-line timestamp\n                if (maxEnd <= start) {\n                    continue;\n                }\n                // slither-disable-next-line timestamp\n                if (end > maxEnd) {\n                    end = maxEnd;\n                }\n                spent += _drippedAmt(amtPerSec, start, end);\n                if (spent > balance) {\n                    return false;\n                }\n            }\n            return true;\n        }\n    }\n\n    /// @notice Build a preprocessed list of drips configurations from receivers.\n    /// @param receivers The list of drips receivers.\n    /// Must be sorted, deduplicated and without 0 amtPerSecs.\n    /// @return configs The list of drips configurations\n    /// @return configsLen The length of `configs`\n    function _buildConfigs(DripsReceiver[] memory receivers)\n        private\n        view\n        returns (uint256[] memory configs, uint256 configsLen)\n    {\n        unchecked {\n            require(receivers.length <= _MAX_DRIPS_RECEIVERS, \"Too many drips receivers\");\n            configs = new uint256[](receivers.length);\n            for (uint256 i = 0; i < receivers.length; i++) {\n                DripsReceiver memory receiver = receivers[i];\n                if (i > 0) {\n                    require(_isOrdered(receivers[i - 1], receiver), \"Receivers not sorted\");\n                }\n                configsLen = _addConfig(configs, configsLen, receiver);\n            }\n        }\n    }\n\n    /// @notice Preprocess and add a drips receiver to the list of configurations.\n    /// @param configs The list of drips configurations\n    /// @param configsLen The length of `configs`\n    /// @param receiver The added drips receivers.\n    /// @return newConfigsLen The new length of `configs`\n    function _addConfig(uint256[] memory configs, uint256 configsLen, DripsReceiver memory receiver)\n        private\n        view\n        returns (uint256 newConfigsLen)\n    {\n        uint256 amtPerSec = receiver.config.amtPerSec();\n        require(amtPerSec != 0, \"Drips receiver amtPerSec is zero\");\n        (uint256 start, uint256 end) =\n            _dripsRangeInFuture(receiver, _currTimestamp(), type(uint32).max);\n        // slither-disable-next-line incorrect-equality,timestamp\n        if (start == end) {\n            return configsLen;\n        }\n        configs[configsLen] = (amtPerSec << 64) | (start << 32) | end;\n        return configsLen + 1;\n    }\n\n    /// @notice Load a drips configuration from the list.\n    /// @param configs The list of drips configurations\n    /// @param idx The loaded configuration index. It must be smaller than the `configs` length.\n    /// @return amtPerSec The amount per second being dripped.\n    /// @return start The timestamp when dripping starts.\n    /// @return end The maximum timestamp when dripping ends.\n    function _getConfig(uint256[] memory configs, uint256 idx)\n        private\n        pure\n        returns (uint256 amtPerSec, uint256 start, uint256 end)\n    {\n        uint256 val;\n        // slither-disable-next-line assembly\n        assembly (\"memory-safe\") {\n            val := mload(add(32, add(configs, shl(5, idx))))\n        }\n        return (val >> 64, uint32(val >> 32), uint32(val));\n    }\n\n    /// @notice Calculates the hash of the drips configuration.\n    /// It's used to verify if drips configuration is the previously set one.\n    /// @param receivers The list of the drips receivers.\n    /// Must be sorted, deduplicated and without 0 amtPerSecs.\n    /// If the drips have never been updated, pass an empty array.\n    /// @return dripsHash The hash of the drips configuration\n    function _hashDrips(DripsReceiver[] memory receivers)\n        internal\n        pure\n        returns (bytes32 dripsHash)\n    {\n        if (receivers.length == 0) {\n            return bytes32(0);\n        }\n        return keccak256(abi.encode(receivers));\n    }\n\n    /// @notice Calculates the hash of the drips history after the drips configuration is updated.\n    /// @param oldDripsHistoryHash The history hash which was valid before the drips were updated.\n    /// The `dripsHistoryHash` of a user before they set drips for the first time is `0`.\n    /// @param dripsHash The hash of the drips receivers being set.\n    /// @param updateTime The timestamp when the drips are updated.\n    /// @param maxEnd The maximum end of the drips being set.\n    /// @return dripsHistoryHash The hash of the updated drips history.\n    function _hashDripsHistory(\n        bytes32 oldDripsHistoryHash,\n        bytes32 dripsHash,\n        uint32 updateTime,\n        uint32 maxEnd\n    ) internal pure returns (bytes32 dripsHistoryHash) {\n        return keccak256(abi.encode(oldDripsHistoryHash, dripsHash, updateTime, maxEnd));\n    }\n\n    /// @notice Applies the effects of the change of the drips on the receivers' drips states.\n    /// @param states The drips states for the used asset.\n    /// @param currReceivers The list of the drips receivers set in the last drips update\n    /// of the user.\n    /// If this is the first update, pass an empty array.\n    /// @param lastUpdate the last time the sender updated the drips.\n    /// If this is the first update, pass zero.\n    /// @param currMaxEnd The maximum end time of drips according to the last drips update.\n    /// @param newReceivers  The list of the drips receivers of the user to be set.\n    /// Must be sorted, deduplicated and without 0 amtPerSecs.\n    /// @param newMaxEnd The maximum end time of drips according to the new drips configuration.\n    function _updateReceiverStates(\n        mapping(uint256 => DripsState) storage states,\n        DripsReceiver[] memory currReceivers,\n        uint32 lastUpdate,\n        uint32 currMaxEnd,\n        DripsReceiver[] memory newReceivers,\n        uint32 newMaxEnd\n    ) private {\n        uint256 currIdx = 0;\n        uint256 newIdx = 0;\n        while (true) {\n            bool pickCurr = currIdx < currReceivers.length;\n            // slither-disable-next-line uninitialized-local\n            DripsReceiver memory currRecv;\n            if (pickCurr) {\n                currRecv = currReceivers[currIdx];\n            }\n\n            bool pickNew = newIdx < newReceivers.length;\n            // slither-disable-next-line uninitialized-local\n            DripsReceiver memory newRecv;\n            if (pickNew) {\n                newRecv = newReceivers[newIdx];\n            }\n\n            // Limit picking both curr and new to situations when they differ only by time\n            if (\n                pickCurr && pickNew\n                    && (\n                        currRecv.userId != newRecv.userId\n                            || currRecv.config.amtPerSec() != newRecv.config.amtPerSec()\n                    )\n            ) {\n                pickCurr = _isOrdered(currRecv, newRecv);\n                pickNew = !pickCurr;\n            }\n\n            if (pickCurr && pickNew) {\n                // Shift the existing drip to fulfil the new configuration\n                DripsState storage state = states[currRecv.userId];\n                (uint32 currStart, uint32 currEnd) =\n                    _dripsRangeInFuture(currRecv, lastUpdate, currMaxEnd);\n                (uint32 newStart, uint32 newEnd) =\n                    _dripsRangeInFuture(newRecv, _currTimestamp(), newMaxEnd);\n                {\n                    int256 amtPerSec = int256(uint256(currRecv.config.amtPerSec()));\n                    // Move the start and end times if updated\n                    _addDeltaRange(state, currStart, newStart, -amtPerSec);\n                    _addDeltaRange(state, currEnd, newEnd, amtPerSec);\n                }\n                // Ensure that the user receives the updated cycles\n                uint32 currStartCycle = _cycleOf(currStart);\n                uint32 newStartCycle = _cycleOf(newStart);\n                // The `currStartCycle > newStartCycle` check is just an optimization.\n                // If it's false, then `state.nextReceivableCycle > newStartCycle` must be\n                // false too, there's no need to pay for the storage access to check it.\n                // slither-disable-next-line timestamp\n                if (currStartCycle > newStartCycle && state.nextReceivableCycle > newStartCycle) {\n                    state.nextReceivableCycle = newStartCycle;\n                }\n            } else if (pickCurr) {\n                // Remove an existing drip\n                // slither-disable-next-line similar-names\n                DripsState storage state = states[currRecv.userId];\n                (uint32 start, uint32 end) = _dripsRangeInFuture(currRecv, lastUpdate, currMaxEnd);\n                // slither-disable-next-line similar-names\n                int256 amtPerSec = int256(uint256(currRecv.config.amtPerSec()));\n                _addDeltaRange(state, start, end, -amtPerSec);\n            } else if (pickNew) {\n                // Create a new drip\n                DripsState storage state = states[newRecv.userId];\n                // slither-disable-next-line uninitialized-local\n                (uint32 start, uint32 end) =\n                    _dripsRangeInFuture(newRecv, _currTimestamp(), newMaxEnd);\n                int256 amtPerSec = int256(uint256(newRecv.config.amtPerSec()));\n                _addDeltaRange(state, start, end, amtPerSec);\n                // Ensure that the user receives the updated cycles\n                uint32 startCycle = _cycleOf(start);\n                // slither-disable-next-line timestamp\n                if (state.nextReceivableCycle == 0 || state.nextReceivableCycle > startCycle) {\n                    state.nextReceivableCycle = startCycle;\n                }\n            } else {\n                break;\n            }\n\n            if (pickCurr) {\n                currIdx++;\n            }\n            if (pickNew) {\n                newIdx++;\n            }\n        }\n    }\n\n    /// @notice Calculates the time range in the future in which a receiver will be dripped to.\n    /// @param receiver The drips receiver\n    /// @param maxEnd The maximum end time of drips\n    function _dripsRangeInFuture(DripsReceiver memory receiver, uint32 updateTime, uint32 maxEnd)\n        private\n        view\n        returns (uint32 start, uint32 end)\n    {\n        return _dripsRange(receiver, updateTime, maxEnd, _currTimestamp(), type(uint32).max);\n    }\n\n    /// @notice Calculates the time range in which a receiver is to be dripped to.\n    /// This range is capped to provide a view on drips through a specific time window.\n    /// @param receiver The drips receiver\n    /// @param updateTime The time when drips are configured\n    /// @param maxEnd The maximum end time of drips\n    /// @param startCap The timestamp the drips range start should be capped to\n    /// @param endCap The timestamp the drips range end should be capped to\n    function _dripsRange(\n        DripsReceiver memory receiver,\n        uint32 updateTime,\n        uint32 maxEnd,\n        uint32 startCap,\n        uint32 endCap\n    ) private pure returns (uint32 start, uint32 end_) {\n        start = receiver.config.start();\n        // slither-disable-start timestamp\n        if (start == 0) {\n            start = updateTime;\n        }\n        uint40 end = uint40(start) + receiver.config.duration();\n        // slither-disable-next-line incorrect-equality\n        if (end == start || end > maxEnd) {\n            end = maxEnd;\n        }\n        if (start < startCap) {\n            start = startCap;\n        }\n        if (end > endCap) {\n            end = endCap;\n        }\n        if (end < start) {\n            end = start;\n        }\n        // slither-disable-end timestamp\n        return (start, uint32(end));\n    }\n\n    /// @notice Adds funds received by a user in a given time range\n    /// @param state The user state\n    /// @param start The timestamp from which the delta takes effect\n    /// @param end The timestamp until which the delta takes effect\n    /// @param amtPerSec The dripping rate\n    function _addDeltaRange(DripsState storage state, uint32 start, uint32 end, int256 amtPerSec)\n        private\n    {\n        // slither-disable-next-line incorrect-equality,timestamp\n        if (start == end) {\n            return;\n        }\n        mapping(uint32 => AmtDelta) storage amtDeltas = state.amtDeltas;\n        _addDelta(amtDeltas, start, amtPerSec);\n        _addDelta(amtDeltas, end, -amtPerSec);\n    }\n\n    /// @notice Adds delta of funds received by a user at a given time\n    /// @param amtDeltas The user amount deltas\n    /// @param timestamp The timestamp when the deltas need to be added\n    /// @param amtPerSec The dripping rate\n    function _addDelta(\n        mapping(uint32 => AmtDelta) storage amtDeltas,\n        uint256 timestamp,\n        int256 amtPerSec\n    ) private {\n        unchecked {\n            // In order to set a delta on a specific timestamp it must be introduced in two cycles.\n            // These formulas follow the logic from `_drippedAmt`, see it for more details.\n            int256 amtPerSecMultiplier = int256(_AMT_PER_SEC_MULTIPLIER);\n            int256 fullCycle = (int256(uint256(_cycleSecs)) * amtPerSec) / amtPerSecMultiplier;\n            // slither-disable-next-line weak-prng\n            int256 nextCycle = (int256(timestamp % _cycleSecs) * amtPerSec) / amtPerSecMultiplier;\n            AmtDelta storage amtDelta = amtDeltas[_cycleOf(uint32(timestamp))];\n            // Any over- or under-flows are fine, they're guaranteed to be fixed by a matching\n            // under- or over-flow from the other call to `_addDelta` made by `_addDeltaRange`.\n            // This is because the total balance of `Drips` can never exceed `type(int128).max`,\n            // so in the end no amtDelta can have delta higher than `type(int128).max`.\n            amtDelta.thisCycle += int128(fullCycle - nextCycle);\n            amtDelta.nextCycle += int128(nextCycle);\n        }\n    }\n\n    /// @notice Checks if two receivers fulfil the sortedness requirement of the receivers list.\n    /// @param prev The previous receiver\n    /// @param prev The next receiver\n    function _isOrdered(DripsReceiver memory prev, DripsReceiver memory next)\n        private\n        pure\n        returns (bool)\n    {\n        if (prev.userId != next.userId) {\n            return prev.userId < next.userId;\n        }\n        return prev.config.lt(next.config);\n    }\n\n    /// @notice Calculates the amount dripped over a time range.\n    /// The amount dripped in the `N`th second of each cycle is:\n    /// `(N + 1) * amtPerSec / AMT_PER_SEC_MULTIPLIER - N * amtPerSec / AMT_PER_SEC_MULTIPLIER`.\n    /// For a range of `N`s from `0` to `M` the sum of the dripped amounts is calculated as:\n    /// `M * amtPerSec / AMT_PER_SEC_MULTIPLIER` assuming that `M <= cycleSecs`.\n    /// For an arbitrary time range across multiple cycles the amount is calculated as the sum of\n    /// the amount dripped in the start cycle, each of the full cycles in between and the end cycle.\n    /// This algorithm has the following properties:\n    /// - During every second full units are dripped, there are no partially dripped units.\n    /// - Undripped fractions are dripped when they add up into full units.\n    /// - Undripped fractions don't add up across cycle end boundaries.\n    /// - Some seconds drip more units and some less.\n    /// - Every `N`th second of each cycle drips the same amount.\n    /// - Every full cycle drips the same amount.\n    /// - The amount dripped in a given second is independent from the dripping start and end.\n    /// - Dripping over time ranges `A:B` and then `B:C` is equivalent to dripping over `A:C`.\n    /// - Different drips existing in the system don't interfere with each other.\n    /// @param amtPerSec The dripping rate\n    /// @param start The dripping start time\n    /// @param end The dripping end time\n    /// @param amt The dripped amount\n    function _drippedAmt(uint256 amtPerSec, uint256 start, uint256 end)\n        private\n        view\n        returns (uint256 amt)\n    {\n        // This function is written in Yul because it can be called thousands of times\n        // per transaction and it needs to be optimized as much as possible.\n        // As of Solidity 0.8.13, rewriting it in unchecked Solidity triples its gas cost.\n        uint256 cycleSecs = _cycleSecs;\n        // slither-disable-next-line assembly\n        assembly {\n            let endedCycles := sub(div(end, cycleSecs), div(start, cycleSecs))\n            // slither-disable-next-line divide-before-multiply\n            let amtPerCycle := div(mul(cycleSecs, amtPerSec), _AMT_PER_SEC_MULTIPLIER)\n            amt := mul(endedCycles, amtPerCycle)\n            // slither-disable-next-line weak-prng\n            let amtEnd := div(mul(mod(end, cycleSecs), amtPerSec), _AMT_PER_SEC_MULTIPLIER)\n            amt := add(amt, amtEnd)\n            // slither-disable-next-line weak-prng\n            let amtStart := div(mul(mod(start, cycleSecs), amtPerSec), _AMT_PER_SEC_MULTIPLIER)\n            amt := sub(amt, amtStart)\n        }\n    }\n\n    /// @notice Calculates the cycle containing the given timestamp.\n    /// @param timestamp The timestamp.\n    /// @return cycle The cycle containing the timestamp.\n    function _cycleOf(uint32 timestamp) private view returns (uint32 cycle) {\n        unchecked {\n            return timestamp / _cycleSecs + 1;\n        }\n    }\n\n    /// @notice The current timestamp, casted to the contract's internal representation.\n    /// @return timestamp The current timestamp\n    function _currTimestamp() private view returns (uint32 timestamp) {\n        return uint32(block.timestamp);\n    }\n\n    /// @notice The current cycle start timestamp, casted to the contract's internal representation.\n    /// @return timestamp The current cycle start timestamp\n    function _currCycleStart() private view returns (uint32 timestamp) {\n        uint32 currTimestamp = _currTimestamp();\n        // slither-disable-next-line weak-prng\n        return currTimestamp - (currTimestamp % _cycleSecs);\n    }\n\n    /// @notice Returns the Drips storage.\n    /// @return dripsStorage The storage.\n    function _dripsStorage() private view returns (DripsStorage storage dripsStorage) {\n        bytes32 slot = _dripsStorageSlot;\n        // slither-disable-next-line assembly\n        assembly {\n            dripsStorage.slot := slot\n        }\n    }\n}"
}