@bananapus/721-hook-v6 0.0.10 → 0.0.12

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.
package/SKILLS.md CHANGED
@@ -21,11 +21,11 @@ Tiered ERC-721 NFT hook for Juicebox V6 that mints NFTs when a project is paid a
21
21
 
22
22
  | Function | Contract | What it does |
23
23
  |----------|----------|--------------|
24
- | `initialize(projectId, name, symbol, baseUri, tokenUriResolver, contractUri, tiersConfig, flags)` | `JB721TiersHook` | One-time setup for a cloned hook instance. Stores pricing context (currency, decimals, prices contract packed into uint256), records tiers and flags in the store. Validates `decimals <= 18`. |
24
+ | `initialize(projectId, name, symbol, baseUri, tokenUriResolver, contractUri, tiersConfig, flags)` | `JB721TiersHook` | One-time setup for a cloned hook instance. Stores pricing context (currency, decimals, prices contract packed into uint256), records tiers and flags in the store. Registers any configured tier splits in `JBSplits` via `SPLITS.setSplitGroupsOf`. Validates `decimals <= 18`. |
25
25
  | `afterPayRecordedWith(context)` | `JB721Hook` | Called by terminal after payment. Validates caller is a project terminal, delegates to virtual `_processPayment`. |
26
26
  | `_processPayment(context)` | `JB721TiersHook` | Normalizes payment value via pricing context, decodes payer metadata for tier IDs to mint, calls `_mintAll`, manages pay credits for overspending. Distributes tier split funds via `JB721TiersHookLib.distributeAll` if split amounts were forwarded. |
27
27
  | `afterCashOutRecordedWith(context)` | `JB721Hook` | Called by terminal during cash out. Decodes token IDs from metadata, validates ownership, burns NFTs, delegates to virtual `_didBurn`. Reverts if `msg.value != 0`. |
28
- | `beforePayRecordedWith(context)` | `JB721TiersHook` | Data hook: returns original weight, calculates per-tier split amounts via `JB721TiersHookLib.calculateSplitAmounts`, and sets this contract as the pay hook with the total split amount forwarded. |
28
+ | `beforePayRecordedWith(context)` | `JB721TiersHook` | Data hook: calculates per-tier split amounts via `JB721TiersHookLib.calculateSplitAmounts`, adjusts the weight proportionally so the terminal only mints tokens for the amount that actually enters the project (i.e., `weight = mulDiv(context.weight, amount - totalSplitAmount, amount)`), and sets this contract as the pay hook with the total split amount forwarded. If no splits, returns original weight unchanged. If splits consume the entire payment, returns weight 0. If the `issueTokensForSplits` flag is set, returns the full `context.weight` regardless of splits. |
29
29
  | `beforeCashOutRecordedWith(context)` | `JB721Hook` | Data hook: calculates `cashOutCount` (via virtual `cashOutWeightOf`) and `totalSupply` (via virtual `totalCashOutWeight`). Rejects if fungible tokens are also being cashed out. |
30
30
  | `adjustTiers(tiersToAdd, tierIdsToRemove)` | `JB721TiersHook` | Owner-only. Adds/removes tiers via `JB721TiersHookLib.adjustTiersFor` (DELEGATECALL). Requires `ADJUST_721_TIERS` permission. Registers tier splits in `JBSplits` if configured. |
31
31
  | `mintFor(tierIds, beneficiary)` | `JB721TiersHook` | Owner-only manual mint. Requires `MINT_721` permission. Passes `amount: type(uint256).max` and `isOwnerMint: true` to force the mint. |
@@ -60,8 +60,8 @@ Tiered ERC-721 NFT hook for Juicebox V6 that mints NFTs when a project is paid a
60
60
  | `votingUnitsOf(hook, account)` | `JB721TiersHookStore` | Returns total voting units for an address across all tiers. Uses custom `votingUnits` if `useVotingUnits` is set, otherwise uses tier price. |
61
61
  | `tierVotingUnitsOf(hook, account, tierId)` | `JB721TiersHookStore` | Returns voting units for an address within a specific tier. |
62
62
  | `calculateSplitAmounts(store, hook, metadataIdTarget, metadata)` | `JB721TiersHookLib` | Called in `beforePayRecordedWith`. Decodes tier IDs from payer metadata, looks up each tier's `splitPercent`, calculates `mulDiv(price, splitPercent, SPLITS_TOTAL_PERCENT)` per tier, returns `totalSplitAmount` (forwarded to hook as `amount`) and encoded `hookMetadata` (tier IDs + amounts). |
