@bananapus/721-hook-v6 0.0.35 → 0.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/ADMINISTRATION.md +49 -163
  2. package/ARCHITECTURE.md +71 -49
  3. package/AUDIT_INSTRUCTIONS.md +47 -84
  4. package/README.md +40 -28
  5. package/RISKS.md +85 -86
  6. package/SKILLS.md +17 -16
  7. package/USER_JOURNEYS.md +85 -62
  8. package/foundry.toml +2 -0
  9. package/package.json +1 -1
  10. package/references/operations.md +7 -3
  11. package/references/runtime.md +5 -4
  12. package/src/JB721CheckpointsDeployer.sol +2 -0
  13. package/src/JB721TiersHook.sol +0 -2
  14. package/src/JB721TiersHookProjectDeployer.sol +0 -1
  15. package/src/JB721TiersHookStore.sol +1 -2
  16. package/src/abstract/JB721Hook.sol +0 -1
  17. package/src/interfaces/IJB721CheckpointsDeployer.sol +3 -0
  18. package/src/interfaces/IJB721TiersHook.sol +0 -2
  19. package/src/interfaces/IJB721TiersHookStore.sol +1 -1
  20. package/src/libraries/JB721Constants.sol +0 -1
  21. package/src/structs/JB721InitTiersConfig.sol +0 -1
  22. package/src/structs/JB721Tier.sol +0 -2
  23. package/src/structs/JB721TierConfig.sol +0 -2
  24. package/src/structs/JB721TierConfigFlags.sol +0 -1
  25. package/src/structs/JB721TierFlags.sol +0 -1
  26. package/src/structs/JB721TiersHookFlags.sol +0 -1
  27. package/src/structs/JB721TiersMintReservesConfig.sol +0 -1
  28. package/src/structs/JB721TiersRulesetMetadata.sol +0 -1
  29. package/src/structs/JB721TiersSetDiscountPercentConfig.sol +0 -1
  30. package/src/structs/JBBitmapWord.sol +0 -1
  31. package/src/structs/JBDeploy721TiersHookConfig.sol +0 -1
  32. package/src/structs/JBLaunchProjectConfig.sol +0 -1
  33. package/src/structs/JBLaunchRulesetsConfig.sol +0 -1
  34. package/src/structs/JBPayDataHookRulesetConfig.sol +0 -1
  35. package/src/structs/JBPayDataHookRulesetMetadata.sol +0 -1
  36. package/src/structs/JBQueueRulesetsConfig.sol +0 -1
  37. package/src/structs/JBStored721Tier.sol +0 -1
  38. package/test/unit/JB721CheckpointsDeployer_AccessControl.t.sol +116 -0
package/README.md CHANGED
@@ -3,22 +3,27 @@
3
3
  `@bananapus/721-hook-v6` is the tiered NFT issuance layer for Juicebox V6. It lets a project mint ERC-721s on payment, attach tier-specific pricing and supply rules, mint reserves, and integrate custom token URI resolvers.
4
4
 
5
5
  Docs: <https://docs.juicebox.money>
6
- Architecture: [ARCHITECTURE.md](./ARCHITECTURE.md)
6
+ Architecture: [ARCHITECTURE.md](./ARCHITECTURE.md)
7
+ User journeys: [USER_JOURNEYS.md](./USER_JOURNEYS.md)
8
+ Skills: [SKILLS.md](./SKILLS.md)
9
+ Risks: [RISKS.md](./RISKS.md)
10
+ Administration: [ADMINISTRATION.md](./ADMINISTRATION.md)
11
+ Audit instructions: [AUDIT_INSTRUCTIONS.md](./AUDIT_INSTRUCTIONS.md)
7
12
 
8
13
  ## Overview
9
14
 
10
- This package is the standard NFT hook for the V6 ecosystem. Projects use it to:
15
+ This package is the main shared tiered NFT hook used across the V6 ecosystem. Projects use it to:
11
16
 
12
17
  - sell fixed-price NFT tiers through Juicebox payments
13
- - apply tier supply, reserve frequency, voting unit, and discount rules
18
+ - apply tier supply, reserve frequency, voting units, and discount rules
14
19
  - cash out tiers through the Juicebox terminal surface
15
- - compose custom metadata resolvers such as Banny or Defifa
20
+ - plug in custom metadata resolvers such as Banny or Defifa
16
21
 
17
- The deployer and project-deployer helpers make it practical to clone hooks for existing projects or launch a new project with a 721 hook already configured.
22
+ The deployer helps clone hooks for existing projects, and the project deployer helps launch new projects with a hook already attached.
18
23
 
19
- Use this repo when a project's NFT logic should be part of its payment and cash-out flow. Do not use it for collection-specific rendering or game logic; those belong in higher-level packages like Banny or Defifa.
24
+ Use this repo when a project's NFT logic should be part of its payment and cash-out flow. Do not use it for collection-specific rendering or game logic. Those belong in higher-level packages like Banny or Defifa.
20
25
 
21
- The important architectural point is that this repo does not just "mint NFTs on pay." It changes how payment value, tier state, reserves, and cash-out behavior interact.
26
+ This repo does more than "mint NFTs on pay." It changes how payment value, tier state, reserves, and cash-out behavior interact.
22
27
 
23
28
  ## Key Contracts
24
29
 
@@ -36,17 +41,10 @@ Think about the repo in three pieces:
36
41
 
37
42
  1. `JB721TiersHook` defines behavior at the project edge
38
43
  2. `JB721TiersHookStore` is the tier accounting backend
