Miner.sol
615 lines · sha256 628077e0e46d05d9fef9793d7de228d625f8eabbfa494fe2465171a82c924b66 · Raw
| 1 | // SPDX-License-Identifier: MIT |
| 2 | pragma solidity ^0.8.26; |
| 3 | |
| 4 | import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; |
| 5 | import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; |
| 6 | import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; |
| 7 | import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol"; |
| 8 | import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; |
| 9 | import {KibbleToken} from "./KibbleToken.sol"; |
| 10 | import {Emission} from "./Emission.sol"; |
| 11 | import {Genesis} from "./Genesis.sol"; |
| 12 | import {Oracle} from "./Oracle.sol"; |
| 13 | import {Zapper} from "./Zapper.sol"; |
| 14 | import {Burner} from "./Burner.sol"; |
| 15 | import {EmissionMath} from "./libraries/EmissionMath.sol"; |
| 16 | import {ExpiryBitmap} from "./libraries/ExpiryBitmap.sol"; |
| 17 | import {ChainBlock} from "./libraries/ChainBlock.sol"; |
| 18 | import {KibbleConstants as K} from "./libraries/KibbleConstants.sol"; |
| 19 | |
| 20 | /// @title Miner |
| 21 | /// @notice Rig balances, on/off state, power tanks, reward accounting, claims (docs §3, §4, §11, §12, §13). |
| 22 | /// |
| 23 | /// @dev Time. All accounting runs in "mining time" t = block - block0 (0 before block 0). Preordered rigs can be |
| 24 | /// powered and switched on before block 0, but mining time stays 0 until block 0, so nothing is drawn or mined |
| 25 | /// before it (docs §6). |
| 26 | /// |
| 27 | /// Power units. Tanks are stored in units of wei × 60,000, so one rig drains exactly 1e18 units per block |
| 28 | /// (1/60,000 HYPE) and a full era is exactly 3.6 HYPE per rig. Withdrawals floor back to wei. |
| 29 | /// |
| 30 | /// Two sub-tanks. `hypeUnits` (deposited in HYPE) and `kibbleUnits` (deposited in KIBBLE, credited at |
| 31 | /// KIBBLE × TWAP × 10/9, docs §4) with `kibbleAmount`, the KIBBLE backing `kibbleUnits`. Consuming x units |
| 32 | /// of the KIBBLE sub-tank burns kibbleAmount × x / kibbleUnits KIBBLE, so unused KIBBLE power is returned at |
| 33 | /// the deposit rate (docs §13). Several KIBBLE deposits are pooled at their weighted average rate. |
| 34 | /// Consumption order: KIBBLE-backed power first, then HYPE-backed. Withdrawal order: HYPE-backed first. |
| 35 | /// |
| 36 | /// Rewards (docs §12). accRewardPerHash += reward(segment) × 1e36 / onlineHashrate, per era segment. |
| 37 | /// Blocks with zero online hashrate add nothing and mint nothing. |
| 38 | /// |
| 39 | /// Expiry buckets (docs §12). A wallet with r rigs on and U units has an empty block E = t + U / (r × 1e18). |
| 40 | /// r is registered in bucket E. When accounting advances, buckets are processed in increasing E: rewards are |
| 41 | /// accrued up to E, accRewardPerHash is snapshotted for E, then r leaves the online total. Non-empty buckets |
| 42 | /// are indexed by a 4-level bitmap (ExpiryBitmap) so empty block ranges are skipped in O(1). |
| 43 | /// Cost: O(number of distinct non-empty buckets crossed), about 30k gas each. If many buckets accumulated |
| 44 | /// without any interaction, `checkpointPartial(maxBuckets)` advances in bounded steps. |
| 45 | /// |
| 46 | /// Burns are deferred: consumed HYPE / KIBBLE accrue in `pendingBurnHypeUnits` / `pendingBurnKibble` and |
| 47 | /// `flushBurn()` (public) sends them to the `Burner`. |
| 48 | contract Miner is ReentrancyGuard { |
| 49 | using SafeERC20 for IERC20; |
| 50 | using ExpiryBitmap for ExpiryBitmap.Bitmap; |
| 51 | |
| 52 | // ------------------------------------------------------------------ errors |
| 53 | error ZeroAmount(); |
| 54 | error WrongPayment(); |
| 55 | error TooManyRigs(); |
| 56 | error EmptyTank(); |
| 57 | error InsufficientPower(); |
| 58 | error MiningNotStarted(); |
| 59 | error NoTwap(); |
| 60 | error TransferFailed(); |
| 61 | |
| 62 | // ------------------------------------------------------------------ events (docs §11) |
| 63 | event RigsBought(address user, uint256 amount, uint256 hypePaid); |
| 64 | event PowerDeposited(address user, uint256 hypeEquivalent, bool inKibble); |
| 65 | event PowerWithdrawn(address user, uint256 hypeEquivalent); |
| 66 | event RigsSwitched(address user, uint256 rigsOn); |
| 67 | event TankEmpty(address user, uint256 blockNumber); |
| 68 | event Claimed(address user, uint256 amount); |
| 69 | |
| 70 | uint256 public constant ACC_PRECISION = 1e36; |
| 71 | uint256 internal constant UNITS_PER_WEI = K.DRAW_DIVISOR; |
| 72 | uint256 internal constant UNITS_PER_RIG_BLOCK = K.UNITS_PER_RIG_BLOCK; |
| 73 | |
| 74 | /// @dev Packed in 4 slots. Bounds: rigs < 2^64 (HYPE supply), power units < 2^128 (> 5e9 HYPE), |
| 75 | /// KIBBLE < 2^128 (> max supply), mining time < 2^64. Writes go through SafeCast. |
| 76 | struct Account { |
| 77 | uint64 rigs; |
| 78 | uint64 rigsOn; // configured on-count; online while expiry > now |
| 79 | uint64 expiry; // mining-time empty block, valid while rigsOn > 0 |
| 80 | uint64 lastT; |
| 81 | uint128 hypeUnits; |
| 82 | uint128 kibbleUnits; |
| 83 | uint128 kibbleAmount; |
| 84 | uint128 pendingReward; |
| 85 | uint256 accSnapshot; |
| 86 | } |
| 87 | |
| 88 | KibbleToken public immutable kibble; |
| 89 | Emission public immutable emission; |
| 90 | Genesis public immutable genesis; |
| 91 | Oracle public immutable oracle; |
| 92 | Zapper public immutable zapper; |
| 93 | Burner public immutable burner; |
| 94 | |
| 95 | mapping(address => Account) internal _accounts; |
| 96 | |
| 97 | /// @notice Total rigs ever bought. |
| 98 | uint256 public totalRigs; |
| 99 | /// @notice Online hashrate as of `lastAccountedT` (use `totalOnlineHashrate()` for the live value). |
| 100 | uint256 public onlineHashrateAccounted; |
| 101 | /// @notice Reward per unit of hashrate, scaled by ACC_PRECISION, as of `lastAccountedT`. |
| 102 | uint256 public accRewardPerHash; |
| 103 | /// @notice Mining time up to which global accounting is processed. |
| 104 | uint256 public lastAccountedT; |
| 105 | /// @notice Emission distributed to online hashrate so far, scaled by ACC_PRECISION. |
| 106 | uint256 public totalAllocatedScaled; |
| 107 | /// @notice KIBBLE claimed so far. |
| 108 | uint256 public totalClaimed; |
| 109 | /// @notice Hashrate expiring at each mining-time block. |
| 110 | mapping(uint256 => uint256) public expiringHashrate; |
| 111 | /// @notice accRewardPerHash at each processed expiry block. |
| 112 | mapping(uint256 => uint256) public accAtExpiry; |
| 113 | ExpiryBitmap.Bitmap internal _expiries; |
| 114 | |
| 115 | /// @notice Consumed HYPE power waiting to be sent to the Burner, in power units (wei × 60,000). |
| 116 | uint256 public pendingBurnHypeUnits; |
| 117 | /// @notice Consumed KIBBLE power waiting to be burned. |
| 118 | uint256 public pendingBurnKibble; |
| 119 | /// @notice Sum of all HYPE-backed tanks, power units (as of each wallet's last settlement). |
| 120 | uint256 public totalHypeUnits; |
| 121 | /// @notice Sum of all KIBBLE held for KIBBLE-backed tanks (as of each wallet's last settlement). |
| 122 | uint256 public totalKibbleBacking; |
| 123 | |
| 124 | uint256 internal _block0; |
| 125 | uint256 internal _announcedEra; |
| 126 | |
| 127 | constructor( |
| 128 | KibbleToken kibble_, |
| 129 | Emission emission_, |
| 130 | Genesis genesis_, |
| 131 | Oracle oracle_, |
| 132 | Zapper zapper_, |
| 133 | Burner burner_ |
| 134 | ) { |
| 135 | kibble = kibble_; |
| 136 | emission = emission_; |
| 137 | genesis = genesis_; |
| 138 | oracle = oracle_; |
| 139 | zapper = zapper_; |
| 140 | burner = burner_; |
| 141 | } |
| 142 | |
| 143 | // ================================================================== rigs (docs §3) |
| 144 | |
| 145 | /// @notice Buys `amount` rigs for `amount` × 1 HYPE (docs §3, §11). Before block 0 the HYPE goes to `Genesis` |
| 146 | /// (seeds the pool at block 0); after block 0 it is zapped into locked LP by `Zapper`. |
| 147 | /// Rigs are non-transferable and non-refundable. |
| 148 | function buyRigs(uint256 amount) external payable nonReentrant { |
| 149 | if (amount == 0) revert ZeroAmount(); |
| 150 | if (msg.value != amount * K.RIG_PRICE) revert WrongPayment(); |
| 151 | _sync(); |
| 152 | Account storage acct = _accounts[msg.sender]; |
| 153 | acct.rigs = SafeCast.toUint64(acct.rigs + amount); |
| 154 | totalRigs += amount; |
| 155 | emit RigsBought(msg.sender, amount, msg.value); |
| 156 | if (genesis.miningStarted()) { |
| 157 | zapper.zap{value: msg.value}(); |
| 158 | } else { |
| 159 | genesis.depositPreorder{value: msg.value}(); |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // ================================================================== power (docs §4) |
| 164 | |
| 165 | /// @notice Loads the caller's tank with `msg.value` HYPE (docs §4, §11). |
| 166 | function depositPower() external payable nonReentrant { |
| 167 | if (msg.value == 0) revert ZeroAmount(); |
| 168 | uint256 nowT = _sync(); |
| 169 | Account storage a = _accounts[msg.sender]; |
| 170 | _settle(msg.sender, a, nowT); |
| 171 | uint256 r = _unregister(a); |
| 172 | uint256 units = msg.value * UNITS_PER_WEI; |
| 173 | a.hypeUnits = SafeCast.toUint128(a.hypeUnits + units); |
| 174 | totalHypeUnits += units; |
| 175 | _register(a, r, nowT); |
| 176 | emit PowerDeposited(msg.sender, msg.value, false); |
| 177 | } |
| 178 | |
| 179 | /// @notice Loads the caller's tank with KIBBLE, credited at KIBBLE × TWAP / 0.9 (docs §4, §11). Reverts before |
| 180 | /// block 0 (no TWAP). Needs a KIBBLE approval. |
| 181 | function depositPowerKibble(uint256 kibbleAmount) external nonReentrant { |
| 182 | if (kibbleAmount == 0) revert ZeroAmount(); |
| 183 | if (!genesis.miningStarted()) revert MiningNotStarted(); |
| 184 | uint256 nowT = _sync(); |
| 185 | uint256 price = oracle.twap(); |
| 186 | if (price == 0) revert NoTwap(); |
| 187 | uint256 units = |
| 188 | FullMath.mulDiv(kibbleAmount, price * K.KIBBLE_CREDIT_NUM * UNITS_PER_WEI, K.KIBBLE_CREDIT_DEN * 1e18); |
| 189 | if (units == 0) revert ZeroAmount(); |
| 190 | IERC20(address(kibble)).safeTransferFrom(msg.sender, address(this), kibbleAmount); |
| 191 | |
| 192 | Account storage a = _accounts[msg.sender]; |
| 193 | _settle(msg.sender, a, nowT); |
| 194 | uint256 r = _unregister(a); |
| 195 | a.kibbleUnits = SafeCast.toUint128(a.kibbleUnits + units); |
| 196 | a.kibbleAmount = SafeCast.toUint128(a.kibbleAmount + kibbleAmount); |
| 197 | totalKibbleBacking += kibbleAmount; |
| 198 | _register(a, r, nowT); |
| 199 | emit PowerDeposited(msg.sender, units / UNITS_PER_WEI, true); |
| 200 | } |
| 201 | |
| 202 | /// @notice Withdraws unused power worth `hypeEquivalent` wei, each part in the asset it was deposited in |
| 203 | /// (docs §4, §11, §13). HYPE-backed power is withdrawn first, then KIBBLE-backed power at its deposit |
| 204 | /// rate. Pass type(uint256).max to withdraw everything. If what is left cannot power the rigs that are |
| 205 | /// on for one more block, they switch off (docs §13). |
| 206 | function withdrawPower(uint256 hypeEquivalent) external nonReentrant { |
| 207 | if (hypeEquivalent == 0) revert ZeroAmount(); |
| 208 | uint256 nowT = _sync(); |
| 209 | Account storage a = _accounts[msg.sender]; |
| 210 | _settle(msg.sender, a, nowT); |
| 211 | uint256 r = _unregister(a); |
| 212 | |
| 213 | uint256 hypeOut; |
| 214 | uint256 kibbleOut; |
| 215 | uint256 eqOut; |
| 216 | if (hypeEquivalent == type(uint256).max) { |
| 217 | uint256 hu = a.hypeUnits; |
| 218 | hypeOut = hu / UNITS_PER_WEI; |
| 219 | pendingBurnHypeUnits += hu % UNITS_PER_WEI; // sub-wei dust cannot be paid out: it is burned |
| 220 | totalHypeUnits -= hu; |
| 221 | eqOut = hypeOut + a.kibbleUnits / UNITS_PER_WEI; |
| 222 | kibbleOut = a.kibbleAmount; |
| 223 | a.hypeUnits = 0; |
| 224 | a.kibbleUnits = 0; |
| 225 | a.kibbleAmount = 0; |
| 226 | totalKibbleBacking -= kibbleOut; |
| 227 | } else { |
| 228 | uint256 fromHype = a.hypeUnits / UNITS_PER_WEI; |
| 229 | if (fromHype > hypeEquivalent) fromHype = hypeEquivalent; |
| 230 | a.hypeUnits = uint128(a.hypeUnits - fromHype * UNITS_PER_WEI); |
| 231 | totalHypeUnits -= fromHype * UNITS_PER_WEI; |
| 232 | hypeOut = fromHype; |
| 233 | uint256 restUnits = (hypeEquivalent - fromHype) * UNITS_PER_WEI; |
| 234 | if (restUnits > 0) { |
| 235 | uint256 ku = a.kibbleUnits; |
| 236 | if (restUnits > ku) revert InsufficientPower(); |
| 237 | if (ku - restUnits < UNITS_PER_WEI) restUnits = ku; // sub-wei remainder: withdraw the whole sub-tank |
| 238 | kibbleOut = restUnits == ku ? a.kibbleAmount : FullMath.mulDiv(a.kibbleAmount, restUnits, ku); |
| 239 | a.kibbleUnits = uint128(ku - restUnits); |
| 240 | a.kibbleAmount = uint128(a.kibbleAmount - kibbleOut); |
| 241 | totalKibbleBacking -= kibbleOut; |
| 242 | } |
| 243 | eqOut = hypeEquivalent; |
| 244 | } |
| 245 | |
| 246 | if (r > 0 && !_register(a, r, nowT)) emit RigsSwitched(msg.sender, 0); |
| 247 | emit PowerWithdrawn(msg.sender, eqOut); |
| 248 | |
| 249 | if (kibbleOut > 0) IERC20(address(kibble)).safeTransfer(msg.sender, kibbleOut); |
| 250 | if (hypeOut > 0) { |
| 251 | (bool ok,) = msg.sender.call{value: hypeOut}(""); |
| 252 | if (!ok) revert TransferFailed(); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // ================================================================== mining (docs §4, §11) |
| 257 | |
| 258 | /// @notice Sets how many of the caller's rigs are on (docs §4, §11). Reverts if `count` exceeds owned rigs, |
| 259 | /// or if `count` > 0 and the tank cannot power `count` rigs for one block (docs §13 "switch on with an |
| 260 | /// empty tank reverts"). |
| 261 | function setRigsOn(uint256 count) external nonReentrant { |
| 262 | Account storage a = _accounts[msg.sender]; |
| 263 | if (count > a.rigs) revert TooManyRigs(); |
| 264 | uint256 nowT = _sync(); |
| 265 | _settle(msg.sender, a, nowT); |
| 266 | _unregister(a); |
| 267 | if (count > 0 && !_register(a, count, nowT)) revert EmptyTank(); |
| 268 | emit RigsSwitched(msg.sender, count); |
| 269 | } |
| 270 | |
| 271 | /// @notice Mints the caller's pending KIBBLE to the caller (docs §5 "claimable at any time, no fee, no lock"). |
| 272 | function claim() external nonReentrant returns (uint256 amount) { |
| 273 | uint256 nowT = _sync(); |
| 274 | Account storage a = _accounts[msg.sender]; |
| 275 | _settle(msg.sender, a, nowT); |
| 276 | amount = a.pendingReward; |
| 277 | if (amount == 0) return 0; |
| 278 | a.pendingReward = 0; |
| 279 | totalClaimed += amount; |
| 280 | emission.mint(msg.sender, amount); |
| 281 | emit Claimed(msg.sender, amount); |
| 282 | } |
| 283 | |
| 284 | /// @notice Advances global accounting to the current block, processing every expiry bucket (docs §12). |
| 285 | /// Anyone can call. |
| 286 | function checkpoint() external nonReentrant { |
| 287 | _sync(); |
| 288 | } |
| 289 | |
| 290 | /// @notice Advances global accounting processing at most `maxBuckets` expiry buckets. Gas-bounded escape hatch |
| 291 | /// if very many buckets accumulated without interaction. Returns true when fully caught up. |
| 292 | function checkpointPartial(uint256 maxBuckets) external nonReentrant returns (bool done) { |
| 293 | oracle.update(); |
| 294 | done = _advance(_nowT(), maxBuckets); |
| 295 | _syncEra(); |
| 296 | } |
| 297 | |
| 298 | /// @notice Settles `user` (rewards, power drawn, tank-empty detection) so its consumed power can be burned. |
| 299 | /// Anyone can call; it changes nothing the user could not observe through the views. |
| 300 | function settle(address user) external nonReentrant { |
| 301 | uint256 nowT = _sync(); |
| 302 | _settle(user, _accounts[user], nowT); |
| 303 | } |
| 304 | |
| 305 | /// @notice Sends consumed power to the `Burner` and triggers the burn (docs §4, §9). Anyone can call. |
| 306 | function flushBurn() external nonReentrant { |
| 307 | _sync(); |
| 308 | uint256 hypeWei = pendingBurnHypeUnits / UNITS_PER_WEI; |
| 309 | pendingBurnHypeUnits -= hypeWei * UNITS_PER_WEI; |
| 310 | uint256 kib = pendingBurnKibble; |
| 311 | pendingBurnKibble = 0; |
| 312 | if (kib > 0) IERC20(address(kibble)).safeTransfer(address(burner), kib); |
| 313 | if (hypeWei > 0) { |
| 314 | (bool ok,) = address(burner).call{value: hypeWei}(""); |
| 315 | if (!ok) revert TransferFailed(); |
| 316 | } |
| 317 | burner.burn(); |
| 318 | } |
| 319 | |
| 320 | // ================================================================== internal accounting |
| 321 | |
| 322 | function _currentBlock0() internal returns (uint256 b0) { |
| 323 | b0 = _block0; |
| 324 | if (b0 == 0) { |
| 325 | b0 = genesis.block0(); |
| 326 | if (b0 != 0) _block0 = b0; |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | function _nowT() internal returns (uint256) { |
| 331 | uint256 b0 = _currentBlock0(); |
| 332 | return b0 == 0 ? 0 : ChainBlock.number() - b0; |
| 333 | } |
| 334 | |
| 335 | function _sync() internal returns (uint256 nowT) { |
| 336 | oracle.update(); |
| 337 | nowT = _nowT(); |
| 338 | _advance(nowT, type(uint256).max); |
| 339 | _syncEra(); |
| 340 | } |
| 341 | |
| 342 | function _syncEra() internal { |
| 343 | if (_block0 == 0) return; |
| 344 | uint256 e = EmissionMath.eraAt(lastAccountedT); |
| 345 | if (e > _announcedEra) { |
| 346 | _announcedEra = e; |
| 347 | emission.sync(); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// @dev Processes expiry buckets in (lastAccountedT, toT] in order, then accrues up to toT. |
| 352 | function _advance(uint256 toT, uint256 maxBuckets) internal returns (bool done) { |
| 353 | uint256 t = lastAccountedT; |
| 354 | if (toT <= t) return true; |
| 355 | uint256 h = onlineHashrateAccounted; |
| 356 | uint256 acc = accRewardPerHash; |
| 357 | uint256 allocated; |
| 358 | uint256 processed; |
| 359 | while (true) { |
| 360 | (uint256 k, bool found) = _expiries.nextSet(t + 1, toT); |
| 361 | if (!found) { |
| 362 | (uint256 dAcc, uint256 dAlloc) = EmissionMath.accrue(t, toT, h, ACC_PRECISION); |
| 363 | acc += dAcc; |
| 364 | allocated += dAlloc; |
| 365 | t = toT; |
| 366 | done = true; |
| 367 | break; |
| 368 | } |
| 369 | if (processed == maxBuckets) break; |
| 370 | (uint256 dAcc2, uint256 dAlloc2) = EmissionMath.accrue(t, k, h, ACC_PRECISION); |
| 371 | acc += dAcc2; |
| 372 | allocated += dAlloc2; |
| 373 | accAtExpiry[k] = acc; |
| 374 | h -= expiringHashrate[k]; |
| 375 | delete expiringHashrate[k]; |
| 376 | _expiries.clear(k); |
| 377 | t = k; |
| 378 | ++processed; |
| 379 | } |
| 380 | lastAccountedT = t; |
| 381 | onlineHashrateAccounted = h; |
| 382 | accRewardPerHash = acc; |
| 383 | totalAllocatedScaled += allocated; |
| 384 | } |
| 385 | |
| 386 | /// @dev Brings `a` to mining time nowT (global accounting must already be at nowT). |
| 387 | function _settle(address user, Account storage a, uint256 nowT) internal { |
| 388 | uint256 r = a.rigsOn; |
| 389 | if (r > 0) { |
| 390 | uint256 e = a.expiry; |
| 391 | bool expired = e <= nowT; |
| 392 | uint256 end = expired ? e : nowT; |
| 393 | uint256 accEnd = expired ? accAtExpiry[e] : accRewardPerHash; |
| 394 | a.pendingReward = SafeCast.toUint128(a.pendingReward + r * (accEnd - a.accSnapshot) / ACC_PRECISION); |
| 395 | _consume(a, r * (end - a.lastT) * UNITS_PER_RIG_BLOCK); |
| 396 | if (expired) { |
| 397 | a.rigsOn = 0; |
| 398 | emit TankEmpty(user, _block0 + e); |
| 399 | } |
| 400 | } |
| 401 | a.lastT = SafeCast.toUint64(nowT); |
| 402 | a.accSnapshot = accRewardPerHash; |
| 403 | } |
| 404 | |
| 405 | /// @dev Draws `units` from the tank, KIBBLE-backed power first. |
| 406 | function _consume(Account storage a, uint256 units) internal { |
| 407 | if (units == 0) return; |
| 408 | uint256 ku = a.kibbleUnits; |
| 409 | uint256 fromK = units < ku ? units : ku; |
| 410 | if (fromK > 0) { |
| 411 | uint256 kb = fromK == ku ? a.kibbleAmount : FullMath.mulDiv(a.kibbleAmount, fromK, ku); |
| 412 | a.kibbleUnits = uint128(ku - fromK); |
| 413 | a.kibbleAmount = uint128(a.kibbleAmount - kb); |
| 414 | totalKibbleBacking -= kb; |
| 415 | pendingBurnKibble += kb; |
| 416 | } |
| 417 | uint256 rest = units - fromK; |
| 418 | if (rest > 0) { |
| 419 | a.hypeUnits = uint128(a.hypeUnits - rest); |
| 420 | totalHypeUnits -= rest; |
| 421 | pendingBurnHypeUnits += rest; |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | /// @dev Removes a settled, online account from the online total and its bucket. Returns its previous rigsOn. |
| 426 | function _unregister(Account storage a) internal returns (uint256 r) { |
| 427 | r = a.rigsOn; |
| 428 | if (r == 0) return 0; |
| 429 | uint256 e = a.expiry; |
| 430 | uint256 left = expiringHashrate[e] - r; |
| 431 | expiringHashrate[e] = left; |
| 432 | if (left == 0) _expiries.clear(e); |
| 433 | onlineHashrateAccounted -= r; |
| 434 | a.rigsOn = 0; |
| 435 | } |
| 436 | |
| 437 | /// @dev Puts `r` rigs online if the tank can power them for at least one block. Returns false (rigs off) if not. |
| 438 | function _register(Account storage a, uint256 r, uint256 nowT) internal returns (bool) { |
| 439 | if (r == 0) return true; |
| 440 | uint256 n = (a.hypeUnits + a.kibbleUnits) / (r * UNITS_PER_RIG_BLOCK); |
| 441 | if (n == 0) { |
| 442 | a.rigsOn = 0; |
| 443 | return false; |
| 444 | } |
| 445 | uint256 e = nowT + n; |
| 446 | uint256 prev = expiringHashrate[e]; |
| 447 | expiringHashrate[e] = prev + r; |
| 448 | if (prev == 0) _expiries.set(e); |
| 449 | onlineHashrateAccounted += r; |
| 450 | a.rigsOn = uint64(r); // r <= rigs < 2^64 |
| 451 | a.expiry = SafeCast.toUint64(e); |
| 452 | return true; |
| 453 | } |
| 454 | |
| 455 | // ================================================================== views (docs §14) |
| 456 | |
| 457 | /// @notice Current block number used by the protocol (Elysium L2 block, see ChainBlock). |
| 458 | function currentBlock() external view returns (uint256) { |
| 459 | return ChainBlock.number(); |
| 460 | } |
| 461 | |
| 462 | /// @notice Block 0 (0 during preorder). |
| 463 | function block0() public view returns (uint256) { |
| 464 | uint256 b0 = _block0; |
| 465 | return b0 != 0 ? b0 : genesis.block0(); |
| 466 | } |
| 467 | |
| 468 | /// @notice Current mining time (blocks since block 0). |
| 469 | function miningTime() public view returns (uint256) { |
| 470 | uint256 b0 = block0(); |
| 471 | return b0 == 0 ? 0 : ChainBlock.number() - b0; |
| 472 | } |
| 473 | |
| 474 | /// @dev Simulates global accounting up to `target` (>= lastAccountedT) without writing. |
| 475 | function _simulate(uint256 target) internal view returns (uint256 acc, uint256 h, uint256 allocated) { |
| 476 | uint256 t = lastAccountedT; |
| 477 | acc = accRewardPerHash; |
| 478 | h = onlineHashrateAccounted; |
| 479 | allocated = totalAllocatedScaled; |
| 480 | if (target <= t) return (acc, h, allocated / ACC_PRECISION); |
| 481 | while (true) { |
| 482 | (uint256 k, bool found) = _expiries.nextSet(t + 1, target); |
| 483 | uint256 stop = found ? k : target; |
| 484 | (uint256 dAcc, uint256 dAlloc) = EmissionMath.accrue(t, stop, h, ACC_PRECISION); |
| 485 | acc += dAcc; |
| 486 | allocated += dAlloc; |
| 487 | t = stop; |
| 488 | if (!found) break; |
| 489 | h -= expiringHashrate[k]; |
| 490 | } |
| 491 | allocated /= ACC_PRECISION; |
| 492 | } |
| 493 | |
| 494 | /// @notice Live total online hashrate (docs §14), expired tanks removed. |
| 495 | function totalOnlineHashrate() external view returns (uint256 h) { |
| 496 | (, h,) = _simulate(miningTime()); |
| 497 | } |
| 498 | |
| 499 | /// @notice Emission distributed to online hashrate as of `lastAccountedT` (upper bound of claimed + pending). |
| 500 | function totalAllocated() external view returns (uint256) { |
| 501 | return totalAllocatedScaled / ACC_PRECISION; |
| 502 | } |
| 503 | |
| 504 | /// @notice Emission distributed to online hashrate up to now. |
| 505 | function totalAllocatedNow() external view returns (uint256 allocated) { |
| 506 | (,, allocated) = _simulate(miningTime()); |
| 507 | } |
| 508 | |
| 509 | /// @notice Rigs owned by `user`. |
| 510 | function rigsOf(address user) external view returns (uint256) { |
| 511 | return _accounts[user].rigs; |
| 512 | } |
| 513 | |
| 514 | /// @notice Rigs of `user` currently on (0 once the tank ran dry). |
| 515 | function rigsOnOf(address user) public view returns (uint256) { |
| 516 | Account storage a = _accounts[user]; |
| 517 | if (a.rigsOn == 0 || a.expiry <= miningTime()) return 0; |
| 518 | return a.rigsOn; |
| 519 | } |
| 520 | |
| 521 | /// @notice Pending KIBBLE of `user` (docs §12), live. |
| 522 | function pending(address user) external view returns (uint256) { |
| 523 | Account storage a = _accounts[user]; |
| 524 | uint256 p = a.pendingReward; |
| 525 | uint256 r = a.rigsOn; |
| 526 | if (r == 0) return p; |
| 527 | uint256 nowT = miningTime(); |
| 528 | uint256 e = a.expiry; |
| 529 | uint256 accEnd; |
| 530 | if (e <= lastAccountedT) accEnd = accAtExpiry[e]; |
| 531 | else (accEnd,,) = _simulate(e < nowT ? e : nowT); |
| 532 | return p + r * (accEnd - a.accSnapshot) / ACC_PRECISION; |
| 533 | } |
| 534 | |
| 535 | /// @notice Live tank of `user`, all in wei (docs §14 "Tank level"). `kibbleBackedHype` is the HYPE-equivalent of |
| 536 | /// the KIBBLE-backed sub-tank, `kibbleAmount` the KIBBLE it returns on withdrawal. |
| 537 | function tankOf(address user) |
| 538 | public |
| 539 | view |
| 540 | returns (uint256 hypeBacked, uint256 kibbleBackedHype, uint256 kibbleAmount, uint256 total) |
| 541 | { |
| 542 | Account storage a = _accounts[user]; |
| 543 | uint256 hu = a.hypeUnits; |
| 544 | uint256 ku = a.kibbleUnits; |
| 545 | kibbleAmount = a.kibbleAmount; |
| 546 | uint256 r = a.rigsOn; |
| 547 | if (r > 0) { |
| 548 | uint256 nowT = miningTime(); |
| 549 | uint256 end = a.expiry < nowT ? a.expiry : nowT; |
| 550 | uint256 drain = r * (end - a.lastT) * UNITS_PER_RIG_BLOCK; |
| 551 | uint256 fromK = drain < ku ? drain : ku; |
| 552 | if (fromK > 0) { |
| 553 | kibbleAmount -= fromK == ku ? kibbleAmount : FullMath.mulDiv(kibbleAmount, fromK, ku); |
| 554 | ku -= fromK; |
| 555 | } |
| 556 | hu -= drain - fromK; |
| 557 | } |
| 558 | hypeBacked = hu / UNITS_PER_WEI; |
| 559 | kibbleBackedHype = ku / UNITS_PER_WEI; |
| 560 | total = (hu + ku) / UNITS_PER_WEI; |
| 561 | } |
| 562 | |
| 563 | /// @notice Block at which the tank of `user` runs dry (docs §12), 0 if no rig is on or mining has not started |
| 564 | /// (see `blocksLeftOf` during preorder). |
| 565 | function emptyBlockOf(address user) external view returns (uint256) { |
| 566 | if (rigsOnOf(user) == 0) return 0; |
| 567 | uint256 b0 = block0(); |
| 568 | if (b0 == 0) return 0; |
| 569 | return b0 + _accounts[user].expiry; |
| 570 | } |
| 571 | |
| 572 | /// @notice Blocks of mining left before the tank of `user` runs dry at the current rigs on (0 if off). |
| 573 | function blocksLeftOf(address user) external view returns (uint256) { |
| 574 | if (rigsOnOf(user) == 0) return 0; |
| 575 | return _accounts[user].expiry - miningTime(); |
| 576 | } |
| 577 | |
| 578 | /// @notice Full account of `user` in one call. |
| 579 | function accountOf(address user) |
| 580 | external |
| 581 | view |
| 582 | returns ( |
| 583 | uint256 rigs, |
| 584 | uint256 rigsOn, |
| 585 | uint256 hypeBacked, |
| 586 | uint256 kibbleBackedHype, |
| 587 | uint256 kibbleAmount, |
| 588 | uint256 expiry, |
| 589 | uint256 lastT, |
| 590 | uint256 storedPending |
| 591 | ) |
| 592 | { |
| 593 | Account storage a = _accounts[user]; |
| 594 | (hypeBacked, kibbleBackedHype, kibbleAmount,) = tankOf(user); |
| 595 | return (a.rigs, rigsOnOf(user), hypeBacked, kibbleBackedHype, kibbleAmount, a.expiry, a.lastT, a.pendingReward); |
| 596 | } |
| 597 | |
| 598 | /// @notice Power drawn per rig per block, as the exact ratio numerator / denominator in wei (1e18 / 60,000). |
| 599 | function powerDrawPerRigPerBlock() external pure returns (uint256 numerator, uint256 denominator) { |
| 600 | return (1e18, K.DRAW_DIVISOR); |
| 601 | } |
| 602 | |
| 603 | /// @notice Production cost in HYPE per KIBBLE (1e18 scaled), docs §7: |
| 604 | /// power per rig per block × online hashrate / block reward, with exact ratios. |
| 605 | /// During preorder it uses era 1 and the rigs currently switched on (the block 0 calibration). |
| 606 | function productionCost() external view returns (uint256) { |
| 607 | uint256 nowT = miningTime(); |
| 608 | (, uint256 h,) = _simulate(nowT); |
| 609 | uint256 em = EmissionMath.eraEmission(EmissionMath.eraAt(nowT)); |
| 610 | if (em == 0) return 0; |
| 611 | // (h × 1e18 / 60,000) / (em / ERA_LENGTH) × 1e18 |
| 612 | return FullMath.mulDiv(h * 1e18, 1e18 * K.ERA_LENGTH, K.DRAW_DIVISOR * em); |
| 613 | } |
| 614 | } |
| 615 |