63
- | `distributeAll(directory, projectId, hookAddress, token, encodedSplitData)` | `JB721TiersHookLib` | Called in `afterPayRecordedWith`. Decodes per-tier amounts, looks up each tier's splits from `JBSplits` by group ID (`hookAddress | (tierId << 160)`), distributes to split recipients. Leftover goes to project balance via `addToBalance`. |
64
- | `adjustTiersFor(store, directory, projectId, hookAddress, caller, tiersToAdd, tierIdsToRemove)` | `JB721TiersHookLib` | Called via DELEGATECALL from `adjustTiers`. Removes tiers, adds tiers, emits events, and registers any configured splits in `JBSplits` via the project's controller. |
63
+ | `distributeAll(directory, splits, projectId, hookAddress, token, encodedSplitData)` | `JB721TiersHookLib` | Called in `afterPayRecordedWith`. Decodes per-tier amounts, looks up each tier's splits from `JBSplits` by group ID (`hookAddress | (tierId << 160)`), distributes to split recipients. Leftover goes to project balance via `addToBalance`. |
64
+ | `adjustTiersFor(store, splits, projectId, hookAddress, caller, tiersToAdd, tierIdsToRemove)` | `JB721TiersHookLib` | Called via DELEGATECALL from `adjustTiers`. Removes tiers, adds tiers, emits events, and registers any configured splits directly in `JBSplits`. |
65
65
  | `normalizePaymentValue(packedPricingContext, projectId, amountValue, amountCurrency, amountDecimals)` | `JB721TiersHookLib` | Converts a payment value to the hook's pricing currency using `JBPrices`. Returns `(0, false)` if currencies differ and no prices contract is set. |
66
66
  | `resolveTokenURI(store, hook, baseUri, tokenId)` | `JB721TiersHookLib` | Resolves token URI: checks for custom `tokenUriResolver` first, otherwise decodes IPFS URI via `JBIpfsDecoder`. |
67
67
 
@@ -69,7 +69,7 @@ Tiered ERC-721 NFT hook for Juicebox V6 that mints NFTs when a project is paid a
69
69
 
70
70
  | Dependency | Import | Used For |
71
71
  |------------|--------|----------|
72
- | `@bananapus/core-v6` | `IJBDirectory`, `IJBRulesets`, `IJBPrices`, `IJBController`, `IJBTerminal`, `IJBSplits`, `JBRuleset`, `JBRulesetMetadata`, `JBAfterPayRecordedContext`, `JBBeforeCashOutRecordedContext`, `JBSplit`, `JBSplitGroup`, `JBConstants`, etc. | Terminal validation, ruleset metadata, pricing, payment/cash-out contexts, splits |
72
+ | `@bananapus/core-v6` | `IJBDirectory`, `IJBRulesets`, `IJBPrices`, `IJBSplits`, `IJBTerminal`, `JBRuleset`, `JBRulesetMetadata`, `JBAfterPayRecordedContext`, `JBBeforeCashOutRecordedContext`, `JBSplit`, `JBSplitGroup`, `JBConstants`, etc. | Terminal validation, ruleset metadata, pricing, payment/cash-out contexts, splits |
73
73
  | `@bananapus/ownable-v6` | `JBOwnable` | Project-based ownership for the hook (ownership can be transferred to a project NFT) |
74
74
  | `@bananapus/permission-ids-v6` | `JBPermissionIds` | Permission IDs: `ADJUST_721_TIERS`, `MINT_721`, `SET_721_METADATA`, `SET_721_DISCOUNT_PERCENT`, `QUEUE_RULESETS`, `SET_TERMINALS` |
75
75
  | `@bananapus/address-registry-v6` | `IJBAddressRegistry` | Registering deployed hook clones |
@@ -86,7 +86,7 @@ Tiered ERC-721 NFT hook for Juicebox V6 that mints NFTs when a project is paid a
86
86
  | `JBStored721Tier` | `uint104 price`, `uint32 remainingSupply`, `uint32 initialSupply`, `uint32 splitPercent`, `uint24 category`, `uint8 discountPercent`, `uint16 reserveFrequency`, `uint8 packedBools` (allowOwnerMint, transfersPausable, useVotingUnits, cannotBeRemoved, cannotIncreaseDiscountPercent) | Internal storage in `JB721TiersHookStore`. Voting units stored separately in `_tierVotingUnitsOf` when `useVotingUnits` is true. |
87
87
  | `JB721InitTiersConfig` | `JB721TierConfig[] tiers`, `uint32 currency`, `uint8 decimals`, `IJBPrices prices` | `initialize` -- defines tiers and pricing context |
88
88
  | `JBDeploy721TiersHookConfig` | `string name`, `string symbol`, `string baseUri`, `IJB721TokenUriResolver tokenUriResolver`, `string contractUri`, `JB721InitTiersConfig tiersConfig`, `address reserveBeneficiary`, `JB721TiersHookFlags flags` | `deployHookFor`, `launchProjectFor` |
89
- | `JB721TiersHookFlags` | `bool noNewTiersWithReserves`, `bool noNewTiersWithVotes`, `bool noNewTiersWithOwnerMinting`, `bool preventOverspending` | `initialize`, `recordFlags` |
89
+ | `JB721TiersHookFlags` | `bool noNewTiersWithReserves`, `bool noNewTiersWithVotes`, `bool noNewTiersWithOwnerMinting`, `bool preventOverspending`, `bool issueTokensForSplits` | `initialize`, `recordFlags` |
90
90
  | `JB721TiersRulesetMetadata` | `bool pauseTransfers`, `bool pauseMintPendingReserves` | Packed into `JBRulesetMetadata.metadata` per-ruleset (bit 0 = pauseTransfers, bit 1 = pauseMintPendingReserves) |