39
- 3. deployers package the hook into reusable project-launch and clone flows
44
+ 3. deployers package the hook into reusable launch and clone flows
40
45
 
41
46
  If a bug affects supply, reserve minting, or tier lookup, it usually lives in the hook-store interaction. If it affects project wiring, it usually lives in the deployer path or in how the hook is attached to rulesets.
42
47
 
43
- The shortest useful reading order is:
44
-
45
- 1. `JB721TiersHook`
46
- 2. `JB721TiersHookStore`
47
- 3. the relevant deployer
48
- 4. the resolver plugged into the hook, if the project uses one
49
-
50
48
  ## Read These Files First
51
49
 
52
50
  1. `src/JB721TiersHook.sol`
@@ -57,18 +55,26 @@ The shortest useful reading order is:
57
55
 
58
56
  ## Integration Traps
59
57
 
60
- - this hook participates in treasury-facing execution, not only metadata. Teams often underestimate the economic implications of tier splits, reserve behavior, and weight adjustments.
61
- - custom token URI resolvers should be treated as part of the project's trusted surface.
62
- - adding a 721 hook through a deployer is easy; carrying forward the right ruleset behavior over time is where mistakes happen.
63
- - projects should be explicit about whether the hook should affect pay, cash out, or only metadata-facing paths.
58
+ - this hook participates in treasury-facing execution, not only metadata
59
+ - custom token URI resolvers should be treated as part of the trusted surface
60
+ - adding a 721 hook through a deployer is easy; carrying the right ruleset behavior forward is where mistakes happen
61
+ - projects should be explicit about whether the hook affects pay, cash out, or only metadata-facing paths
64
62
 
65
63
  ## Where State Lives
66
64
 
67
- - tier definitions and accounting live primarily in `JB721TiersHookStore`
68
- - project-facing execution and permission checks live in `JB721TiersHook`
69
- - collection-specific presentation usually lives outside this repo in a resolver contract
65
+ - tier definitions and accounting: `JB721TiersHookStore`
66
+ - project-facing execution and permission checks: `JB721TiersHook`
67
+ - collection-specific presentation: usually outside this repo in a resolver contract
68
+
69
+ That split is why UI bugs, economic bugs, and deployment bugs often land in different repos even when users describe them all as "721 hook issues."
70
70
 
71
- That split is why UI bugs, economic bugs, and deployment bugs often land in different repos even though users describe them all as "721 hook issues."
71
+ ## High-Signal Tests
72
+
73
+ 1. `test/E2E/Pay_Mint_Redeem_E2E.t.sol`
74
+ 2. `test/invariants/TierLifecycleInvariant.t.sol`
75
+ 3. `test/invariants/TieredHookStoreInvariant.t.sol`
76
+ 4. `test/audit/CodexSplitCreditsMismatch.t.sol`
77
+ 5. `test/regression/ProjectDeployerRulesets.t.sol`
72
78
 
73
79
  ## Install
74
80
 
@@ -91,7 +97,7 @@ Useful scripts:
91
97
 
92
98
  ## Deployment Notes
93
99
 
94
- Hooks are deployed as clones and typically registered in the address registry. The package is designed to compose with Omnichain, Croptop, Defifa, Banny, and other ecosystem packages that rely on tier-aware NFT issuance.
100
+ Hooks are deployed as clones and typically registered in the address registry. The package is designed to compose with Omnichain, Croptop, Defifa, Banny, and other packages that rely on tier-aware NFT issuance.
95
101
 
96
102
  ## Repository Layout
97
103
 
@@ -115,9 +121,15 @@ script/
115
121
  ## Risks And Notes
116
122
 
117
123
  - tier accounting is sensitive to reserve minting, split routing, and cross-currency normalization
118
- - tiny split allocations can round down to zero recipient amounts; integrations should not rely on dust-sized split routing
119
- - custom token URI resolvers are part of the security surface because they define how metadata is served
120
- - projects need to be deliberate about whether the hook participates in pay, cash-out, or both paths
124
+ - tiny split allocations can round down to zero recipient amounts
125
+ - custom token URI resolvers are part of the security surface
126
+ - projects need to be deliberate about whether the hook participates in pay, cash out, or both paths
121
127
  - tier mutations after launch are powerful and should be permissioned carefully
122
128
 
123
- When people say "the 721 hook," they often mean three different things: the hook contract, the store, and the metadata resolver plugged into it. Audits and integrations should separate those concerns.
129
+ When people say "the 721 hook," they often mean three different things: the hook contract, the store, and the metadata resolver plugged into it.
130
+
131
+ ## For AI Agents
132
+
133
+ - Separate hook behavior, store behavior, and resolver behavior in your explanation.
134
+ - Read the store invariants and end-to-end pay/mint/redeem tests before summarizing lifecycle guarantees.
135
+ - If metadata or rendering behavior is project-specific, move to the downstream resolver repo.
package/RISKS.md CHANGED
@@ -1,119 +1,118 @@
1
1
  # Juicebox 721 Hook Risk Register
2
2
 
3
- This file focuses on the tiered-NFT accounting, reserve-mint, and cash-out risks in the shared 721 hook used across multiple higher-level products.
3
+ This file covers the tiered-NFT accounting, reserve-mint, and cash-out risks in the shared 721 hook used across multiple higher-level products.
4
4
 
5
- ## How to use this file
5
+ ## How To Use This File
6
6
 
