// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {KibbleConstants as K} from "./KibbleConstants.sol"; /// @title EmissionMath /// @notice Pure era schedule (docs §5). Time is "mining time" t = blocks since block 0. /// @dev Reward per block is never stored as a rounded number: the reward over b blocks of era e is /// b × eraEmission(e) / ERA_LENGTH, with eraEmission(e) = ERA1_EMISSION >> (e - 1). /// A full era 1 is therefore exactly 4,500,000e18. Emission stops once eraEmission(e) == 0. library EmissionMath { /// @notice Era containing mining-time t (era 1 = t in [0, ERA_LENGTH)). function eraAt(uint256 t) internal pure returns (uint256) { return t / K.ERA_LENGTH + 1; } /// @notice Total emission of era e (0 for e == 0 or once halved to zero). function eraEmission(uint256 e) internal pure returns (uint256) { if (e == 0 || e > 256) return 0; return K.ERA1_EMISSION >> (e - 1); } /// @notice Display value of the reward per block in era e (truncated to wei). Accounting never uses it. function rewardPerBlockOf(uint256 e) internal pure returns (uint256) { return eraEmission(e) / K.ERA_LENGTH; } /// @notice Cumulative emission of all full eras 1..n (docs §5 "Total mined" column). function cumulativeThroughEra(uint256 n) internal pure returns (uint256 total) { for (uint256 e = 1; e <= n; ++e) { uint256 em = eraEmission(e); if (em == 0) break; total += em; } } /// @notice Maximum emission that the schedule allows over mining-time [0, t) (blocks with zero hashrate included). function scheduledAt(uint256 t) internal pure returns (uint256) { uint256 e = eraAt(t); uint256 full = cumulativeThroughEra(e - 1); uint256 into = t - (e - 1) * K.ERA_LENGTH; return full + into * eraEmission(e) / K.ERA_LENGTH; } /// @notice Reward-per-hash increment and allocated emission for [from, to) at constant hashrate h. /// Splits the range per era segment (docs §12 "Era boundaries"). /// @return dAcc increment of the accumulator, scaled by `precision` /// @return allocatedScaled emission distributed in the range, scaled by `precision` (sum of dAcc × h per segment, /// an exact upper bound of what wallets can claim for the range) function accrue(uint256 from, uint256 to, uint256 h, uint256 precision) internal pure returns (uint256 dAcc, uint256 allocatedScaled) { if (h == 0 || to <= from) return (0, 0); while (from < to) { uint256 e = eraAt(from); uint256 em = eraEmission(e); if (em == 0) break; uint256 segEnd = e * K.ERA_LENGTH; if (segEnd > to) segEnd = to; uint256 b = segEnd - from; uint256 d = (b * em * precision) / (K.ERA_LENGTH * h); dAcc += d; allocatedScaled += d * h; from = segEnd; } } }