91
91
  | `JBPayDataHookRulesetConfig` | `uint48 mustStartAtOrAfter`, `uint32 duration`, `uint112 weight`, `uint32 weightCutPercent`, `IJBRulesetApprovalHook approvalHook`, `JBPayDataHookRulesetMetadata metadata`, `JBSplitGroup[] splitGroups`, `JBFundAccessLimitGroup[] fundAccessLimitGroups` | `JB721TiersHookProjectDeployer` -- wraps core ruleset config with `useDataHookForPay: true` hardcoded |
92
92
  | `JBPayDataHookRulesetMetadata` | Same as `JBRulesetMetadata` minus `allowSetCustomToken` (hardcoded false) and `useDataHookForPay` (hardcoded true) and `dataHook` (set to deployed hook). Includes `ownerMustSendPayouts`. | `launchProjectFor`, `launchRulesetsFor`, `queueRulesetsOf` |
@@ -137,14 +137,14 @@ Each tier has configurable voting power:
137
137
 
138
138
  - Each tier can route a percentage of its mint price to configured split recipients. The `splitPercent` field (out of `JBConstants.SPLITS_TOTAL_PERCENT` = 1,000,000,000) determines how much of the price is forwarded.
139
139
  - Split recipients are stored in `JBSplits` using group IDs computed as `uint256(uint160(hookAddress)) | (uint256(tierId) << 160)`.
140
- - Splits are registered via `JB721TiersHookLib._setSplitGroupsFor` when tiers with `splits` are added.
141
- - In `beforePayRecordedWith`, `calculateSplitAmounts` decodes tier IDs from payer metadata, computes `mulDiv(price, splitPercent, SPLITS_TOTAL_PERCENT)` per tier, and returns the total to be forwarded to the hook.
140
+ - Splits are registered in `JBSplits` both during `initialize()` (for tiers included at launch) and during `adjustTiers()` (for tiers added later), using the hook's `SPLITS` immutable directly.
141
+ - In `beforePayRecordedWith`, `calculateSplitAmounts` decodes tier IDs from payer metadata, computes `mulDiv(price, splitPercent, SPLITS_TOTAL_PERCENT)` per tier, and returns the total to be forwarded to the hook. The weight is adjusted down proportionally unless the `issueTokensForSplits` flag is set, in which case the full `context.weight` is returned.
142
142
  - In `afterPayRecordedWith`, `distributeAll` distributes forwarded funds to each tier's split group recipients. Leftover after all splits goes back to the project's balance via `addToBalance`.
143
143
  - Split recipients can be projects (via `terminal.pay` or `terminal.addToBalance`) or plain addresses (direct ETH transfer or `SafeERC20.safeTransfer`). Splits with no `projectId` and no `beneficiary` are skipped -- their share stays in the leftover and is routed to the project's own balance via `addToBalanceOf`, preventing a misconfigured split from bricking the payout distribution.
144
144
 
145
145
  ## Gotchas
146
146
 
147
- - `JB721TiersHook` is deployed as a **minimal clone** (not a full deployment). The constructor sets immutables (`RULESETS`, `STORE`, `DIRECTORY`, `METADATA_ID_TARGET`), and `initialize()` sets per-instance state. Calling `initialize()` twice reverts with `JB721TiersHook_AlreadyInitialized`.
147
+ - `JB721TiersHook` is deployed as a **minimal clone** (not a full deployment). The constructor sets immutables (`RULESETS`, `STORE`, `SPLITS`, `DIRECTORY`, `METADATA_ID_TARGET`), and `initialize()` sets per-instance state. Calling `initialize()` twice reverts with `JB721TiersHook_AlreadyInitialized`.
148
148
  - **`JB721Hook` abstract base**: `JB721TiersHook` extends `JB721Hook`, which handles generic 721 hook lifecycle (terminal validation, burn loop, metadata decoding). `JB721TiersHook` overrides `cashOutWeightOf`, `totalCashOutWeight`, `_didBurn`, `_processPayment`, and `beforePayRecordedWith`. Errors like `JB721Hook_InvalidPay` and `JB721Hook_InvalidCashOut` are defined on the abstract class, not `JB721TiersHook`.
149
149
  - **Pricing context is bit-packed** into a single `uint256`: currency (bits 0-31), decimals (bits 32-39), prices contract address (bits 40-199). Read it via `pricingContext()`.
150
150
  - **Pricing decimals must be <= 18**: `initialize` reverts with `JB721TiersHook_InvalidPricingDecimals` otherwise.
@@ -169,6 +169,8 @@ Each tier has configurable voting power:
169
169
  - **Max initial supply per tier is 999,999,999** (`_ONE_BILLION - 1`). Exceeding this would cause token ID overflow into the next tier's ID space.