7
- - Read `Priority risks` first; they summarize the shared 721-hook risks with the widest blast radius.
8
- - Use the detailed sections below for reentrancy, gas, tier accounting, and integration reasoning.
9
- - Treat `Invariants to Verify` as required regression coverage for any hook or store change.
7
+ - Read `Priority risks` first. They summarize the shared 721-hook risks with the widest blast radius.
8
+ - Use the later sections for reentrancy, gas, tier accounting, and integration reasoning.
9
+ - Treat `Invariants to verify` as required coverage for any hook or store change.
10
10
 
11
- ## Priority risks
11
+ ## Priority Risks
12
12
 
13
13
  | Priority | Risk | Why it matters | Primary controls |
14
14
  |----------|------|----------------|------------------|
15
- | P0 | Shared store corruption or accounting drift | `JB721TiersHookStore` is reused across products; a tier-accounting bug can affect Defifa, Croptop, Banny, revnets, and standalone hooks simultaneously. | Heavy store testing, invariant coverage, and cautious upgrades or deployments. |
16
- | P1 | Gas and iteration ceilings around tier state | Tier operations can iterate over reserves, pricing state, and cash-out weights; poorly bounded use can become a liveness issue. | Explicit gas tests, tier-count limits, and section 4 DoS analysis. |
17
- | P1 | Cash-out and reserve math mismatch | Fair redemption depends on tier supply, pending reserves, and pricing state staying aligned. | Detailed invariants, fuzzing, and integration tests with downstream consumers. |
18
-
15
+ | P0 | Shared store corruption or accounting drift | `JB721TiersHookStore` is reused across products. A tier-accounting bug can affect many repos at once. | Heavy store testing, invariants, and cautious deployment review. |
16
+ | P1 | Gas and iteration ceilings around tier state | Tier operations can iterate over reserves, pricing state, and cash-out weights. | Gas tests, tier-count limits, and DoS review. |
17
+ | P1 | Cash-out and reserve math mismatch | Fair redemption depends on tier supply, pending reserves, and pricing state staying aligned. | Detailed invariants, fuzzing, and integration tests. |
19
18
 
20
19
  ## 1. Trust Assumptions
21
20
 
22
- - **Store contract (`JB721TiersHookStore`) is fully trusted.** Record functions (`recordMint`, `recordBurn`, `recordAddTiers`, `recordTransferForTier`, `recordFlags`) have no access control -- they key state by `msg.sender`. Any address can call the store to manipulate state for a hook address it controls, but cannot affect other hooks.
23
- - **Tier configuration is partially immutable.** Once created: `price`, `initialSupply`, `reserveFrequency`, `category`, `votingUnits`, `splitPercent` are permanent. Mutable: `discountPercent` (owner-controlled, subject to `flags.cantIncreaseDiscountPercent`), `encodedIPFSUri` (owner-controlled).
24
- - **Category sort order is enforced only at insertion.** `recordAddTiers` reverts `InvalidCategorySortOrder` if tiers are not ascending by category. The sorted linked list (`_tierIdAfter`) depends on this invariant across all `adjustTiers` calls. Direct store callers could corrupt the list.
25
- - **`flags.useReserveBeneficiaryAsDefault` has global side effects.** Setting this on ANY new tier overwrites `defaultReserveBeneficiaryOf` for ALL existing tiers that lack a tier-specific `_reserveBeneficiaryOf` entry. Documented but dangerous when calling `adjustTiers` on hooks with existing tiers.
26
- - **Clone initialization is one-shot, atomic.** `initialize()` guards via an `_initialized` bool flag. The implementation contract's constructor sets `_initialized = true`, blocking direct initialization. Clones start with `_initialized = false` and set it to `true` during `initialize()`. After `initialize()` sets it, any subsequent call reverts. Deployer contracts call deploy+initialize in a single transaction, preventing front-running. Ownership transfers to `_msgSender()` at the end of `initialize`.
27
- - **`balanceOf(address(0))` reverts with a hook-specific error.** The hook explicitly reverts with `JB721TiersHook_ZeroAddress` when called with `address(0)`. This matches standard ERC-721 semantics but is still relevant for integrators that key off the custom error surface.
28
- - **`tokenURI` reverts for nonexistent tokens.** Calling `tokenURI` with a token ID that has never been minted reverts with `ERC721NonexistentToken(tokenId)`. The check is `_ownerOf(tokenId) == address(0)`.
29
- - **JBDirectory is trusted for terminal authentication.** `afterPayRecordedWith` and `afterCashOutRecordedWith` check `DIRECTORY.isTerminalOf()`. If the directory is compromised, arbitrary addresses can invoke pay/cashout hooks.
30
- - **JBPrices is trusted for cross-currency conversion.** A reverting price feed blocks all payments in non-matching currencies (DoS, not fund loss). If `address(prices) == address(0)`, cross-currency payments silently skip minting.
21
+ - **The store is trusted.** It keys state by `msg.sender`, so a hook can only affect its own namespace, but that namespace is fully trusted.
22
+ - **Tier configuration is partly immutable.** Price, supply, reserve frequency, category, voting units, and split percent are permanent after creation.
23
+ - **Category ordering matters.** The store's linked-list assumptions depend on correct sorted insertion.
24
+ - **`useReserveBeneficiaryAsDefault` has wide effects.** Setting it on a new tier can change the default reserve beneficiary for older tiers without their own explicit beneficiary.
25
+ - **Clone initialization is one-shot.** Clones are deployed and initialized atomically.
26
+ - **Directory and prices are trusted.** Terminal authentication and cross-currency behavior depend on core.
31
27
 
