# Style Guide 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. ## File organization ``` src/ ├── Contract.sol # Main contracts in root ├── abstract/ # Base contracts (JBPermissioned, JBControlled) ├── enums/ # One enum per file ├── interfaces/ # One interface per file, prefixed with I ├── libraries/ # Pure/view logic, prefixed with JB ├── periphery/ # Utility contracts (deadlines, price feeds) └── structs/ # One struct per file, prefixed with JB ``` One contract/interface/struct/enum per file. Name the file after the type it contains. ## Pragma versions ```solidity // Contracts — pin to exact version pragma solidity 0.8.28; // Interfaces, structs, enums — caret for forward compatibility pragma solidity ^0.8.0; // Libraries — pin to exact version like contracts pragma solidity 0.8.28; ``` ## Imports Named imports only. Grouped by source, alphabetized within each group: ```solidity // External packages (alphabetized) import {ERC2771Context} from "@openzeppelin/contracts/metatx/ERC2771Context.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {mulDiv} from "@prb/math/src/Common.sol"; // Local: abstract contracts import {JBPermissioned} from "./abstract/JBPermissioned.sol"; // Local: interfaces (alphabetized) import {IJBController} from "./interfaces/IJBController.sol"; import {IJBDirectory} from "./interfaces/IJBDirectory.sol"; import {IJBMultiTerminal} from "./interfaces/IJBMultiTerminal.sol"; // Local: libraries (alphabetized) import {JBConstants} from "./libraries/JBConstants.sol"; import {JBFees} from "./libraries/JBFees.sol"; // Local: structs (alphabetized) import {JBAccountingContext} from "./structs/JBAccountingContext.sol"; import {JBSplit} from "./structs/JBSplit.sol"; ``` ## Contract structure Section banners divide the contract into a fixed ordering. Every contract with 50+ lines uses these banners: ```solidity /// @notice One-line description. contract JBExample is JBPermissioned, IJBExample { // A library that does X. using SomeLib for SomeType; //*********************************************************************// // --------------------------- custom errors ------------------------- // //*********************************************************************// error JBExample_SomethingFailed(uint256 amount); //*********************************************************************// // ------------------------- public constants ------------------------ // //*********************************************************************// uint256 public constant override FEE = 25; //*********************************************************************// // ----------------------- internal constants ------------------------ // //*********************************************************************// uint256 internal constant _FEE_BENEFICIARY_PROJECT_ID = 1; //*********************************************************************// // ------------------------ private constants ------------------------ // //*********************************************************************// //*********************************************************************// // --------------- public immutable stored properties ---------------- // //*********************************************************************// IJBDirectory public immutable override DIRECTORY; //*********************************************************************// // -------------- internal immutable stored properties -------------- // //*********************************************************************// //*********************************************************************// // --------------------- public stored properties -------------------- // //*********************************************************************// //*********************************************************************// // -------------------- internal stored properties ------------------- // //*********************************************************************// //*********************************************************************// // -------------------- private stored properties -------------------- // //*********************************************************************// //*********************************************************************// // ------------------- transient stored properties ------------------- // //*********************************************************************// //*********************************************************************// // -------------------------- constructor ---------------------------- // //*********************************************************************// //*********************************************************************// // ---------------------------- modifiers ---------------------------- // //*********************************************************************// //*********************************************************************// // ------------------------- receive / fallback ---------------------- // //*********************************************************************// //*********************************************************************// // ---------------------- external transactions ---------------------- // //*********************************************************************// //*********************************************************************// // ----------------------- external views ---------------------------- // //*********************************************************************// //*********************************************************************// // -------------------------- public views --------------------------- // //*********************************************************************// //*********************************************************************// // ----------------------- public transactions ----------------------- // //*********************************************************************// //*********************************************************************// // ---------------------- internal transactions ---------------------- // //*********************************************************************// //*********************************************************************// // ----------------------- internal helpers -------------------------- // //*********************************************************************// //*********************************************************************// // ----------------------- internal views ---------------------------- // //*********************************************************************// //*********************************************************************// // ----------------------- private helpers --------------------------- // //*********************************************************************// } ``` **Section order:** 1. Custom errors 2. Public constants 3. Internal constants 4. Private constants 5. Public immutable stored properties 6. Internal immutable stored properties 7. Public stored properties 8. Internal stored properties 9. Private stored properties 10. Transient stored properties 11. Constructor 12. Modifiers 13. Receive / fallback 14. External transactions 15. External views 16. Public views 17. Public transactions 18. Internal transactions 19. Internal helpers 20. Internal views 21. Private helpers Use these additional section labels where they better match the contents of the block: - `internal functions` is accepted as equivalent to `internal helpers` - `events` and `structs` are acceptable in specialized contracts that define them explicitly Functions are alphabetized within each section. ## Interface structure ```solidity /// @notice One-line description. interface IJBExample is IJBBase { // Events (with full NatSpec) /// @notice Emitted when X happens. /// @param projectId The ID of the project. /// @param amount The amount transferred. event SomethingHappened(uint256 indexed projectId, uint256 amount); // Views (alphabetized) /// @notice The directory of terminals and controllers. function DIRECTORY() external view returns (IJBDirectory); // State-changing functions (alphabetized) /// @notice Does the thing. /// @param projectId The ID of the project. /// @return result The result. function doThing(uint256 projectId) external returns (uint256 result); } ``` **Rules:** - Events first, then views, then state-changing functions - No custom errors in interfaces — errors belong in the implementing contract - Full NatSpec on every event, function, and parameter - Alphabetized within each group ## Naming | Thing | Convention | Example | |-------|-----------|---------| | Contract | PascalCase | `JBMultiTerminal` | | Interface | `I` + PascalCase | `IJBMultiTerminal` | | Library | PascalCase | `JBCashOuts` | | Struct | PascalCase | `JBRulesetConfig` | | Enum | PascalCase | `JBApprovalStatus` | | Enum value | PascalCase | `ApprovalExpected` | | Error | `ContractName_ErrorName` | `JBMultiTerminal_FeeTerminalNotFound` | | Public constant | `ALL_CAPS` | `FEE`, `MAX_FEE` | | Internal constant | `_ALL_CAPS` | `_FEE_HOLDING_SECONDS` | | Public immutable | `ALL_CAPS` | `DIRECTORY`, `PERMISSIONS` | | Public/external function | `camelCase` | `cashOutTokensOf` | | Internal/private function | `_camelCase` | `_processFee` | | Internal storage | `_camelCase` | `_accountingContextForTokenOf` | | Function parameter | `camelCase` (no underscores) | `projectId`, `cashOutCount` | ## NatSpec Every contract, interface, library, error, event, function, return value, state variable, mapping, and struct member carries complete NatSpec. NatSpec describes the current behavior as the only behavior (see Comments). Required tags by member: - **Contract / interface / library** — `@notice` (what it is and does). Add `@dev` for cross-cutting notes such as storage-layout choices, invariants it upholds, or integration assumptions. - **Error** — `@notice` stating exactly when it reverts and the reason the guard exists. - **Event** — `@notice` (when it's emitted) and a `@param` for every field. - **Function** — `@notice` (what it does, user-facing), a `@param` for every parameter, and a named `@return` for every return value. Add `@dev` whenever a non-obvious mechanic, ordering requirement, edge case, rounding choice, permission rule, or invariant explains the WHY behind the behavior. - **State variable** — `@notice` (what it holds). Add `@dev` for how/when it is maintained or any invariant it preserves. For a mapping, also a `@custom:param` for every key, outer to inner. - **Struct** — `@custom:member` for every field. **Contracts:** ```solidity /// @notice One-line description of what the contract does. contract JBExample is IJBExample { ``` **Errors:** ```solidity /// @notice Thrown when the caller is not the project's controller, so only the controller can record balances. error JBExample_Unauthorized(address caller); ``` **Events:** ```solidity /// @notice Emitted when funds are added to a project's balance. /// @param projectId The ID of the project funds were added to. /// @param amount The amount added. event AddToBalance(uint256 indexed projectId, uint256 amount); ``` **Functions:** ```solidity /// @notice Records funds being added to a project's balance. /// @dev Reverts if the project has no accounting context for the token, so the token must be registered first. /// @param projectId The ID of the project which funds are being added to. /// @param token The token being added. /// @param amount The amount added, as a fixed point number with the same decimals as the terminal. /// @return surplus The new surplus after adding. function recordAddedBalanceFor( uint256 projectId, address token, uint256 amount ) external override returns (uint256 surplus) { ``` **State variables and mappings:** ```solidity /// @notice How many NFTs an address owns from a hook, totaled across all tiers. /// @dev Maintained as a running aggregate in `recordTransferForTier`, so this read is O(1) instead of O(tiers). /// @custom:param hook The 721 contract to check. /// @custom:param owner The address to get the balance of. mapping(address hook => mapping(address owner => uint256)) public override balanceOf; ``` **Structs:** ```solidity /// @custom:member duration The number of seconds the ruleset lasts for. 0 means it never expires. /// @custom:member weight How many tokens to mint per unit paid (18 decimals). /// @custom:member weightCutPercent How much weight decays each cycle (9 decimals). struct JBRulesetConfig { uint32 duration; uint112 weight; uint32 weightCutPercent; } ``` ## Comments Every non-trivial statement or block carries an inline `//` comment that explains WHY it exists — the reason, invariant, edge case, ordering requirement, or guarantee it provides — in plain English. Comment the intent, not the literal syntax: `// increment i` adds nothing; `// advance the index before the external call so a re-entrant call cannot replay this entry` does. Write every comment and NatSpec as if the current implementation is the first and the last: - No references to other implementations in time: no "previously", "now", "used to", "changed to", "legacy", "old/new approach", "v1/v2", "temporary", or "for backwards compatibility". - No references to audits, audit tools, reviewers, or finding/issue codes. The code stands on its own reasoning; describe the mechanism and its rationale directly. - Describe a behavior by what it guarantees, not by the history of how it came to be. A `// forge-lint: disable-next-line()` directive sits on its own line directly above the line it applies to — never merged into a prose comment, or the formatter reflows it into the prose and it silently disables nothing. ## Numbers Use underscores for thousands separators: ```solidity uint256 internal constant _FEE_HOLDING_SECONDS = 2_419_200; // 28 days uint32 public constant MAX_WEIGHT_CUT_PERCENT = 1_000_000_000; uint256 public constant MAX_RESERVED_PERCENT = 10_000; ``` ## Function calls Use named arguments for all function calls with 2 or more arguments — in both `src/` and `script/`: ```solidity // Good — named arguments token.mint({account: beneficiary, amount: count}); _transferOwnership({newOwner: address(0), projectId: 0}); PERMISSIONS.hasPermission({ operator: sender, account: account, projectId: projectId, permissionId: permissionId, includeRoot: true, includeWildcardProjectId: true }); // Bad — positional arguments with 2+ args token.mint(beneficiary, count); _transferOwnership(address(0), 0); ``` Single-argument calls use positional style: `_burn(amount)`. This also applies to constructor calls, struct literals, and inherited/library calls (e.g., OZ `_mint`, `_safeMint`, `safeTransfer`, `allowance`, `Clones.cloneDeterministic`). Named argument keys must use **camelCase** — never underscores. If a function's parameter names use underscores, rename them to camelCase first. ## Multiline signatures ```solidity function recordCashOutFor( address holder, uint256 projectId, uint256 cashOutCount, JBAccountingContext calldata accountingContext ) external override returns ( JBRuleset memory ruleset, uint256 reclaimAmount, JBCashOutHookSpecification[] memory hookSpecifications ) { ``` Modifiers and return types go on their own indented lines. ## Error handling - Validate inputs with explicit `revert` + custom error - Use `try-catch` only for external calls to untrusted contracts (hooks, fee processing) - Always include relevant context in error parameters ```solidity // Direct validation // Cap to remaining payout limit instead of reverting if (amount > remainingPayoutLimit) amount = remainingPayoutLimit; // External call to untrusted hook try hook.afterPayRecordedWith(context) {} catch (bytes memory reason) { emit HookAfterPayReverted(hook, context, reason, _msgSender()); } ``` --- ## DevOps ### foundry.toml Standard config across all repos: ```toml [profile.default] solc = '0.8.28' evm_version = 'cancun' optimizer_runs = 200 libs = ["node_modules", "lib"] fs_permissions = [{ access = "read-write", path = "./"}] [fuzz] runs = 4096 [invariant] runs = 1024 depth = 100 fail_on_revert = false [fmt] number_underscore = "thousands" multiline_func_header = "all" wrap_comments = true ``` **Optional sections (add only when needed):** - `[rpc_endpoints]` — repos with fork tests. Maps named endpoints to env vars (e.g. `ethereum = "${RPC_ETHEREUM_MAINNET}"`). - `[profile.ci_sizes]` — only when CI needs different optimizer settings than defaults for the size check step (e.g. `optimizer_runs = 200` when the default profile uses a lower value). **Common variations:** - `via_ir = true` when hitting stack-too-deep - `optimizer = false` when optimization causes stack-too-deep - `optimizer_runs` reduced when deep struct nesting causes stack-too-deep at 200 runs ### CI workflows Every repo has at minimum `test.yml` and `lint.yml`: **test.yml:** ```yaml name: test on: pull_request: branches: [main] push: branches: [main] jobs: forge-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: recursive - uses: actions/setup-node@v4 with: node-version: 25.9.0 - name: Install npm dependencies run: npm install --omit=dev - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 - name: Run tests run: forge test --deny notes --fail-fast --summary --detailed --skip "*/script/**" env: RPC_ETHEREUM_MAINNET: ${{ secrets.RPC_ETHEREUM_MAINNET }} - name: Check contract sizes run: forge build --deny notes --sizes --skip "*/test/**" --skip "*/script/**" --skip SphinxUtils ``` **lint.yml:** ```yaml name: lint on: pull_request: branches: [main] push: branches: [main] jobs: forge-fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 - name: Check formatting run: forge fmt --check ``` **Static review workflow** (repos with `src/` contracts only): Keep repo-local static review automation current with the package's runtime surface. At minimum, CI should run formatting, linting, and build checks with `--deny notes`. Repos that only contain deployment scripts can rely on the shared formatting and lint jobs unless they add runtime contracts. ### package.json ```json { "name": "@bananapus/package-name-v6", "version": "x.x.x", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/Org/repo.git" }, "engines": { "node": ">=20.0.0" }, "scripts": { "test": "forge test", "coverage": "forge coverage --match-path \"./src/*.sol\" --report lcov --report summary" }, "dependencies": { ... }, "devDependencies": { "@sphinx-labs/plugins": "0.33.3" } } ``` **Scoping:** `@bananapus/` for Bananapus repos, `@rev-net/` for revnet, `@croptop/` for croptop, `@bannynet/` for banny, `@ballkidz/` for defifa. ### remappings.txt Every repo has a `remappings.txt` as the **single source of truth** for import remappings. Never add remappings to `foundry.toml`. **Principle:** Import paths in Solidity source must match npm package names exactly. With `libs = ["node_modules", "lib"]`, Foundry auto-resolves `@scope/package/path/File.sol` → `node_modules/@scope/package/path/File.sol`. No remapping needed for packages installed as real directories. **Note:** Auto-resolution does **not** work for symlinked packages (e.g. npm workspace links). Workspace repos like `deploy-all-v6` and `nana-cli-v6` need explicit `@scope/package/=node_modules/@scope/package/` remappings for each symlinked dependency. **Minimal content** (most repos): ``` forge-std/=lib/forge-std/src/ ``` Only add extra remappings for: - **`forge-std`** — always needed (git submodule with `src/` subdirectory) - **Repo-specific `lib/` submodules** that have no npm package (e.g., `hookmate/=lib/hookmate/src/`) - **Symlinked npm packages** — need explicit `@scope/package/=node_modules/@scope/package/` entries - **Nested transitive deps** — e.g., `@chainlink/contracts-ccip/` nested inside `@bananapus/suckers-v6/node_modules/` **Never add remappings for:** - npm packages that match their import path and are installed as real directories — they auto-resolve - Short-form aliases (e.g., `@bananapus/core/` → `@bananapus/core-v6/src/`) — fix the import instead - Packages available via npm that are also git submodules — remove the submodule, use npm **Import path convention:** | Package | Import path | Resolves to | |---------|------------|-------------| | `@bananapus/core-v6` | `@bananapus/core-v6/src/libraries/JBConstants.sol` | `node_modules/@bananapus/core-v6/src/...` | | `@openzeppelin/contracts` | `@openzeppelin/contracts/token/ERC20/IERC20.sol` | `node_modules/@openzeppelin/contracts/...` | | `@uniswap/v4-core` | `@uniswap/v4-core/src/interfaces/IPoolManager.sol` | `node_modules/@uniswap/v4-core/src/...` | ### Linting The committed source builds, lints, and tests with zero errors, warnings, and notes. CI runs `forge build --deny notes --sizes ...` and `forge test --deny notes ...`; `--deny notes` escalates any solc warning or solar lint note to a hard failure, so anything less than clean fails CI. Do not silence a real issue — fix it. The only acceptable suppression is a justified, standalone `// forge-lint: disable-next-line()` for a rule that is genuinely inapplicable (for example a multi-day timestamp comparison flagged by `block-timestamp`). Solar (Foundry's built-in linter) runs automatically during `forge build`. It scans all `.sol` files in `libs` directories, including `node_modules`. All test helpers use relative imports (e.g. `../../src/structs/JBRuleset.sol`), not bare `src/` imports, so solar can resolve paths when the helper is consumed via npm in downstream repos. ### Fork tests Fork tests use named RPC endpoints defined in `[rpc_endpoints]` of `foundry.toml`. No skip guards — fork tests should hard-fail if the RPC endpoint is unavailable, making CI failures explicit. ```solidity function setUp() public { vm.createSelectFork("ethereum"); // ... setup code } ``` The endpoint name (e.g. `"ethereum"`) maps to an env var via `foundry.toml`: ```toml [rpc_endpoints] ethereum = "${RPC_ETHEREUM_MAINNET}" ``` For multi-chain fork tests, add all needed endpoints. ### Formatting Run `forge fmt` before committing. The `[fmt]` config in `foundry.toml` enforces: - Thousands separators on numbers (`1_000_000`) - Multiline function headers when multiple parameters - Wrapped comments at reasonable width CI checks formatting via `forge fmt --check`. ### Branching - `main` is the primary branch - Feature branches for PRs - All PRs trigger test + lint workflows - Submodule checkout with `--recursive` in CI ### Dependencies - Solidity dependencies via npm (`node_modules/`) - `forge-std` as a git submodule in `lib/` - Sphinx plugins as a devDependency - Cross-repo references use `file:../sibling-repo` in local development - Published npm dependencies are pinned to exact versions unless a repo intentionally tracks a compatible release range and the lockfile pins CI installs - GitHub dependency refs are pinned to a commit and used only when the needed Solidity sources are not published to npm ### Contract size checks CI runs `forge build --sizes` to catch contracts approaching the 24KB limit. When the repo's default `optimizer_runs` differs from what you want for size checking, use `FOUNDRY_PROFILE=ci_sizes forge build --sizes` with a `[profile.ci_sizes]` section in `foundry.toml`.