170
170
  - **`noNewTiersWithVotes` blocks all voting power**: It rejects tiers where voting units would be non-zero, whether from custom `votingUnits` or from a non-zero `price` (when `useVotingUnits` is false).
171
171
  - **`firstOwnerOf` is lazy**: The first owner is only stored when the token is first transferred away from its original holder. Before any transfer, `firstOwnerOf` returns the current owner.
172
+ - **Tiers must be sorted by category, NOT price.** `recordAddTiers` reverts with `JB721TiersHookStore_InvalidCategorySortOrder` if tiers aren't in ascending category order. The `JB721InitTiersConfig` struct comment previously said "sorted by price" but the code enforces category ordering. Within the same category, tiers can be in any order.
173
+ - **Always use `JB721TiersHookProjectDeployer.launchProjectFor` even without NFTs.** Pass an empty tiers array to enable future NFT additions without migration. If a project is launched via `JBController.launchProjectFor` instead, adding NFT tiers later requires wiring a new data hook into a new ruleset — using the 721 deployer from the start avoids this.
172
174
 
173
175
  ## Example Integration
174
176
 
@@ -223,7 +225,8 @@ tiers[0] = JB721TierConfig({
223
225
  noNewTiersWithReserves: false,
224
226
  noNewTiersWithVotes: false,
225
227
  noNewTiersWithOwnerMinting: false,
226
- preventOverspending: false
228
+ preventOverspending: false,
229
+ issueTokensForSplits: false
227
230
  })
228
231
  }),
229
232
  launchProjectConfig: launchConfig, // JBLaunchProjectConfig with rulesets, terminals, etc.