32
28
  ## 2. Economic Risks
33
29
 
34
- - **Cash out weight uses full undiscounted price.** `cashOutWeightOf` and `totalCashOutWeight` always use `storedTier.price`, not the discounted price. NFTs bought at a discount have cash-out value proportional to the full tier price. A `discountPercent=200` (100% off, denominator is 200) enables free minting with full cash-out weight. Mitigated by `flags.cantIncreaseDiscountPercent` flag.
35
- - **Pending reserves inflate the `totalCashOutWeight` denominator.** The total includes `price * pendingReserves` for unminted reserve NFTs. This dilutes per-NFT reclaim value before reserves are actually minted. Effect is proportional to reserve frequency and number of unminted reserves.
36
- - **Pay credits accumulate without cap.** `payCreditsOf` grows from leftover amounts after minting. Credits are per-beneficiary, not per-payer. When `payer != beneficiary`, overspend accrues to the beneficiary's credits; the payer's existing credits are not applied. No upper bound on accumulation.
37
- - **Zero-price tiers are valid.** A tier with `price=0` allows free minting. Cash-out weight for price-0 tiers is zero, so no value extraction risk. However, they still consume supply and generate pending reserves if `reserveFrequency > 0`.
38
- - **Discount denominator is 200, not 10,000.** `DISCOUNT_DENOMINATOR = 200`. A `discountPercent` of 1 = 0.5% off, 100 = 50% off, 200 = 100% off. `mulDiv` rounding makes small-price discounts lossy (e.g., `price=1, discountPercent=1` -> `mulDiv(1,1,200)=0`, no discount applied).
39
- - **Currency mismatch silently skips minting.** If payment currency differs from tier pricing currency and `PRICES == address(0)`, `_processPayment` returns without minting or reverting. Funds enter the project balance, no NFTs issued, no credits created (the normalized value is 0).
40
- - **`splitPercent` reduces minting weight.** `beforePayRecordedWith` scales down the weight returned to the terminal by `(amountValue - totalSplitAmount) / amountValue`. Payers receive fewer fungible tokens for the split portion. `issueTokensForSplits` flag overrides this to give full weight.
41
- - **Reserved NFT minting is permissionless.** Anyone can call `mintPendingReservesFor` to mint pending reserves to the tier's beneficiary. Only gated by the `mintPendingReservesPaused` ruleset flag. Timing of reserve minting is not owner-controlled.
42
- - **Cross-reference: `PRICES == address(0)` behavior.** When `address(prices) == address(0)`, cross-currency payments skip minting silently (see Trust Assumptions section 1 and Accepted Behaviors section 8.3). This is the same address stored during `initialize()` — clones that omit the prices parameter get `address(0)` permanently.
30
+ - **Cash-out weight uses full undiscounted price.**
31
+ - **Pending reserves inflate the cash-out denominator before reserves are minted.**
32
+ - **Pay credits can accumulate without a cap.**
33
+ - **Zero-price tiers are valid.**
34
+ - **Discount math uses a denominator of 200, not 10,000.**
35
+ - **Currency mismatch can silently skip minting when no prices contract is configured.**
36
+ - **`splitPercent` can reduce fungible-token minting weight.**
37
+ - **Reserve minting is permissionless.**
43
38
 
44
39
  ## 3. Reentrancy Surface
45
40
 
