Verified contractExactMIT
RewardsDistributor
Address0x0c35b5bfd31eb2fb4922577e18aa87a35d89098a
- Balance
0.114517 ETH
- Transactions
893
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,325,592
- Creation transaction
- 0xcd76050059…3c692d1d1e
7 files
- src/RewardsDistributor.solmain14.47 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.09 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.08 KB
- src/interfaces/IBountyEngine.sol5.91 KB
- src/interfaces/IRewardsDistributor.sol4.42 KB
- src/interfaces/IWordBank.sol3.65 KB
- src/interfaces/Types.sol1.79 KB
src/RewardsDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IBountyEngine} from "./interfaces/IBountyEngine.sol";
import {IRewardsDistributor} from "./interfaces/IRewardsDistributor.sol";
import {IWordBank} from "./interfaces/IWordBank.sol";
/// @title RewardsDistributor — equal ETH fee-share across alive word NFTs
/// @notice Splits every ETH deposit (the rewards slice of the 1% swap fee: 50% at launch
/// while buy-and-burn is active, default 70% after burn completion — this contract
/// is agnostic to the slice size) equally across all alive word NFTs using the
/// 1e18-scaled rewards-per-share accumulator: O(1) per deposit, O(1) per claim,
/// no loops over holders, no snapshots.
/// @dev All accounting is keyed by tokenId, never by owner — rewards travel with the
/// NFT (transfers never touch reward state; the claim-time owner collects).
///
/// Zero-alive deposits (documented choice, charter micro-decision): a deposit that
/// arrives while `wordBank.totalAlive() == 0` is HELD AND DEFERRED, never reverted.
/// `deposit()` is on the permissionless fee-routing path (FeeHook.flush, BurnEngine
/// residual sweep) and must be unbrickable; zero-alive is reachable before the first
/// mint registers and, in the terminal case, if every word is ever unbound. Deferred
/// ETH accumulates in `pendingUndistributed` and folds into the next deposit made
/// while at least one token is alive (a zero-value `deposit()` call acts as a
/// permissionless kick). Deferred funds are reserved — the dust sweep cannot touch
/// them. If the collection terminally empties, the buffer simply sits: with zero
/// alive words there are no holders to favor, and no admin path exists by design.
///
/// Entitlement safety: `owedScaled` tracks the aggregate outstanding entitlement in
/// 1e18-scaled units. Deposits add exactly what they accrue; claims and settlements
/// subtract the full scaled delta they release (including the sub-wei fraction the
/// floored payout forfeits, which thereby becomes provable dust). The sweep sends
/// only `balance - pendingUndistributed - ceil(owedScaled / 1e18)`, so it can never
/// touch owed funds — system invariant: contract balance always covers the sum of
/// pending entitlements plus the deferred buffer.
contract RewardsDistributor is IRewardsDistributor, ReentrancyGuardTransient {
// ─────────────────────────────────── types ─────────────────────────────────────────
/// @notice Lifecycle of a tokenId in this contract. None → Active (register, at mint)
/// → Closed (settleAndClose, at unbind). Closed is terminal: no re-registration,
/// no accrual, no claim.
enum TokenStatus {
None,
Active,
Closed
}
// ─────────────────────────────────── errors ────────────────────────────────────────
/// @notice Caller is not the WordBank.
error NotWordBank();
/// @notice Zero address given where a real one is required.
error ZeroAddress();
/// @notice deposit() called with no value and no deferred buffer to fold.
error ZeroDeposit();
/// @notice register() for an id that is already Active or Closed.
error AlreadyRegistered(uint256 tokenId);
/// @notice Operation on an id that was never registered.
error NotRegistered(uint256 tokenId);
/// @notice Operation on a permanently closed id.
error TokenClosed(uint256 tokenId);
/// @notice claimRewards() caller does not own the token.
error NotTokenOwner(uint256 tokenId);
/// @notice claimRewards() called with an empty id array.
error EmptyClaim();
/// @notice ETH payout failed (recipient reverted or has no payable path).
error EthTransferFailed(address to, uint256 amount);
/// @notice sweepDust() found nothing provably sweepable.
error NoDust();
// ─────────────────────────────────── events ────────────────────────────────────────
/// @notice A deposit arrived while totalAlive == 0 and was deferred, not distributed.
/// @param from The depositor.
/// @param amount The value of this call.
/// @param buffered Total now held in the deferred buffer (includes prior deferrals).
event DepositDeferred(address indexed from, uint256 amount, uint256 buffered);
// ─────────────────────────────────── storage ───────────────────────────────────────
/// @dev Accumulator scale. 1e18 keeps rounding dust sub-wei per token per deposit even
/// at the full 10,000 shares.
uint256 private constant ACC_PRECISION = 1e18;
/// @notice The ERC-721 + binding vault. Sole authority for register/settleAndClose and
/// the claim-auth + totalAlive oracle.
IWordBank public immutable wordBank;
/// @notice BountyEngine treasury — the only place dust can ever be swept to.
address public immutable bountyTreasury;
/// @inheritdoc IRewardsDistributor
uint256 public override accRewardPerNFT;
/// @notice Per-token accumulator checkpoint: the value of accRewardPerNFT already
/// accounted for (paid or never owed). Pending = (acc - debt) / 1e18.
mapping(uint256 => uint256) public rewardDebt;
/// @notice Lifecycle status per tokenId.
mapping(uint256 => TokenStatus) public statusOf;
/// @notice Aggregate outstanding entitlement, 1e18-scaled. Increases by exactly what
/// each deposit accrues; decreases by the full scaled delta each claim/settle
/// releases. ceil(owedScaled / 1e18) is the wei reserve the dust sweep honors.
uint256 public owedScaled;
/// @notice ETH from deposits that arrived while totalAlive == 0, held for the next
/// distribution. Reserved — never sweepable as dust.
uint256 public pendingUndistributed;
// ────────────────────────────────── modifiers ──────────────────────────────────────
modifier onlyWordBank() {
if (msg.sender != address(wordBank)) revert NotWordBank();
_;
}
// ────────────────────────────────── constructor ────────────────────────────────────
/// @param wordBank_ The WordBank (immutable; no upgradeability anywhere).
/// @param bountyTreasury_ The BountyEngine, sink for swept dust (immutable).
constructor(address wordBank_, address bountyTreasury_) {
if (wordBank_ == address(0) || bountyTreasury_ == address(0)) revert ZeroAddress();
wordBank = IWordBank(wordBank_);
bountyTreasury = bountyTreasury_;
}
// ─────────────────────────────────── mutating ──────────────────────────────────────
/// @inheritdoc IRewardsDistributor
/// @dev Permissionless; donations are fine. Folds any deferred buffer into this
/// distribution. With zero alive tokens the full amount is deferred instead (see
/// contract NatSpec). A zero-value call with a non-empty buffer is the
/// permissionless kick that distributes a previously deferred buffer.
function deposit() external payable nonReentrant {
uint256 amount = msg.value + pendingUndistributed;
if (amount == 0) revert ZeroDeposit();
uint256 alive = wordBank.totalAlive();
if (alive == 0) {
pendingUndistributed = amount;
emit DepositDeferred(msg.sender, msg.value, amount);
return;
}
if (pendingUndistributed != 0) pendingUndistributed = 0;
uint256 perShare = (amount * ACC_PRECISION) / alive;
accRewardPerNFT += perShare;
owedScaled += perShare * alive;
emit Deposited(msg.sender, amount, accRewardPerNFT);
}
/// @inheritdoc IRewardsDistributor
/// @dev Checkpoints debt to the current accumulator so a mid-stream mint cannot claim
/// fees that arrived before it existed. Reverts on re-registration and on closed
/// ids (burned ids can never be reminted — WordBank's _nextId only grows).
function register(uint256 tokenId) external onlyWordBank {
TokenStatus status = statusOf[tokenId];
if (status == TokenStatus.Active) revert AlreadyRegistered(tokenId);
if (status == TokenStatus.Closed) revert TokenClosed(tokenId);
statusOf[tokenId] = TokenStatus.Active;
rewardDebt[tokenId] = accRewardPerNFT;
emit Registered(tokenId);
}
/// @inheritdoc IRewardsDistributor
/// @dev WordBank calls this mid-unbind, AFTER burning the NFT but BEFORE the alive
/// registry pop (settle-before-decrement, system invariant 3) — so this function
/// must not and does not consult ownerOf or totalAlive; `to` is the burner, passed
/// explicitly. State is fully settled before the ETH leaves (CEI), and the
/// reentrancy guard shared with claimRewards/deposit/sweepDust blocks any reentry
/// while totalAlive is still pre-decrement.
function settleAndClose(uint256 tokenId, address to) external onlyWordBank nonReentrant {
if (to == address(0)) revert ZeroAddress();
TokenStatus status = statusOf[tokenId];
if (status == TokenStatus.None) revert NotRegistered(tokenId);
if (status == TokenStatus.Closed) revert TokenClosed(tokenId);
uint256 delta = accRewardPerNFT - rewardDebt[tokenId];
uint256 payout = delta / ACC_PRECISION;
statusOf[tokenId] = TokenStatus.Closed;
rewardDebt[tokenId] = accRewardPerNFT;
owedScaled -= delta;
emit SettledAndClosed(tokenId, to, payout);
if (payout != 0) _pay(to, payout);
}
/// @inheritdoc IRewardsDistributor
/// @dev Reverts the whole batch on any non-owned, unregistered, or closed id — nothing
/// is skipped silently. Duplicate ids in one batch pay once (the second occurrence
/// has zero delta). Per-token payouts are floored individually so the total paid
/// always equals the sum of pendingRewards over the batch. Single ETH transfer at
/// the end; all state is final before it (CEI + reentrancy guard).
function claimRewards(uint256[] calldata tokenIds) external nonReentrant {
uint256 len = tokenIds.length;
if (len == 0) revert EmptyClaim();
uint256 acc = accRewardPerNFT;
uint256 totalPayout;
uint256 releasedScaled;
for (uint256 i = 0; i < len; ++i) {
uint256 tokenId = tokenIds[i];
TokenStatus status = statusOf[tokenId];
if (status == TokenStatus.None) revert NotRegistered(tokenId);
if (status == TokenStatus.Closed) revert TokenClosed(tokenId);
if (wordBank.ownerOf(tokenId) != msg.sender) revert NotTokenOwner(tokenId);
uint256 delta = acc - rewardDebt[tokenId];
uint256 payout = delta / ACC_PRECISION;
if (delta != 0) {
rewardDebt[tokenId] = acc;
releasedScaled += delta;
totalPayout += payout;
}
emit Claimed(tokenId, msg.sender, payout);
}
if (releasedScaled != 0) owedScaled -= releasedScaled;
if (totalPayout != 0) _pay(msg.sender, totalPayout);
}
/// @notice Sweeps provable rounding dust to the BountyEngine treasury. Permissionless.
/// @dev Dust = balance − deferred buffer − ceil(owedScaled / 1e18). Because the sum
/// of floored per-token pendings can never exceed floor(owedScaled / 1e18), the
/// ceiling reserve guarantees the sweep never touches owed funds. Forced ETH
/// (selfdestruct sends — there is no receive()) lands here too rather than
/// being stranded.
function sweepDust() external nonReentrant {
uint256 reserved = pendingUndistributed + (owedScaled + ACC_PRECISION - 1) / ACC_PRECISION;
uint256 balance = address(this).balance;
if (balance <= reserved) revert NoDust();
uint256 dust = balance - reserved;
emit DustSwept(bountyTreasury, dust);
IBountyEngine(bountyTreasury).deposit{value: dust}();
}
// ──────────────────────────────────── views ────────────────────────────────────────
/// @inheritdoc IRewardsDistributor
/// @dev Returns 0 for unregistered and closed ids.
function pendingRewards(uint256 tokenId) external view returns (uint256) {
if (statusOf[tokenId] != TokenStatus.Active) return 0;
return (accRewardPerNFT - rewardDebt[tokenId]) / ACC_PRECISION;
}
// ─────────────────────────────────── internal ──────────────────────────────────────
/// @dev ETH out via call (convention: no transfer()); reverts on failure — a recipient
/// that cannot receive ETH fails its own claim/unbind only.
function _pay(address to, uint256 amount) internal {
(bool ok,) = to.call{value: amount}("");
if (!ok) revert EthTransferFailed(to, amount);
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
src/interfaces/IBountyEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @title IBountyEngine — daily commit-reveal sentence bounties
/// @notice FROZEN at interfaces-v1. Do not edit without overseer approval and a tag bump.
/// @dev Implemented by agent 4 (bounty). Consumed by:
/// - FeeHook (agent 5): deposit (the bounty slice: 25% at launch, default 30% post-burn).
/// - RewardsDistributor (agent 3): deposit (dust sweep destination).
/// - Frontend (agent 8): the full game console drives off this surface + events.
/// Template administration and tier-menu administration are BountyEngine-internal
/// admin surface, intentionally absent here (shape is agent 4's discretion within
/// the normative bounds: MAX 7 slots, tiers 0.1–0.5 ETH, admin sets menus never draws).
interface IBountyEngine {
// ──────────────────────────────────── events ───────────────────────────────────────
/// @notice ETH arrived in the treasury (from FeeHook flush, dust sweep, or donation).
event TreasuryDeposit(address indexed from, uint256 amount);
/// @notice A holder committed; the reveal becomes possible after targetBlock.
event Committed(uint256 indexed eventId, address indexed committer, uint256 targetBlock);
/// @notice The sentence was generated and the bounty locked. `words` are the resolved
/// strings at reveal time (frontend renders history from this without re-reading).
event SentenceGenerated(
uint256 indexed eventId,
uint256[] tokenIds,
string[] words,
uint256 templateId,
uint256 amount,
uint256 sharePerWord,
uint256 deadline
);
/// @notice An unrevealed commit lapsed past the blockhash window; bond forfeited to treasury.
event CommitExpired(uint256 indexed eventId, address indexed committer, uint256 bondForfeited);
/// @notice A word's share was claimed.
event BountyClaimed(uint256 indexed eventId, uint256 indexed tokenId, address indexed to, uint256 amount);
/// @notice Post-deadline unclaimed remainder returned to the free treasury.
event EventSwept(uint256 indexed eventId, uint256 amountReturned);
// ─────────────────────────────────── mutating ──────────────────────────────────────
/// @notice Accepts ETH into the treasury. Permissionless (FeeHook is the primary source).
function deposit() external payable;
/// @notice Opens a generation event. Caller must hold ≥1 Word NFT; at most one event per
/// 24h cycle; requires free treasury ≥ the minimum tier and no pending commit.
/// @dev msg.value MUST equal the 0.01 ETH bond exactly. Stores
/// targetBlock = block.number + REVEAL_DELAY (15 blocks).
function commit() external payable;
/// @notice Resolves a pending commit. Callable by ANYONE once block.number > targetBlock,
/// while targetBlock is within the 256-block blockhash window. Atomically: picks a
/// feasible template, fills slots from the alive registry (deduplicated), draws a
/// tier among only affordable tiers, locks the funds, pays the caller the 2%
/// reveal reward, refunds the committer's bond, emits SentenceGenerated.
function reveal() external;
/// @notice Clears a commit whose targetBlock fell out of the blockhash window unrevealed.
/// Callable by anyone; forfeits the bond to the treasury; re-enables commit.
function expireCommit() external;
/// @notice Claims one word's share. Requires: tokenId in the event's word set; before the
/// 7-day deadline; wordBank.ownerOf(tokenId) == msg.sender (claim-time ownership);
/// not already claimed.
function claim(uint256 eventId, uint256 tokenId) external;
/// @notice Batched claim for multi-word winners. Same checks per id; any failure reverts
/// the whole batch.
function claimMany(uint256 eventId, uint256[] calldata tokenIds) external;
/// @notice Returns the post-deadline unclaimed remainder of an event's locked funds to the
/// free treasury. Callable by anyone. Shares of words burned before claiming fall
/// through to this — never redistributed (per-event share math is immutable).
function sweep(uint256 eventId) external;
// ──────────────────────────────────── views ────────────────────────────────────────
/// @notice Single-call buyer/frontend check: true iff tokenId is in the event's set,
/// unclaimed, before the deadline, and the token is still alive.
function isClaimable(uint256 eventId, uint256 tokenId) external view returns (bool);
/// @notice ETH reserved for revealed-but-unswept events. Free treasury =
/// address(this).balance - lockedFunds(). Invariant: lockedFunds() ≤ balance.
function lockedFunds() external view returns (uint256);
/// @notice Full event record for frontends and integration tests.
/// @return tokenIds the words in sentence order (empty if eventId unknown/unrevealed)
/// @return sharePerWord immutable per-word payout for this event
/// @return deadline claim cutoff timestamp
/// @return swept whether the post-deadline sweep has run
function eventInfo(uint256 eventId)
external
view
returns (uint256[] memory tokenIds, uint256 sharePerWord, uint256 deadline, bool swept);
}
src/interfaces/IRewardsDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @title IRewardsDistributor — equal fee-share across alive NFTs (accumulator pattern)
/// @notice FROZEN at interfaces-v1. Do not edit without overseer approval and a tag bump.
/// @dev Implemented by agent 3 (rewards). Consumed by:
/// - WordBank (agent 1): register on mint, settleAndClose on unbind.
/// - FeeHook (agent 5): deposit (the rewards slice: 50% at launch, default 70% post-burn).
/// - BurnEngine (agent 5): deposit (residual-ETH sweep at retirement).
/// - Frontend (agent 8): pendingRewards, claimRewards, events.
/// All accounting is keyed by tokenId, never by owner — rewards travel with the NFT.
interface IRewardsDistributor {
// ──────────────────────────────────── events ───────────────────────────────────────
/// @notice ETH arrived and was spread over `totalAlive` shares.
event Deposited(address indexed from, uint256 amount, uint256 accRewardPerNFT);
/// @notice Token registered at mint with its debt checkpointed to the current accumulator.
event Registered(uint256 indexed tokenId);
/// @notice Pending rewards paid to the token's owner via claimRewards.
event Claimed(uint256 indexed tokenId, address indexed to, uint256 amount);
/// @notice Token force-settled and permanently closed during unbind.
event SettledAndClosed(uint256 indexed tokenId, address indexed to, uint256 amount);
/// @notice Provable rounding dust swept to the BountyEngine treasury.
event DustSwept(address indexed to, uint256 amount);
// ─────────────────────────────────── mutating ──────────────────────────────────────
/// @notice Accepts ETH and accrues it equally to all currently-alive tokens:
/// accRewardPerNFT += amount * 1e18 / wordBank.totalAlive().
/// @dev Called by the FeeHook's flush; MUST be permissionless (donations are fine).
/// Behavior at totalAlive == 0 is the implementer's documented choice (charter).
function deposit() external payable;
/// @notice Registers a freshly minted token. WordBank-only, called inside every mint.
/// @dev MUST set rewardDebt[tokenId] = accRewardPerNFT so mid-stream mints cannot
/// claim fees that arrived before they existed. MUST revert on re-registration
/// and on previously closed ids.
function register(uint256 tokenId) external;
/// @notice Force-settles and permanently closes a token during unbind. WordBank-only.
/// @param to Recipient of the pending payout (the burner — claim-time owner).
/// @dev WordBank calls this BEFORE removing the token from the alive registry, so the
/// token receives its full share of every deposit up to the burn and survivors
/// split everything after (settle-before-decrement, system invariant 3).
/// Closed ids can never accrue, claim, or re-register.
function settleAndClose(uint256 tokenId, address to) external;
/// @notice Batched pull-payment claim. For each id: requires
/// wordBank.ownerOf(tokenId) == msg.sender; pays pending; advances rewardDebt.
/// @dev No deadline — this stream accrues continuously. MUST skip nothing silently:
/// a non-owned or closed id reverts the whole batch.
function claimRewards(uint256[] calldata tokenIds) external;
// ──────────────────────────────────── views ────────────────────────────────────────
/// @notice Exact pending (unclaimed) rewards for a token, in wei. Returns 0 for closed
/// ids. The buyer-due-diligence view: marketplaces price listings off this.
function pendingRewards(uint256 tokenId) external view returns (uint256);
/// @notice Current accumulator value (1e18-scaled rewards per alive NFT), for frontends
/// and invariant tests.
function accRewardPerNFT() external view returns (uint256);
}
src/interfaces/IWordBank.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Category} from "./Types.sol";
/// @title IWordBank — the cross-contract surface of the ERC-721 + binding vault
/// @notice FROZEN at interfaces-v1. Do not edit without overseer approval and a tag bump.
/// @dev Implemented by agent 1 (token-bank). Consumed by:
/// - BountyEngine (agent 4): ownerOf, balanceOf, wordOf, categoryOf, aliveCount,
/// aliveAt, isAlive — sentence generation and claim/commit gating.
/// - RewardsDistributor (agent 3): ownerOf, totalAlive — claim auth and accumulator.
/// This is deliberately NOT the full ERC-721 ABI — only what other protocol contracts
/// need. The implementation is additionally a standard ERC-721 + ERC-2981; minting,
/// unbinding, phase admin, and royalty functions are WordBank-internal surface and are
/// intentionally absent here so their shape stays in agent 1's discretion.
interface IWordBank {
// ─────────────────────────── ownership (ERC-721 subset) ────────────────────────────
/// @notice Owner of a live token. MUST revert for burned/nonexistent ids (ERC-721
/// semantics) — BountyEngine and RewardsDistributor rely on this for claim auth.
function ownerOf(uint256 tokenId) external view returns (address);
/// @notice ERC-721 balance. BountyEngine.commit gates on balanceOf(caller) >= 1.
function balanceOf(address owner) external view returns (uint256);
// ──────────────────────────────── word metadata ────────────────────────────────────
/// @notice The word string of a token. MUST work for any minted id, alive or burned
/// (burned words still appear in historical SentenceGenerated events).
function wordOf(uint256 tokenId) external view returns (string memory);
/// @notice Part-of-speech category of a token's word.
function categoryOf(uint256 tokenId) external view returns (Category);
// ─────────────────────────────── alive registry ────────────────────────────────────
/// @notice Number of alive (minted, not unbound) tokens in a category.
function aliveCount(Category category) external view returns (uint256);
/// @notice TokenId at `index` in the dense alive array for `category`.
/// Valid iff index < aliveCount(category). Ordering is arbitrary and changes on
/// unbind (swap-and-pop) — callers MUST NOT assume stability across transactions.
function aliveAt(Category category, uint256 index) external view returns (uint256 tokenId);
/// @notice Total alive tokens across all categories. Equals the sum of aliveCount over
/// every Category member. RewardsDistributor divides deposits by this.
function totalAlive() external view returns (uint256);
/// @notice True iff the token is minted and not unbound. Cheaper than try/catch on
/// ownerOf; used by BountyEngine.isClaimable.
function isAlive(uint256 tokenId) external view returns (bool);
/// @notice Bound WORD backing of a token (1,000e18 while alive, 0 after unbind).
/// Exposed for frontends and integration invariants.
function bondedBalance(uint256 tokenId) external view returns (uint256);
}
src/interfaces/Types.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @title WORDBANK shared types
/// @notice FROZEN at interfaces-v1. Do not edit without overseer approval and a tag bump
/// (see root AGENTS.md, "Interface protocol"). Multiple agents compile against this file.
/// @notice Part-of-speech category of a word. Drives sentence-slot filling and palette bias.
/// @dev Frozen at four categories for v1. Agent 2 (renderer-art) may propose additions via
/// the overseer; appending new members is ABI-compatible, reordering is NOT — never
/// reorder. The alive registry, templates, and trait palettes are all keyed by this enum.
enum Category {
NOUN,
VERB,
ADJ,
ADV
}
/// @notice Everything the Renderer needs to assemble tokenURI for one word.
/// @dev Produced by WordBank from its per-token storage; consumed by IRenderer.tokenURI.
/// Trait fields are indices into the Renderer's fragment/constraint tables, assigned
/// via the provenance offset. Visual traits MUST never be read by BountyEngine or
/// RewardsDistributor (system invariant 6).
struct WordData {
/// @notice The word itself, stored fully onchain.
string word;
/// @notice Part-of-speech category (also biases background palette — color only, never odds).
Category category;
/// @notice Index into the Renderer's material fragment table (the surface the word is on).
uint8 material;
/// @notice Index into validInks[material] (NOT a global ink id — material-relative).
uint8 ink;
/// @notice Index into validBackgrounds[material] (material-relative; always a solid color).
uint8 background;
/// @notice True for the 25 one-of-one honors words rendered as bespoke SVG path art.
bool honors;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"solady/=lib/solady/src/",
"v4-core/=lib/v4-core/",
"v4-periphery/=lib/v4-periphery/",
"forge-std/=lib/forge-std/src/",
"@uniswap/v4-core/=lib/v4-core/",
"solmate/=lib/v4-core/lib/solmate/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.