package/STYLE_GUIDE.md ADDED
@@ -0,0 +1,470 @@
1
+ # Style Guide
2
+
3
+ How we write Solidity and organize repos across the Juicebox V6 ecosystem. `nana-core-v6` is the gold standard — when in doubt, match what it does.
4
+
5
+ ## File Organization
6
+
7
+ ```
8
+ src/
9
+ ├── Contract.sol # Main contracts in root
10
+ ├── abstract/ # Base contracts (JBPermissioned, JBControlled)
11
+ ├── enums/ # One enum per file
12
+ ├── interfaces/ # One interface per file, prefixed with I
13
+ ├── libraries/ # Pure/view logic, prefixed with JB
14
+ ├── periphery/ # Utility contracts (deadlines, price feeds)
15
+ └── structs/ # One struct per file, prefixed with JB
16
+ ```
17
+
18
+ One contract/interface/struct/enum per file. Name the file after the type it contains.
19
+
20
+ **Structs, enums, libraries, and interfaces always go in their subdirectories** (`src/structs/`, `src/enums/`, `src/libraries/`, `src/interfaces/`) — never inline in contract files or placed in `src/` root. This keeps type definitions discoverable and import paths consistent across repos.
21
+
22
+ ## Pragma Versions
23
+
24
+ ```solidity
25
+ // Contracts — pin to exact version
26
+ pragma solidity 0.8.26;
27
+
28
+ // Interfaces, structs, enums — caret for forward compatibility
29
+ pragma solidity ^0.8.0;
30
+
31
+ // Libraries — caret, may use newer features
32
+ pragma solidity ^0.8.17;
33
+ ```
34
+
35
+ ## Imports
36
+
37
+ Named imports only. Grouped by source, alphabetized within each group:
38
+
39
+ ```solidity
40
+ // External packages (alphabetized)
41
+ import {ERC2771Context} from "@openzeppelin/contracts/metatx/ERC2771Context.sol";
42
+ import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
43
+ import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
44
+ import {mulDiv} from "@prb/math/src/Common.sol";
45
+
46
+ // Local: abstract contracts
47
+ import {JBPermissioned} from "./abstract/JBPermissioned.sol";
48
+
49
+ // Local: interfaces (alphabetized)
50
+ import {IJBController} from "./interfaces/IJBController.sol";
51
+ import {IJBDirectory} from "./interfaces/IJBDirectory.sol";
52
+ import {IJBMultiTerminal} from "./interfaces/IJBMultiTerminal.sol";
53
+
54
+ // Local: libraries (alphabetized)
55
+ import {JBConstants} from "./libraries/JBConstants.sol";
56
+ import {JBFees} from "./libraries/JBFees.sol";
57
+
58
+ // Local: structs (alphabetized)
59
+ import {JBAccountingContext} from "./structs/JBAccountingContext.sol";
60
+ import {JBSplit} from "./structs/JBSplit.sol";
61
+ ```
62
+
63
+ ## Contract Structure
64
+
65
+ Section banners divide the contract into a fixed ordering. Every contract with 50+ lines uses these banners:
66
+
67
+ ```solidity
68
+ /// @notice One-line description.
69
+ contract JBExample is JBPermissioned, IJBExample {
70
+ // A library that does X.
71
+ using SomeLib for SomeType;
72
+
73
+ //*********************************************************************//
74
+ // --------------------------- custom errors ------------------------- //
75
+ //*********************************************************************//
76
+
77
+ error JBExample_SomethingFailed(uint256 amount);
78
+
79
+ //*********************************************************************//
80
+ // ------------------------- public constants ------------------------ //
81
+ //*********************************************************************//
82
+
83
+ uint256 public constant override FEE = 25;
84
+
85
+ //*********************************************************************//
86
+ // ----------------------- internal constants ------------------------ //
87
+ //*********************************************************************//
88
+
89
+ uint256 internal constant _FEE_BENEFICIARY_PROJECT_ID = 1;
90
+
91
+ //*********************************************************************//
92
+ // --------------- public immutable stored properties ---------------- //
93
+ //*********************************************************************//
94
+
95
+ IJBDirectory public immutable override DIRECTORY;
96
+
97
+ //*********************************************************************//
98
+ // --------------------- public stored properties -------------------- //
99
+ //*********************************************************************//
100
+
101
+ //*********************************************************************//
102
+ // -------------------- internal stored properties ------------------- //
103
+ //*********************************************************************//
104
+
105
+ //*********************************************************************//
106
+ // -------------------------- constructor ---------------------------- //
107
+ //*********************************************************************//
108
+
109
+ //*********************************************************************//
110
+ // ---------------------- receive / fallback ------------------------- //
111
+ //*********************************************************************//
112
+
113
+ //*********************************************************************//
114
+ // --------------------------- modifiers ----------------------------- //
115
+ //*********************************************************************//
116
+
117
+ //*********************************************************************//
118
+ // ---------------------- external transactions ---------------------- //
119
+ //*********************************************************************//
120
+
121
+ //*********************************************************************//
122
+ // ----------------------- external views ---------------------------- //
123
+ //*********************************************************************//
124
+
125
+ //*********************************************************************//
126
+ // ----------------------- public transactions ----------------------- //
127
+ //*********************************************************************//
128
+
129
+ //*********************************************************************//
130
+ // ----------------------- internal helpers -------------------------- //
131
+ //*********************************************************************//
132
+
133
+ //*********************************************************************//
134
+ // ----------------------- internal views ---------------------------- //
135
+ //*********************************************************************//
136
+
137
+ //*********************************************************************//
138
+ // ----------------------- private helpers --------------------------- //
139
+ //*********************************************************************//
140
+ }
141
+ ```
142
+
143
+ **Section order:**
144
+ 1. `using` declarations
145
+ 2. Custom errors
146
+ 3. Public constants
147
+ 4. Internal constants
148
+ 5. Public immutable stored properties
149
+ 6. Internal immutable stored properties
150
+ 7. Public stored properties
151
+ 8. Internal stored properties
152
+ 9. Constructor
153
+ 10. `receive` / `fallback`
154
+ 11. Modifiers
155
+ 12. External transactions
156
+ 13. External views
157
+ 14. Public transactions
158
+ 15. Internal helpers
159
+ 16. Internal views
160
+ 17. Private helpers
161
+
162
+ Functions are alphabetized within each section.
163
+
164
+ **Events:** Events are declared in interfaces only, never in implementation contracts. Implementations inherit events from their interface and emit them unqualified. This keeps the ABI definition in one place and allows tests to use interface-qualified event expectations (e.g., `emit IJBController.LaunchProject(...)`).
165
+
166
+ ## Interface Structure
167
+
168
+ ```solidity
169
+ /// @notice One-line description.
170
+ interface IJBExample is IJBBase {
171
+ // Events (with full NatSpec)
172
+
173
+ /// @notice Emitted when X happens.
174
+ /// @param projectId The ID of the project.
175
+ /// @param amount The amount transferred.
176
+ event SomethingHappened(uint256 indexed projectId, uint256 amount);
177
+
178
+ // Views (alphabetized)
179
+
180
+ /// @notice The directory of terminals and controllers.
181
+ function DIRECTORY() external view returns (IJBDirectory);
182
+
183
+ // State-changing functions (alphabetized)
184
+
185
+ /// @notice Does the thing.
186
+ /// @param projectId The ID of the project.
187
+ /// @return result The result.
188
+ function doThing(uint256 projectId) external returns (uint256 result);
189
+ }
190
+ ```
191
+
192
+ **Rules:**
193
+ - Events first, then views, then state-changing functions
194
+ - No custom errors in interfaces — errors belong in the implementing contract
195
+ - Full NatSpec on every event, function, and parameter
196
+ - Alphabetized within each group
197
+
198
+ ## Naming
199
+
200
+ | Thing | Convention | Example |
201
+ |-------|-----------|---------|
202
+ | Contract | PascalCase | `JBMultiTerminal` |
203
+ | Interface | `I` + PascalCase | `IJBMultiTerminal` |
204
+ | Library | PascalCase | `JBCashOuts` |
205
+ | Struct | PascalCase | `JBRulesetConfig` |
206
+ | Enum | PascalCase | `JBApprovalStatus` |
207
+ | Enum value | PascalCase | `ApprovalExpected` |
208
+ | Error | `ContractName_ErrorName` | `JBMultiTerminal_FeeTerminalNotFound` |
209
+ | Public constant | `ALL_CAPS` | `FEE`, `MAX_FEE` |
210
+ | Internal constant | `_ALL_CAPS` | `_FEE_HOLDING_SECONDS` |
211
+ | Public immutable | `ALL_CAPS` | `DIRECTORY`, `PERMISSIONS` |
212
+ | Public/external function | `camelCase` | `cashOutTokensOf` |
213
+ | Internal/private function | `_camelCase` | `_processFee` |
214
+ | Internal storage | `_camelCase` | `_accountingContextForTokenOf` |
215
+ | Function parameter | `camelCase` | `projectId`, `cashOutCount` |
216
+
217
+ ## NatSpec
218
+
219
+ **Contracts:**
220
+ ```solidity
221
+ /// @notice One-line description of what the contract does.
222
+ contract JBExample is IJBExample {
223
+ ```
224
+
225
+ **Functions:**
226
+ ```solidity
227
+ /// @notice Records funds being added to a project's balance.
228
+ /// @param projectId The ID of the project which funds are being added to.
229
+ /// @param token The token being added.
230
+ /// @param amount The amount added, as a fixed point number with the same decimals as the terminal.
231
+ /// @return surplus The new surplus after adding.
232
+ function recordAddedBalanceFor(
233
+ uint256 projectId,
234
+ address token,
235
+ uint256 amount
236
+ ) external override returns (uint256 surplus) {
237
+ ```
238
+
239
+ **Structs:**
240
+ ```solidity
241
+ /// @custom:member duration The number of seconds the ruleset lasts for. 0 means it never expires.
242
+ /// @custom:member weight How many tokens to mint per unit paid (18 decimals).
243
+ /// @custom:member weightCutPercent How much weight decays each cycle (9 decimals).
244
+ struct JBRulesetConfig {
245
+ uint32 duration;
246
+ uint112 weight;
247
+ uint32 weightCutPercent;
248
+ }
249
+ ```
250
+
251
+ **Mappings:**
252
+ ```solidity
253
+ /// @notice Context describing how a token is accounted for by a project.
254
+ /// @custom:param projectId The ID of the project.
255
+ /// @custom:param token The address of the token.
256
+ mapping(uint256 projectId => mapping(address token => JBAccountingContext)) internal _accountingContextForTokenOf;
257
+ ```
258
+
259
+ ## Numbers
260
+
261
+ Use underscores for thousands separators:
262
+
263
+ ```solidity
264
+ uint256 internal constant _FEE_HOLDING_SECONDS = 2_419_200; // 28 days
265
+ uint32 public constant MAX_WEIGHT_CUT_PERCENT = 1_000_000_000;
266
+ uint256 public constant MAX_RESERVED_PERCENT = 10_000;
267
+ ```
268
+
269
+ ## Function Calls
270
+
271
+ Use named parameters for readability when calling functions with 3+ arguments:
272
+
273
+ ```solidity
274
+ PERMISSIONS.hasPermission({
275
+ operator: sender,
276
+ account: account,
277
+ projectId: projectId,
278
+ permissionId: permissionId,
279
+ includeRoot: true,
280
+ includeWildcardProjectId: true
281
+ });
282
+ ```
283
+
284
+ ## Multiline Signatures
285
+
286
+ ```solidity
287
+ function recordCashOutFor(
288
+ address holder,
289
+ uint256 projectId,
290
+ uint256 cashOutCount,
291
+ JBAccountingContext calldata accountingContext
292
+ )
293
+ external
294
+ override
295
+ returns (
296
+ JBRuleset memory ruleset,
297
+ uint256 reclaimAmount,
298
+ JBCashOutHookSpecification[] memory hookSpecifications
299
+ )
300
+ {
301
+ ```
302
+
303
+ Modifiers and return types go on their own indented lines.
304
+
305
+ ## Error Handling
306
+
307
+ - Validate inputs with explicit `revert` + custom error
308
+ - Use `try-catch` only for external calls to untrusted contracts (hooks, fee processing)
309
+ - Always include relevant context in error parameters
310
+
311
+ ```solidity
312
+ // Direct validation
313
+ if (amount > limit) revert JBTerminalStore_InadequateControllerPayoutLimit(amount, limit);
314
+
315
+ // External call to untrusted hook
316
+ try hook.afterPayRecordedWith(context) {} catch (bytes memory reason) {
317
+ emit HookAfterPayReverted(hook, context, reason, _msgSender());
318
+ }
319
+ ```
320
+
321
+ ---
322
+
323
+ ## DevOps
324
+
325
+ ### foundry.toml
326
+
327
+ Standard config across all repos:
328
+
329
+ ```toml
330
+ [profile.default]
331
+ solc = '0.8.26'
332
+ evm_version = 'cancun'
333
+ optimizer_runs = 200
334
+ libs = ["node_modules", "lib"]
335
+ fs_permissions = [{ access = "read-write", path = "./"}]
336
+
337
+ [profile.ci_sizes]
338
+ optimizer_runs = 200
339
+
340
+ [fuzz]
341
+ runs = 4096
342
+
343
+ [invariant]
344
+ runs = 1024
345
+ depth = 100
346
+ fail_on_revert = false
347
+
348
+ [fmt]
349
+ number_underscore = "thousands"
350
+ multiline_func_header = "all"
351
+ wrap_comments = true
352
+ ```
353
+
354
+ **Variations:**
355
+ - `evm_version = 'cancun'` for repos using transient storage (buyback-hook, router-terminal, univ4-router)
356
+ - `via_ir = true` for repos hitting stack-too-deep (buyback-hook, banny-retail, univ4-lp-split-hook, deploy-all)
357
+ - `optimizer = false` only for deploy-all-v6 (stack-too-deep with optimization)
358
+
359
+ This repo uses the standard config with no deviations: `cancun`, `optimizer_runs=200`, no `via_ir`.
360
+
361
+ ### CI Workflows
362
+
363
+ Every repo has at minimum `test.yml` and `lint.yml`:
364
+
365
+ **test.yml:**
366
+ ```yaml
367
+ name: test
368
+ on:
369
+ pull_request:
370
+ branches: [main]
371
+ push:
372
+ branches: [main]
373
+ jobs:
374
+ forge-test:
375
+ runs-on: ubuntu-latest
376
+ steps:
377
+ - uses: actions/checkout@v4
378
+ with:
379
+ submodules: recursive
380
+ - uses: actions/setup-node@v4
381
+ with:
382
+ node-version: 22.4.x
383
+ - name: Install npm dependencies
384
+ run: npm install --omit=dev
385
+ - name: Install Foundry
386
+ uses: foundry-rs/foundry-toolchain@v1
387
+ - name: Run tests
388
+ run: forge test --fail-fast --summary --detailed --skip "*/script/**"
389
+ - name: Check contract sizes
390
+ run: FOUNDRY_PROFILE=ci_sizes forge build --sizes --skip "*/test/**" --skip "*/script/**" --skip SphinxUtils
391
+ ```
392
+
393
+ **lint.yml:**
394
+ ```yaml
395
+ name: lint
396
+ on:
397
+ pull_request:
398
+ branches: [main]
399
+ push:
400
+ branches: [main]
401
+ jobs:
402
+ forge-fmt:
403
+ runs-on: ubuntu-latest
404
+ steps:
405
+ - uses: actions/checkout@v4
406
+ - name: Install Foundry
407
+ uses: foundry-rs/foundry-toolchain@v1
408
+ - name: Check formatting
409
+ run: forge fmt --check
410
+ ```
411
+
412
+ ### package.json
413
+
414
+ ```json
415
+ {
416
+ "name": "@bananapus/721-hook-v6",
417
+ "version": "x.x.x",
418
+ "license": "MIT",
419
+ "repository": { "type": "git", "url": "git+https://github.com/Org/repo.git" },
420
+ "engines": { "node": ">=20.0.0" },
421
+ "scripts": {
422
+ "test": "forge test",
423
+ "coverage": "forge coverage --match-path \"./src/*.sol\" --report lcov --report summary"
424
+ },
425
+ "dependencies": { ... },
426
+ "devDependencies": {
427
+ "@sphinx-labs/plugins": "^0.33.2"
428
+ }
429
+ }
430
+ ```
431
+
432
+ **Scoping:** `@bananapus/` for Bananapus repos, `@rev-net/` for revnet, `@croptop/` for croptop, `@bannynet/` for banny, `@ballkidz/` for defifa.
433
+
434
+ ### remappings.txt
435
+
436
+ Every repo has a `remappings.txt`. Minimal content:
437
+
438
+ ```
439
+ @sphinx-labs/contracts/=lib/sphinx/packages/contracts/contracts/foundry
440
+ ```
441
+
442
+ Additional mappings as needed for repo-specific dependencies.
443
+
444
+ ### Formatting
445
+
446
+ Run `forge fmt` before committing. The `[fmt]` config in `foundry.toml` enforces:
447
+ - Thousands separators on numbers (`1_000_000`)
448
+ - Multiline function headers when multiple parameters
449
+ - Wrapped comments at reasonable width
450
+
451
+ CI checks formatting via `forge fmt --check`.
452
+
453
+ ### Branching
454
+
455
+ - `main` is the primary branch
456
+ - Feature branches for PRs
457
+ - All PRs trigger test + lint workflows
458
+ - Submodule checkout with `--recursive` in CI
459
+
460
+ ### Dependencies
461
+
462
+ - Solidity dependencies via npm (`node_modules/`)
463
+ - `forge-std` as a git submodule in `lib/`
464
+ - Sphinx plugins as a devDependency
465
+ - Cross-repo references use `file:../sibling-repo` in local development
466
+ - Published versions use semver ranges (`^0.0.x`) for npm
467
+
468
+ ### Contract Size Checks
469
+
470
+ CI runs `FOUNDRY_PROFILE=ci_sizes forge build --sizes` to catch contracts approaching the 24KB limit. The `ci_sizes` profile uses `optimizer_runs = 200` for realistic size measurement even when the default profile has different optimizer settings.
@@ -167,7 +167,7 @@ mapping(address hook => mapping(uint256 tierId => JBStored721Tier)) internal _st
167
167
 