46
- - **Split hook callbacks (`processSplitWith`).** During `afterPayRecordedWith` -> `_processPayment` -> `distributeAll`, the library calls `split.hook.processSplitWith{value}()` for each split with a hook. This executes arbitrary code. At callback time: NFTs already minted, `payCreditsOf` updated, `remainingSupply` decremented in the store. Reentering `afterPayRecordedWith` requires terminal authentication and processes as an independent payment. All split hook and terminal calls are wrapped in try-catch to prevent a single reverting recipient from bricking all payments to the project. For native token hooks, a revert returns false (ETH stays in the contract and routes to project balance). For ERC20 hooks, tokens are transferred before the callback; a revert still returns true because the tokens have already left the contract. Tested: `TestAuditGaps_Reentrancy` confirms reentrancy is blocked by terminal check.
47
- - **Split beneficiary ETH sends.** `_sendPayoutToSplit` uses `beneficiary.call{value: amount}("")`. If the beneficiary reverts, the function returns `false` and the failed amount is accumulated separately, then routed to the project's balance after the distribution loop via `addToBalanceOf`. Later split recipients receive only their proportional share, not the failed recipient's share. Does not revert the entire payment.
48
- - **Terminal `.pay()` / `.addToBalanceOf()` during split distribution.** For project-targeted splits, the library calls the target project's primary terminal via try-catch. A reverting terminal returns false, routing the funds to the project's balance instead. For ERC20 terminal calls, approval is reset to zero on failure to prevent dangling approvals. The target terminal could call back into the hook, but the hook's state is fully settled (supply, credits, mint state). Reentrancy through this path cannot double-mint or corrupt state.
49
- - **`afterCashOutRecordedWith` execution order.** Burns tokens via `_burn()` -> `_update()` -> `STORE.tierTransferInfoOfTokenId()` in a loop, then calls `STORE.recordBurn()`. ERC721 `_update` triggers the store's tier balance decrement. Burns go to `address(0)`, so no `onERC721Received` callback.
50
- - **No `ReentrancyGuard`.** Protection relies on state ordering (all `STORE.record*` calls before external calls), terminal authentication checks, and try-catch wrapping of all external calls in `_sendPayoutToSplit`. `_mint()` uses the non-safe variant, avoiding `onERC721Received` callbacks during minting.
51
-
52
- ## 4. Gas/DoS Vectors
53
-
54
- - **`totalCashOutWeight` iterates ALL tier IDs** (1 to `maxTierIdOf`), including removed tiers with minted NFTs. Called during every `beforeCashOutRecordedWith`. At ~2-3k gas per tier, 500+ tiers approaches block gas limits. Could block all NFT cash-outs if an attacker with `ADJUST_721_TIERS` permission adds thousands of tiers.
55
- - **`balanceOf`, `votingUnitsOf`, `totalSupplyOf` iterate all tiers.** Same pattern: loop from `maxTierIdOf` down to 1. These are view functions but called by governance contracts.
56
- - **Theoretical max is not the supported operating envelope.** The store permits up to 65,535 tiers, but the practical
57
- comfort zone is far lower. The test suite demonstrates survivability at 100 to 200 tiers and also demonstrates that
58
- `balanceOf` and `totalCashOutWeight` become materially more expensive at 100 tiers than at 10 tiers. Treat large
59
- catalogs as an explicit gas-budgeting exercise, not as a default deployment shape.
60
- - **`tiersOf` traverses removed tiers.** Removed tiers are skipped via bitmap but still traversed in the linked list. `cleanTiers()` must be called separately to compact. `cleanTiers()` is permissionless and idempotent.
61
- - **Minting from many tiers in one payment.** `recordMint` loops per tier ID: storage read (stored tier + bitmap check) per iteration. 50 tiers in one payment ~5-7M gas (tested, fits in 30M block). 100+ tiers in a single mint is feasible but consumes most of the block.
62
- - **`recordAddTiers` sort-insertion cost.** Adding a low-category tier to a hook with many existing higher-category tiers iterates the entire sorted list to find the insertion point. O(n) per added tier.
63
- - **Reserve minting is unbounded per call.** `mintPendingReservesFor(tierId, count)` mints `count` NFTs in a loop. Large `count` could exceed block gas. Callers should batch.
64
- - **Max tiers capped at `uint16.max` (65,535).** Store enforces this ceiling. Practical gas limits make 1,000+ tiers problematic for on-chain reads.
65
- - **200+ tiers tested.** `TestAuditGaps_GasLimits` adds 200 tiers and verifies store correctness and gas within 30M block limit.
41
+ - **Split hook callbacks execute arbitrary code.**
42
+ - **Split beneficiary ETH sends can fail softly and reroute value.**
43
+ - **Terminal `pay` and `addToBalanceOf` calls during split distribution can reenter external systems.**
44
+ - **Split fallback can still strand value if the project terminal rejects leftovers.**
45
+ - **There is no `ReentrancyGuard`.** Safety depends on state ordering, terminal auth, and wrapped external calls.
46
+
47
+ ## 4. Gas And DoS Vectors
48
+
49
+ - **`totalCashOutWeight` iterates all tier IDs.**
50
+ - **`balanceOf`, `votingUnitsOf`, and `totalSupplyOf` also iterate all tiers.**
51
+ - **Large tier catalogs are technically allowed but not the supported operating shape.**
52
+ - **`tiersOf` still traverses removed tiers until cleanup runs.**
53
+ - **Minting across many tiers in one payment can get expensive fast.**
54
+ - **Reserve minting is loop-based and should be batched when large.**
66
55
 
67
56
  ## 5. Access Control
68
57
 
69
- - **`adjustTiers` (add/remove):** Requires `ADJUST_721_TIERS` permission from `owner()`. Respects `noNewTiersWithReserves`, `noNewTiersWithVotes`, `noNewTiersWithOwnerMinting` flags (append-only restrictions). `flags.cantBeRemoved` flag on individual tiers is enforced by the store.
70
- - **`mintFor` (owner minting):** Requires `MINT_721` permission. Bypasses price checks (`amount: type(uint256).max`). Still requires per-tier `flags.allowOwnerMint` flag. Tiers with `reserveFrequency > 0` cannot have `flags.allowOwnerMint` (enforced at creation).
71
- - **`setDiscountPercentOf`:** Requires `SET_721_DISCOUNT_PERCENT` permission. Cannot increase discount if `flags.cantIncreaseDiscountPercent` is set on the tier. Can always decrease.
72
- - **`setMetadata`:** Requires `SET_721_METADATA` permission. Can change name, symbol, baseURI, contractURI, tokenUriResolver, and per-tier IPFS URIs. Sentinel value `IJB721TokenUriResolver(address(this))` means "no change" for resolver.
73
- - **Transfer pause:** Ruleset-level flag (`transfersPaused` in 721-specific metadata, bit 0). Only applies to tiers with `flags.transfersPausable = true`. Burns (transfer to address(0)) are never paused. Tiers created with `flags.transfersPausable = false` can never be paused.
74
- - **`mintPendingReservesFor`:** Permissionless. Only gated by `mintPendingReservesPaused` ruleset flag (bit 1 of 721 metadata).
75
- - **`cleanTiers`:** Permissionless, idempotent. Compacts the sorted tier list by removing gaps from deleted tiers. No economic impact.
76
- - **Store `recordFlags`:** No access control -- stores against `msg.sender`. Safe because the store keys by caller address, but a compromised hook can freely change its own flags.
58
+ - **`adjustTiers` is permissioned and respects append-only restrictions.**
59
+ - **`mintFor` is permissioned and still depends on per-tier owner-mint flags.**
60
+ - **`setDiscountPercentOf` is permissioned and can be one-way constrained.**
61
+ - **`setMetadata` is permissioned and changes name, symbol, URIs, resolver, and tier URIs.**
62
+ - **Transfer pause is tier-sensitive.**
63
+ - **`mintPendingReservesFor` and `cleanTiers` are permissionless by design.**
77
64
 