168
168
 
169
169
  ### _tierIdAfter
170
- Returns the ID of the tier which comes after the provided tier ID (sorted by price).
170
+ Returns the ID of the tier which comes after the provided tier ID (sorted by category).
171
171
 
172
172
  *If empty, assume the next tier ID should come after.*
173
173
 
@@ -386,7 +386,7 @@ function tiersOf(
386
386
  |`hook`|`address`|The 721 contract to get the tiers of.|
387
387
  |`categories`|`uint256[]`|An array tier categories to get tiers from. Send an empty array to get all categories.|
388
388
  |`includeResolvedUri`|`bool`|If set to `true`, if the contract has a token URI resolver, its content will be resolved and included.|
389
- |`startingId`|`uint256`|The ID of the first tier to get (sorted by price). Send 0 to get all active tiers.|
389
+ |`startingId`|`uint256`|The ID of the first tier to get (sorted by category). Send 0 to get all active tiers.|
390
390
  |`size`|`uint256`|The number of tiers to include.|
391
391
 
392
392
  **Returns**
@@ -561,7 +561,7 @@ function totalCashOutWeight(address hook) public view override returns (uint256
561
561
 
562
562
  ### _firstSortedTierIdOf
563
563
 
564
- Get the first tier ID from an 721 contract (when sorted by price) within a provided category.
564
+ Get the first tier ID from an 721 contract (when sorted by category) within a provided category.
565
565
 
566
566
 
567
567
  ```solidity
@@ -669,7 +669,7 @@ function _isTierRemovedWithRefresh(
669
669
 
670
670
  ### _lastSortedTierIdOf
671
671
 
672
- The last sorted tier ID from an 721 contract (when sorted by price).
672
+ The last sorted tier ID from an 721 contract (when sorted by category).
673
673
 
674
674
 
675
675
  ```solidity
@@ -690,7 +690,7 @@ function _lastSortedTierIdOf(address hook) internal view returns (uint256 id);
690
690
 
691
691
  ### _nextSortedTierIdOf
692
692
 
693
- Get the tier ID which comes after the provided one when sorted by price.
693
+ Get the tier ID which comes after the provided one when sorted by category.
694
694
 
695
695
 
696
696
  ```solidity
@@ -3,7 +3,7 @@
3
3
 
4
4
  Config to initialize a `JB721TiersHook` with tiers and price data.
5
5
 
6
- *The `tiers` must be sorted by price (from least to greatest).*
6
+ *The `tiers` must be sorted by category (from least to greatest).*
7
7
 
8
8
  **Notes:**
9
9
  - member: tiers The tiers to initialize the hook with.
package/foundry.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [profile.default]
2
2
  solc = '0.8.26'
3
- evm_version = 'paris'
3
+ evm_version = 'cancun'
4
4
  optimizer_runs = 200
5
5
  libs = ["node_modules", "lib"]
6
6
  fs_permissions = [{ access = "read-write", path = "./"}]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bananapus/721-hook-v6",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,10 +17,10 @@
17
17
  "artifacts": "source ./.env && npx sphinx artifacts --org-id 'ea165b21-7cdc-4d7b-be59-ecdd4c26bee4' --project-name 'nana-721-hook-v6'"
18
18
  },
19
19
  "dependencies": {
20
- "@bananapus/address-registry-v6": "^0.0.4",
21
- "@bananapus/core-v6": "^0.0.10",
22
- "@bananapus/ownable-v6": "^0.0.6",
23
- "@bananapus/permission-ids-v6": "^0.0.5",
20
+ "@bananapus/address-registry-v6": "^0.0.6",
21
+ "@bananapus/core-v6": "^0.0.12",
22
+ "@bananapus/ownable-v6": "^0.0.7",
23
+ "@bananapus/permission-ids-v6": "^0.0.6",
24
24
  "@openzeppelin/contracts": "5.2.0",
25
25
  "@prb/math": "^4.1.0",
26
26
  "solady": "^0.1.8"
@@ -74,13 +74,13 @@ contract DeployScript is Script, Sphinx {
74
74
  (address _hook, bool _hookIsDeployed) = _isDeployed(
75
75
  HOOK_SALT,
76
76
  type(JB721TiersHook).creationCode,
77
- abi.encode(core.directory, core.permissions, core.rulesets, store, TRUSTED_FORWARDER)
77
+ abi.encode(core.directory, core.permissions, core.rulesets, store, core.splits, TRUSTED_FORWARDER)
78
78
  );
79
79
 
80
80
  // Deploy it if it has not been deployed yet.
81
81
  hook = !_hookIsDeployed
82
82
  ? new JB721TiersHook{salt: HOOK_SALT}(
83
- core.directory, core.permissions, core.rulesets, store, TRUSTED_FORWARDER
83
+ core.directory, core.permissions, core.rulesets, store, core.splits, TRUSTED_FORWARDER
84
84
  )
85
85
  : JB721TiersHook(_hook);
86
86
  }