78
65
  ## 6. Integration Risks
79
66
 
80
- - **Data hook weight override.** `beforePayRecordedWith` returns modified `weight` accounting for tier split deductions. Terminal uses this for fungible token minting. If splits consume 100% of payment, `weight = 0` and no fungible tokens are minted.
81
- - **Metadata encoding is fragile.** Relies on `JBMetadataResolver.getDataFor` with purpose strings `"pay"` / `"cashOut"` keyed by `METADATA_ID_TARGET` (original hook deploy address for clones). Malformed metadata results in no NFTs minted (pay) or no NFTs burned (cashout) without reverting (unless `preventOverspending` is true).
82
- - **`beforeCashOutRecordedWith` rejects fungible tokens.** Reverts with `JB721Hook_UnexpectedTokenCashedOut` if `context.cashOutCount > 0`. Cannot simultaneously cash out NFTs and fungible tokens in the same terminal call.
83
- - **Split group ID encoding.** Composite: `uint256(uint160(hookAddress)) | (tierId << 160)`. Tier IDs are capped at uint16, so no overflow. Splits are permanently coupled to a specific hook address -- migrating to a new hook requires re-creating all split groups.
84
- - **ERC-20 split distribution pulls from terminal.** `distributeAll` calls `SafeERC20.safeTransferFrom(token, msg.sender, address(this), amount)` to pull ERC-20s from the terminal. Requires the terminal to have granted allowance via its `_beforeTransferTo` pattern. If the terminal's allowance mechanism changes, distribution fails.
85
- - **Forwarded funds depend on non-empty split metadata.** `_processPayment` only calls `distributeAll` when both `context.forwardedAmount.value != 0` and `context.hookMetadata.length != 0`. If an integration ever forwards funds with empty hook metadata, distribution is skipped and the funds remain in the hook contract with no dedicated rescue path.
86
- - **Token URI resolver external calls.** `tokenURI()` and `tiersOf(..., includeResolvedUri=true)` call the resolver if set. A reverting resolver blocks all metadata reads (marketplace/frontend impact, no fund risk).
87
-
88
- ## 7. Invariants to Verify
89
-
90
- - **Per-tier supply conservation:** For every tier, `remainingSupply + outstanding + burned == initialSupply`, where `outstanding = initialSupply - remainingSupply - burned`.
91
- - **Total cash out weight consistency:** `totalCashOutWeight >= sum(tier.price * outstandingNFTs)` for all tiers. Equality holds when no pending reserves exist. Strictly greater when pending reserves are included.
92
- - **Reserve mints bounded by frequency:** For each tier, `reservesMinted <= ceil(nonReserveMints / reserveFrequency)`. Enforced by `_numberOfPendingReservesFor` calculation.
93
- - **Remaining supply never exceeds initial:** `remainingSupply + numberOfBurnedFor <= initialSupply` for every tier.
94
- - **Token ID uniqueness:** Generated as `tierId * 1_000_000_000 + tokenNumber`. Token numbers monotonically assigned from `initialSupply - remainingSupply`. Supply capped at `999,999,999` per tier. No collisions possible.
95
- - **Credit tracking accuracy:** `payCreditsOf[addr]` equals cumulative leftover from payments where `addr` was beneficiary, minus credits consumed by subsequent mints where `payer == beneficiary`.
96
- - **Removed tiers excluded from active listing:** `tiersOf()` never returns tiers marked in the removal bitmap.
97
- - **`maxTierIdOf` monotonically increases:** Tier removal marks a bitmap, does not decrement `maxTierIdOf`.
98
- - **Balance consistency:** `sum(tierBalanceOf[hook][owner][tierId])` across all tiers equals `ERC721._balances[owner]` for each owner.
99
- - **Cash out weight uses full price regardless of discount:** `cashOutWeightOf` for any token returns the tier's stored `price`, not the discounted purchase price.
100
- - **Discount monotonicity when locked:** If `flags.cantIncreaseDiscountPercent` is set, `discountPercent` can only decrease or stay the same.
101
- - **Flags are append-only restrictions:** `noNewTiersWithReserves`, `noNewTiersWithVotes`, `noNewTiersWithOwnerMinting` prevent future tiers from using those features but do not retroactively affect existing tiers.
67
+ - **Hook weight can override fungible-token minting.**
68
+ - **Metadata encoding is fragile.**
69
+ - **`beforeCashOutRecordedWith` rejects mixed fungible-token cash outs.**
70
+ - **Split group IDs are tightly coupled to the hook address.**
71
+ - **ERC-20 split distribution depends on terminal allowance behavior.**
72
+ - **Forwarded funds with empty hook metadata can skip distribution and remain in the hook.**
73
+ - **Token URI resolver calls can block metadata reads if the resolver reverts.**
74
+
75
+ ## 7. Invariants To Verify
76
+
77
+ - per-tier supply conservation holds
78
+ - total cash-out weight stays consistent with outstanding NFTs and pending reserves
79
+ - reserve minting stays bounded by reserve frequency
80
+ - token IDs remain unique
81
+ - credits track leftovers correctly
82
+ - removed tiers stay excluded from active listings
83
+ - store balance views match ERC-721 balances
84
+ - discount monotonicity is enforced when locked
102
85
 
103
86
  ## 8. Accepted Behaviors
104
87
 
105
- ### 8.1 Pending reserves inflate `totalCashOutWeight` denominator (by design)
88
+ ### 8.1 Pending reserves dilute cash-out value before minting
89
+
90
+ This is intentional. Including pending reserves in the denominator prevents reserve front-running.
91
+
92
+ ### 8.2 Cash-out weight uses full price regardless of discount
93
+
94
+ This is intentional. The cash-out weight represents treasury share, not purchase price.
95
+
96
+ ### 8.3 Currency mismatch can skip minting when no prices surface exists
97
+
98
+ If currencies differ and `PRICES == address(0)`, payments can increase project balance without minting NFTs. That is an accepted degradation rather than a revert path.
99
+
100
+ ### 8.4 Tiny split allocations can round down to zero
101
+
102
+ Dust-sized split allocations can become economically lossy after rounding.
103
+
104
+ ### 8.5 Failed split payouts only degrade cleanly if the fallback terminal path works
106
105
 
107
- `totalCashOutWeight` includes `price * pendingReserves` for unminted reserve NFTs. This dilutes per-NFT reclaim value before reserves are actually minted. This is intentional: if pending reserves were excluded, a holder could front-run `mintPendingReservesFor` to cash out at an inflated per-NFT value, then the reserve mint would reduce the remaining holders' share. Including pending reserves in the denominator ensures that the reserve allocation is priced in at all times, preventing front-running. The trade-off is that minting reserves (via the permissionless `mintPendingReservesFor`) does not change individual cash-out values — the reserves are already accounted for.
106
+ If both the primary split path and the fallback `addToBalanceOf` path fail, the hook can retain assets with no built-in rescue path.
108
107
 
109
- ### 8.2 Cash-out weight uses full price regardless of discount (by design)
108
+ ### 8.6 Credit-funded tier purchases may underfund split obligations
110
109
 
111
- `cashOutWeightOf` returns the tier's stored `price`, not the discounted purchase price. An NFT bought at 50% discount has the same cash-out weight as one bought at full price. This is intentional: the cash-out weight represents the NFT's share of the project's treasury, not the purchase price paid. Changing cash-out weight based on discount would require per-token storage of purchase price, adding significant gas cost. The discount mechanism is designed for promotional pricing, not for creating tiered cash-out classes.
110
+ Pay credits can be used to buy tiers that carry a `splitPercent`. When credits satisfy part of the tier price, the fresh ETH forwarded to splits may be less than the split obligation implied by the full tier price. Project owners who consider this a problem should enable the `preventBuyingTierWithCredits` flag on affected tiers. This is accepted behavior.
112
111
 
113
- ### 8.3 Currency mismatch silently skips minting (accepted degradation)
112
+ ### 8.7 Changing the default reserve beneficiary redirects pending reserves
114
113
 
115
- If the payment currency differs from the tier pricing currency and `PRICES == address(0)`, `_processPayment` returns without minting NFTs or creating credits. Funds enter the project balance but no NFTs are issued. This is accepted because: (1) reverting would block all payments in the mismatched currency, (2) the project owner chose not to configure price feeds (by not setting `PRICES`), and (3) the funds are not lost they increase the project's surplus and are reclaimable via cash-out. Projects that need cross-currency NFT minting must configure `JBPrices`.
114
+ When the default reserve beneficiary is updated, any pending (unminted) reserves across all tiers that rely on the default will be distributed to the new beneficiary once minted. This is by design the project owner controls reserve distribution targets and may intentionally redirect pending reserves by updating the default.
116
115
 
117
- ### 8.4 Tiny split allocations can round down to zero recipient amounts
116
+ ### 8.8 Discounted credit mints retain full cash-out weight
118
117
 
119
- Split metadata is expressed in whole token units after conversion and capping. For very small allocations, each rounded per-tier split amount can become zero even though the overall forwarded amount is still reduced by the capped split total. This is an accepted precision tradeoff for dust-sized payments: integrations should not rely on sub-precision split routing and should expect tiny split allocations to be economically lossy.
118
+ Tokens minted at a discounted price via credits still carry the full undiscounted tier price as their cash-out weight. This means a holder who purchased at a discount receives the same treasury share as a holder who paid full price. Project owners should factor this into discount percentage decisions, as aggressive discounts can create favorable cash-out economics for discounted buyers.
package/SKILLS.md CHANGED
@@ -2,41 +2,42 @@
2
2
 
3
3
  ## Use This File For
4
4
 
5
- - Use this file when the task involves tiered NFT issuance, reserve minting, voting units, tier splits, or token URI resolver integration for Juicebox projects.
6
- - Start here, then open the hook, store, deployer, or tests that own the exact behavior you are changing.
5
+ - Use this file when the task involves tiered NFT minting, reserve minting, tier adjustments, deployer wiring, or 721-aware cash-out behavior.
6
+ - Start here, then decide whether the issue is in hook execution, store accounting, deployer setup, or resolver behavior.
7
7
 
8
8
  ## Read This Next
9
9
 
10
10
  | If you need... | Open this next |
11
11
  |---|---|
12
- | Repo overview and integration model | [`README.md`](./README.md), [`ARCHITECTURE.md`](./ARCHITECTURE.md) |
13
- | Runtime hook behavior | [`src/JB721TiersHook.sol`](./src/JB721TiersHook.sol), [`src/abstract/JB721Hook.sol`](./src/abstract/JB721Hook.sol) |
14
- | Tier storage and accounting | [`src/JB721TiersHookStore.sol`](./src/JB721TiersHookStore.sol) |
15
- | Deployment or project launch helpers | [`src/JB721TiersHookDeployer.sol`](./src/JB721TiersHookDeployer.sol), [`src/JB721TiersHookProjectDeployer.sol`](./src/JB721TiersHookProjectDeployer.sol), [`script/Deploy.s.sol`](./script/Deploy.s.sol) |
16
- | Shared libraries, interfaces, and resolver surface | [`src/libraries/`](./src/libraries/), [`src/interfaces/`](./src/interfaces/), [`src/structs/`](./src/structs/) |
17
- | Invariants, E2E flows, and regressions | [`test/invariants/`](./test/invariants/), [`test/E2E/`](./test/E2E/), [`test/regression/`](./test/regression/), [`test/TestVotingUnitsLifecycle.t.sol`](./test/TestVotingUnitsLifecycle.t.sol) |
12
+ | Repo overview and architecture | [`README.md`](./README.md), [`ARCHITECTURE.md`](./ARCHITECTURE.md) |
13
+ | Runtime hook behavior | [`src/JB721TiersHook.sol`](./src/JB721TiersHook.sol) |
14
+ | Tier accounting | [`src/JB721TiersHookStore.sol`](./src/JB721TiersHookStore.sol) |
15
+ | Shared math and metadata helpers | [`src/libraries/`](./src/libraries/), [`src/interfaces/`](./src/interfaces/), [`src/structs/`](./src/structs/) |
16
+ | Deployer flows | [`src/JB721TiersHookDeployer.sol`](./src/JB721TiersHookDeployer.sol), [`src/JB721TiersHookProjectDeployer.sol`](./src/JB721TiersHookProjectDeployer.sol) |
17
+ | Lifecycle, invariant, and audit coverage | [`test/E2E/Pay_Mint_Redeem_E2E.t.sol`](./test/E2E/Pay_Mint_Redeem_E2E.t.sol), [`test/invariants/TierLifecycleInvariant.t.sol`](./test/invariants/TierLifecycleInvariant.t.sol), [`test/invariants/TieredHookStoreInvariant.t.sol`](./test/invariants/TieredHookStoreInvariant.t.sol), [`test/audit/CodexSplitCreditsMismatch.t.sol`](./test/audit/CodexSplitCreditsMismatch.t.sol) |
18
18
 
19
19
  ## Repo Map
20
20
 
21
21
  | Area | Where to look |
22
22
  |---|---|
23
23
  | Main contracts | [`src/`](./src/) |
24
- | Abstract bases, interfaces, structs, and libraries | [`src/abstract/`](./src/abstract/), [`src/interfaces/`](./src/interfaces/), [`src/structs/`](./src/structs/), [`src/libraries/`](./src/libraries/) |
24
+ | Libraries, interfaces, and structs | [`src/libraries/`](./src/libraries/), [`src/interfaces/`](./src/interfaces/), [`src/structs/`](./src/structs/) |
25
25
  | Scripts | [`script/`](./script/) |
26
26
  | Tests | [`test/`](./test/) |
27
27
 
28
28
  ## Purpose
29
29
 
30
- Tiered ERC-721 NFT issuance and cash-out hook for Juicebox V6. This repo controls tier pricing, reserve issuance, voting units, split forwarding, and deployer flows for projects that mint NFTs on pay.
30
+ Tiered NFT hook for Juicebox V6. This repo handles priced NFT tiers, reserve logic, tier-aware cash outs, and deployer flows that wire those hooks into projects.
31
31
 
32
32
  ## Reference Files
33
33
 
34
- - Open [`references/runtime.md`](./references/runtime.md) when you need the contract roles, payment and cash-out path, reserve math, or the main invariants that should hold while editing.
35
- - Open [`references/operations.md`](./references/operations.md) when you need deployer behavior, metadata and permission surfaces, test breadcrumbs, or the common failure modes to verify before shipping.
34
+ - Open [`references/runtime.md`](./references/runtime.md) when you need hook and store roles, cash-out weight behavior, or main invariants.
35
+ - Open [`references/operations.md`](./references/operations.md) when you need permission paths, tier-adjustment rules, test breadcrumbs, or common stale assumptions.
36
36
 
37
37
  ## Working Rules
38
38
 
39
- - Start in [`src/JB721TiersHook.sol`](./src/JB721TiersHook.sol) for pay and cash-out behavior, but verify storage-side assumptions in [`src/JB721TiersHookStore.sol`](./src/JB721TiersHookStore.sol) before changing mint, burn, reserve, or supply logic.
40
- - Treat tier splits, reserve minting, and discounted pricing as treasury-sensitive. Check both runtime code and regression coverage before assuming a change is local.
41
- - When a task mentions token metadata or rendering, confirm whether the behavior lives in this repo or in an external resolver. Do not over-edit the hook when the real change belongs downstream.
42
- - When changing deployers or initialization, verify the hook, store, and project-launch path stay aligned. These flows are tightly coupled.
39
+ - Start in [`src/JB721TiersHookStore.sol`](./src/JB721TiersHookStore.sol) for tier accounting questions.
40
+ - Keep hook behavior, store behavior, and resolver behavior separate.
41
+ - Reserve logic, split routing, and cash-out weight calculations are part of the economic surface.
42
+ - Tier adjustments are high-risk because many tier properties are intentionally immutable after creation.
43
+ - If a problem looks like metadata only, verify it is not actually a hook or store issue first.