Juicebox V5 Design Patterns
Proven patterns for common use cases using native Juicebox mechanics. Always prefer configuration over custom contracts.
Golden Rule
Before writing custom code, ask: "Can this be achieved with payout limits, surplus allowance, splits, and cycling rulesets?"
Pattern 1: Vesting via Native Mechanics
Use case: Release funds to a beneficiary over time (e.g., team vesting, milestone-based releases)
Solution: Use cycling rulesets with payout limits
How It Works
| Mechanism |
Behavior |
Use For |
| Payout Limit |
Resets each cycle |
Recurring distributions (vesting) |
| Surplus Allowance |
One-time per ruleset |
Discretionary treasury access |
| Cycle Duration |
Determines distribution frequency |
Monthly = 30 days |
Configuration
JBRulesetConfig({
duration: 30 days, // Monthly cycles
// ... other config
fundAccessLimitGroups: [
JBFundAccessLimitGroup({
terminal: address(TERMINAL),
token: JBConstants.NATIVE_TOKEN,
payoutLimits: [
JBCurrencyAmount({
amount: 6.67 ether, // Monthly vesting amount
currency: nativeCurrency
})
],
surplusAllowances: [
JBCurrencyAmount({
amount: 20 ether, // One-time treasury (doesn't reset)
currency: nativeCurrency
})
]
})
]
});
Capital Flow
Month 0: Balance = 100 ETH
Surplus = Balance - Payout Limit = 93.33 ETH (redeemable)
Month 1: Team calls sendPayoutsOf() → receives 6.67 ETH
Balance = 93.33 ETH
Surplus = 86.67 ETH
Month 12: All vested, Balance = 20 ETH (treasury allowance)
Key Insight
- Payout limits protect vesting funds from redemption
- Surplus = unvested funds available for token holder cash outs
- No custom contracts needed
Pattern 2: NFT-Gated Treasury
Use case: Sell NFTs, allow holders to redeem against treasury surplus
Solution: Use nana-721-hook-v5 with native cash outs
Configuration
- Deploy project with
JB721TiersHookProjectDeployer
- Configure 721 hook as data hook for pay AND cash out
- Set
cashOutTaxRate: 0 for full redemption value
JBRulesetMetadata({
cashOutTaxRate: 0, // Full redemption
useDataHookForPay: true, // 721 hook mints NFTs
useDataHookForCashOut: true, // 721 hook handles burns
dataHook: address(0), // Set by deployer
// ...
});
How Cash Outs Work
- User calls
cashOutTokensOf() on terminal
- 721 hook intercepts, calculates:
(NFT price / total prices) × surplus
- NFT is burned, ETH sent to user
No custom cash out hook needed - the 721 hook handles everything.
Pattern 3: Governance-Minimal Treasury
Use case: Immutable treasury with no admin controls
Solution: Transfer ownership to burn address after setup
Configuration
// 1. Deploy project with restrictive metadata
JBRulesetMetadata({
allowOwnerMinting: false,
allowTerminalMigration: false,
allowSetTerminals: false,
allowSetController: false,
allowAddAccountingContext: false,
allowAddPriceFeed: false,
// ...
});
// 2. After deployment, burn ownership
PROJECTS.transferFrom(deployer, 0x000000000000000000000000000000000000dEaD, projectId);
What This Achieves
- No one can change rulesets
- No one can add/remove terminals
- No one can mint tokens arbitrarily
- Payouts/cash outs work as configured forever
Pattern 4: Split Recipients Without Custom Hooks
Use case: Distribute payouts to multiple addresses
Solution: Use native splits with direct beneficiaries
Configuration
JBSplit[] memory splits = new JBSplit[](3);
splits[0] = JBSplit({
percent: 500_000_000, // 50%
beneficiary: payable(team1),
projectId: 0,
hook: IJBSplitHook(address(0)), // No hook needed!
// ...
});
splits[1] = JBSplit({
percent: 300_000_000, // 30%
beneficiary: payable(team2),
// ...
});
splits[2] = JBSplit({
percent: 200_000_000, // 20%
beneficiary: payable(treasury),
// ...
});
Only use split hooks when you need custom logic (e.g., swapping tokens, adding to LP).
Pattern 5: NFT + Vesting Combined
Use case: Sell NFTs with funds vesting to team over time, holders can exit by burning
Solution: Combine patterns 1 + 2
Architecture
┌─────────────────────────────────────────────────┐
│ JB Project with 721 Hook │
│ │
│ • NFT tier: 100 supply, 1 ETH each │
│ • Payout limit: 6.67 ETH/month (vesting) │
│ • Surplus allowance: 20 ETH (treasury) │
│ • Cash out tax: 0% │
│ • Owner: burn address │
│ │
│ Treasury Flow: │
│ ├── Month 0: 80 ETH surplus (all unvested) │
│ ├── Month 6: 40 ETH surplus │
│ └── Month 12: 0 ETH surplus (fully vested) │
│ │
│ NFT Holder: Can burn anytime for pro-rata │
│ share of current surplus │
└─────────────────────────────────────────────────┘
Complete Example
See the Drip x Juicebox deployment script for a full implementation:
- 100 NFTs at 1 ETH each
- 20 ETH immediate treasury (surplus allowance)
- 80 ETH vests over 12 months (payout limits)
- NFT holders can burn to exit at any time
- Zero custom contracts
Pattern 6: Custom NFT Content via Resolver
Use case: NFT project with custom artwork, composable assets, or dynamic metadata while using 721-hook off-the-shelf
Solution: Implement IJB721TokenUriResolver for custom content, use standard 721-hook for treasury mechanics
Why This Pattern?
The 721-hook handles all the hard stuff:
- Payment processing and tier selection
- Token minting and supply tracking
- Cash out weight calculations
- Reserved token mechanics
You only need custom code for content generation (artwork, metadata, composability).
Architecture
┌─────────────────────────────────────────────────────────────┐
│ Standard 721-Hook (off-the-shelf) │
│ ├── Handles payments, minting, cash outs │
│ ├── Manages tier supply and pricing │
│ └── Calls tokenUriResolver.tokenUriOf() for metadata │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Custom TokenUriResolver (your code) │ │
│ │ ├── Implements IJB721TokenUriResolver │ │
│ │ ├── tokenUriOf() → dynamic SVG/metadata │ │
│ │ └── Custom behaviors (composability, decoration) │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Interface
interface IJB721TokenUriResolver {
/// @notice Get the token URI for a given token.
/// @param hook The 721 hook address.
/// @param tokenId The token ID.
/// @return The token URI (typically base64-encoded JSON with SVG).
function tokenUriOf(address hook, uint256 tokenId)
external view returns (string memory);
}
Basic Resolver Implementation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IJB721TokenUriResolver} from "@bananapus/721-hook/src/interfaces/IJB721TokenUriResolver.sol";
import {IJB721TiersHook} from "@bananapus/721-hook/src/interfaces/IJB721TiersHook.sol";
contract CustomTokenUriResolver is IJB721TokenUriResolver {
/// @notice Generate token URI with custom artwork/metadata.
function tokenUriOf(address hook, uint256 tokenId)
external view override returns (string memory)
{
// Get tier info from the hook
IJB721TiersHook tiersHook = IJB721TiersHook(hook);
uint256 tierId = tiersHook.tierIdOfToken(tokenId);
// Generate your custom metadata/artwork
string memory name = _getNameForTier(tierId);
string memory svg = _generateSvgForToken(tokenId, tierId);
// Return base64-encoded JSON
return string(abi.encodePacked(
"data:application/json;base64,",
Base64.encode(bytes(abi.encodePacked(
'{"name":"', name, '",',
'"image":"data:image/svg+xml;base64,', Base64.encode(bytes(svg)), '"}'
)))
));
}
function _getNameForTier(uint256 tierId) internal view returns (string memory) {
// Your tier naming logic
}
function _generateSvgForToken(uint256 tokenId, uint256 tierId) internal view returns (string memory) {
// Your SVG generation logic
}
}
Advanced: Composable NFTs (Banny Pattern)
For composable NFTs where items can be attached to base tokens:
contract ComposableTokenUriResolver is IJB721TokenUriResolver {
// Track which items are attached to which base tokens
mapping(address hook => mapping(uint256 baseTokenId => uint256[])) public attachedItems;
// Prevent changes for a duration (e.g., 7 days)
mapping(address hook => mapping(uint256 tokenId => uint256)) public lockedUntil;
/// @notice Attach items to a base token.
function decorateWith(
address hook,
uint256 baseTokenId,
uint256[] calldata itemIds
) external {
// Verify caller owns both base token and items
require(IJB721TiersHook(hook).ownerOf(baseTokenId) == msg.sender);
require(lockedUntil[hook][baseTokenId] < block.timestamp, "LOCKED");
for (uint256 i; i < itemIds.length; i++) {
require(IJB721TiersHook(hook).ownerOf(itemIds[i]) == msg.sender);
// Transfer item to this contract (escrow while attached)
IJB721TiersHook(hook).transferFrom(msg.sender, address(this), itemIds[i]);
}
attachedItems[hook][baseTokenId] = itemIds;
}
/// @notice Lock outfit changes for 7 days.
function lockChangesFor(address hook, uint256 baseTokenId) external {
require(IJB721TiersHook(hook).ownerOf(baseTokenId) == msg.sender);
lockedUntil[hook][baseTokenId] = block.timestamp + 7 days;
}
/// @notice Generate composite SVG from base + attached items.
function tokenUriOf(address hook, uint256 tokenId) external view override returns (string memory) {
uint256[] memory items = attachedItems[hook][tokenId];
// Generate layered SVG combining base + all attached items
string memory svg = _generateCompositeSvg(hook, tokenId, items);
return _encodeAsDataUri(svg);
}
}
Deployment Integration
// 1. Deploy your custom resolver
CustomTokenUriResolver resolver = new CustomTokenUriResolver();
// 2. Configure 721 hook with resolver
REVDeploy721TiersHookConfig memory hookConfig = REVDeploy721TiersHookConfig({
baseline721HookConfiguration: JBDeploy721TiersHookConfig({
// ... tier configs
tokenUriResolver: IJB721TokenUriResolver(address(resolver)),
// ...
}),
// ...
});
// 3. Deploy project/revnet with hook config
deployer.deployWith721sFor(projectId, hookConfig, ...);
When to Use This Pattern
| Requirement |
Use Resolver? |
| Static tier images (IPFS) |
No - use encodedIPFSUri in tier config |
| Dynamic/generative art |
Yes |
| Composable/layered NFTs |
Yes |
| On-chain SVG storage |
Yes |
| Token-specific metadata |
Yes |
| Standard ERC-721 metadata |
No - use default |
Reference Implementation
banny-retail-v5: https://github.com/mejango/banny-retail-v5
Banny721TokenUriResolver.sol - Composable SVG NFTs with outfit decoration
Deploy.s.sol - Deployment with custom resolver
Drop1.s.sol - Adding tiers with custom categories
Key features demonstrated:
- On-chain SVG storage with hash verification
- Composable outfits (attach items to base Banny)
- Outfit locking (7-day freeze)
- Category-based slot system
- Multi-chain deployment via Revnet
Pattern 7: Prediction Games with Dynamic Cash Out Weights
Use case: Games where outcomes determine payout distribution (prediction markets, fantasy sports, competitions)
Solution: Extend 721-hook with custom delegate, use on-chain governance for outcome resolution
Why This Pattern Requires Extending 721-Hook
Unlike Pattern 6 (resolver-only), prediction games need to change core treasury mechanics:
| Requirement |
Why Resolver Isn't Enough |
| Dynamic cash out weights |
Cash out calculation is in the hook, not resolver |
| First-owner tracking |
Rewards original minters, not current holders |
| Phase enforcement |
Different rules per game phase |
| Governance integration |
Scorecard ratification triggers weight changes |
Architecture
┌─────────────────────────────────────────────────────────────┐
│ Game Lifecycle (via Juicebox Rulesets) │
│ │
│ COUNTDOWN → MINT → REFUND → SCORING → COMPLETE │
│ │ │ │ │ │ │
│ │ Players Early Holders Winners │
│ │ mint exit vote on cash out │
│ │ NFTs OK scorecard winnings │
│ │
├─────────────────────────────────────────────────────────────┤
│ Custom Delegate (extends JB721Hook) │
│ ├── Tracks first owners (for fair reward distribution) │
│ ├── Phase-aware cash out logic │
│ ├── Dynamic tier weights (set by governor) │
│ └── Enforces phase restrictions │
│ │
├─────────────────────────────────────────────────────────────┤
│ Governor Contract │
│ ├── NFT holders propose scorecards │
│ ├── Tier-weighted voting (own 25% of tier = 25% of votes) │
│ ├── 50% quorum required for ratification │
│ └── Ratification sets tier cash out weights │
└─────────────────────────────────────────────────────────────┘
Game Phases
enum DefifaGamePhase {
COUNTDOWN, // Game announced, no minting yet
MINT, // Players can mint NFTs (pick teams)
REFUND, // Early exit window (get mint cost back)
SCORING, // Game over, holders vote on scorecard
COMPLETE, // Scorecard ratified, winners cash out
NO_CONTEST_INEVITABLE, // Not enough participation
NO_CONTEST // Game cancelled, full refunds
}
Dynamic Cash Out Weights
Standard 721-hook: cashOutWeight = tierPrice (fixed)
Defifa pattern: cashOutWeight = scorecardWeight[tierId] (dynamic)
// Total weight is 1e18 (100%), distributed among tiers by scorecard
uint256 constant TOTAL_CASH_OUT_WEIGHT = 1e18;
struct DefifaTierCashOutWeight {
uint256 id; // Tier ID
uint256 cashOutWeight; // Share of total (e.g., 0.5e18 = 50%)
}
// Example: 4-team tournament, Team A wins
// Team A: 1e18 (100% of pot)
// Team B: 0
// Team C: 0
// Team D: 0
// Example: Fantasy league with scoring
// Team A (1st): 0.5e18 (50%)
// Team B (2nd): 0.3e18 (30%)
// Team C (3rd): 0.15e18 (15%)
// Team D (4th): 0.05e18 (5%)
First Owner Tracking
Critical for fair games - rewards go to original minters, not secondary buyers:
// Track who first minted each token
mapping(uint256 tokenId => address) public firstOwnerOf;
// In _processPayment():
firstOwnerOf[tokenId] = beneficiary;
// In cash out calculation:
// Only firstOwnerOf[tokenId] receives the full reward
// Current owner can transfer, but original minter gets payout
Governor Voting
// Attestation power = share of tier tokens you own
// If you own 25 of 100 tokens in Tier 1, you have 25% of Tier 1's voting power
function attestToScorecardFrom(
address attester,
DefifaScorecard calldata scorecard
) external {
// Verify attester hasn't already voted
// Add attester's voting power to scorecard
// If quorum reached, scorecard can be ratified
}
function ratifyScorecard(DefifaScorecard calldata scorecard) external {
// Verify scorecard has 50% attestation across all minted tiers
// Set tier cash out weights on delegate
// Game moves to COMPLETE phase
}
When to Use This Pattern
| Use Case |
Fits Pattern? |
| Sports predictions |
Yes - teams = tiers, outcomes = weights |
| Fantasy leagues |
Yes - players draft teams, scoring determines payouts |
| Tournament brackets |
Yes - bracket picks = tiers |
| Election predictions |
Yes - candidates = tiers |
| Price predictions |
Yes - price ranges = tiers |
| Art competitions |
Yes - entries = tiers, votes = weights |
| Standard NFT collection |
No - use Pattern 6 instead |
| Fixed-price redemptions |
No - use native 721-hook |
Key Implementation Considerations
- Phase transitions via rulesets: Use ruleset durations to enforce timing
- Refund window: Allow early exit before outcomes are known
- Quorum design: Too high = deadlock, too low = manipulation
- First-owner vs current-owner: Decide who receives rewards
- No-contest handling: What if not enough participation?
Reference Implementation
defifa-collection-deployer-v5: https://github.com/BallKidz/defifa-collection-deployer-v5
Key contracts:
DefifaDelegate.sol - Extends JB721Hook with phase logic and dynamic weights
DefifaGovernor.sol - On-chain voting for scorecard ratification
DefifaDeployer.sol - Factory for launching games
DefifaTokenUriResolver.sol - Dynamic metadata showing pot share
Features demonstrated:
- Phase-based game lifecycle
- Tier-weighted governance voting
- Dynamic cash out weight redistribution
- First-owner tracking for fair rewards
- No-contest handling for failed games
Pattern 8: Custom ERC20 Project Tokens
Use case: Projects requiring custom tokenomics beyond standard mint/burn mechanics
Solution: Implement IJBToken interface and use setTokenFor() instead of deployERC20For()
Why This Pattern?
Default Juicebox tokens (credits or JBERC20) work for most projects, but some use cases require custom token logic:
| Default Token Limitation |
Custom Token Solution |
| No transfer fees |
Implement tax-on-transfer |
| Fixed supply mechanics |
Use rebasing/elastic supply |
| No governance features |
Extend ERC20Votes |
| Immutable name/symbol |
Add setName/setSymbol functions |
| Uniform holder treatment |
Add allowlists/denylists |
Architecture
┌─────────────────────────────────────────────────────────────┐
│ Juicebox Protocol (unchanged) │
│ ├── JBController calls mint/burn on token │
│ ├── JBTokens tracks credits + token supply │
│ └── JBMultiTerminal handles payments/cash outs │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Custom ERC20 Token (your code) │ │
│ │ ├── Implements IJBToken interface │ │
│ │ ├── Authorizes JBController for mint/burn │ │
│ │ ├── Uses 18 decimals (REQUIRED) │ │
│ │ └── Custom logic: taxes, rebasing, governance, etc │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Interface Requirements
interface IJBToken is IERC20 {
/// @notice Must return true for the target project ID
function canBeAddedTo(uint256 projectId) external view returns (bool);
/// @notice Called by JBController when payments are received
function mint(address holder, uint256 amount) external;
/// @notice Called by JBController when tokens are cashed out
function burn(address holder, uint256 amount) external;
}
Example: Transfer Tax Token
Revenue-generating token that collects fees on every transfer:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract TaxedProjectToken is ERC20 {
uint256 public constant TAX_BPS = 100; // 1%
address public immutable controller;
address public immutable treasury;
uint256 public immutable projectId;
constructor(
string memory name,
string memory symbol,
address _controller,
uint256 _projectId,
address _treasury
) ERC20(name, symbol) {
controller = _controller;
projectId = _projectId;
treasury = _treasury;
}
function decimals() public pure override returns (uint8) { return 18; }
function canBeAddedTo(uint256 _projectId) external view returns (bool) {
return _projectId == projectId;
}
function mint(address to, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_mint(to, amount);
}
function burn(address from, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_burn(from, amount);
}
function _update(address from, address to, uint256 amount) internal override {
// No tax on mints, burns, or controller operations
if (from == address(0) || to == address(0) || msg.sender == controller) {
super._update(from, to, amount);
return;
}
// Apply transfer tax
uint256 tax = (amount * TAX_BPS) / 10000;
super._update(from, treasury, tax);
super._update(from, to, amount - tax);
}
}
Deployment:
// 1. Deploy custom token (before or after project creation)
TaxedProjectToken token = new TaxedProjectToken(
"Taxed Token",
"TAX",
address(CONTROLLER),
projectId,
treasuryAddress
);
// 2. Set as project token (requires SET_TOKEN permission)
CONTROLLER.setTokenFor(projectId, IJBToken(address(token)));
Example: Governance Token with Voting
Enable on-chain governance while maintaining treasury mechanics:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ERC20Votes, ERC20} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {Nonces} from "@openzeppelin/contracts/utils/Nonces.sol";
contract GovernanceProjectToken is ERC20Votes {
address public immutable controller;
uint256 public immutable projectId;
constructor(
string memory name,
string memory symbol,
address _controller,
uint256 _projectId
) ERC20(name, symbol) EIP712(name, "1") {
controller = _controller;
projectId = _projectId;
}
function decimals() public pure override returns (uint8) { return 18; }
function canBeAddedTo(uint256 _projectId) external view returns (bool) {
return _projectId == projectId;
}
function mint(address to, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_mint(to, amount);
}
function burn(address from, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_burn(from, amount);
}
// Inherits: delegate(), delegateBySig(), getVotes(), getPastVotes(), etc.
}
Usage with Governor:
// Deploy governor that uses token's voting power
GovernorBravo governor = new GovernorBravo(
GovernanceProjectToken(token),
timelockAddress,
votingDelay,
votingPeriod,
proposalThreshold
);
// Token holders delegate and vote
token.delegate(voterAddress); // Self-delegate to activate voting
governor.propose(...);
governor.castVote(proposalId, support);
Example: Editable Name/Symbol Token
Allow project owners to rebrand without deploying a new token:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IJBProjects} from "@bananapus/core/src/interfaces/IJBProjects.sol";
contract EditableProjectToken is ERC20 {
IJBProjects public immutable PROJECTS;
address public immutable controller;
uint256 public immutable projectId;
string private _tokenName;
string private _tokenSymbol;
event NameUpdated(string oldName, string newName);
event SymbolUpdated(string oldSymbol, string newSymbol);
constructor(
string memory initialName,
string memory initialSymbol,
address _controller,
uint256 _projectId,
IJBProjects projects
) ERC20(initialName, initialSymbol) {
_tokenName = initialName;
_tokenSymbol = initialSymbol;
controller = _controller;
projectId = _projectId;
PROJECTS = projects;
}
modifier onlyProjectOwner() {
require(msg.sender == PROJECTS.ownerOf(projectId), "NOT_OWNER");
_;
}
function name() public view override returns (string memory) {
return _tokenName;
}
function symbol() public view override returns (string memory) {
return _tokenSymbol;
}
function decimals() public pure override returns (uint8) { return 18; }
function canBeAddedTo(uint256 _projectId) external view returns (bool) {
return _projectId == projectId;
}
function mint(address to, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_mint(to, amount);
}
function burn(address from, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_burn(from, amount);
}
/// @notice Update token name. Only callable by project owner.
function setName(string calldata newName) external onlyProjectOwner {
emit NameUpdated(_tokenName, newName);
_tokenName = newName;
}
/// @notice Update token symbol. Only callable by project owner.
function setSymbol(string calldata newSymbol) external onlyProjectOwner {
emit SymbolUpdated(_tokenSymbol, newSymbol);
_tokenSymbol = newSymbol;
}
}
Use cases:
- Project rebranding without migrating liquidity
- Seasonal/event-based name changes
- Fixing typos discovered post-launch
- Community-voted name updates
Tradeoff: Some DEXs and aggregators cache token metadata. Changes may not propagate immediately to all interfaces.
Example: Vesting Token
Enforce time-based vesting at the token level - useful for team allocations, investor locks, or contributor rewards where tokens should vest over time:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IJBProjects} from "@bananapus/core/src/interfaces/IJBProjects.sol";
/// @notice Project token with per-address vesting schedules.
/// @dev Vesting restricts transfers, not minting/burning. Combined with treasury
/// vesting (payout limits), this creates layered protection.
contract VestingProjectToken is ERC20 {
struct VestingSchedule {
uint256 totalAmount; // Total tokens in this schedule
uint256 released; // Already released/transferred
uint40 start; // Vesting start timestamp
uint40 cliff; // Cliff end timestamp (0 = no cliff)
uint40 duration; // Total vesting duration from start
}
IJBProjects public immutable PROJECTS;
address public immutable controller;
uint256 public immutable projectId;
mapping(address => VestingSchedule) public vestingOf;
event VestingScheduleSet(
address indexed beneficiary,
uint256 totalAmount,
uint40 start,
uint40 cliff,
uint40 duration
);
error CliffNotReached();
error InsufficientVestedBalance();
error VestingAlreadyExists();
constructor(
string memory name,
string memory symbol,
address _controller,
uint256 _projectId,
IJBProjects projects
) ERC20(name, symbol) {
controller = _controller;
projectId = _projectId;
PROJECTS = projects;
}
modifier onlyProjectOwner() {
require(msg.sender == PROJECTS.ownerOf(projectId), "NOT_OWNER");
_;
}
function decimals() public pure override returns (uint8) { return 18; }
function canBeAddedTo(uint256 _projectId) external view returns (bool) {
return _projectId == projectId;
}
function mint(address to, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_mint(to, amount);
}
function burn(address from, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_burn(from, amount);
}
/// @notice Set a vesting schedule for an address.
/// @dev Call this AFTER minting tokens to the beneficiary.
/// @param beneficiary Address whose tokens will vest.
/// @param totalAmount Total tokens subject to vesting (should match balance).
/// @param start When vesting begins (can be in the past).
/// @param cliffDuration Seconds until cliff ends (0 for no cliff).
/// @param vestingDuration Total seconds for full vesting from start.
function setVestingSchedule(
address beneficiary,
uint256 totalAmount,
uint40 start,
uint40 cliffDuration,
uint40 vestingDuration
) external onlyProjectOwner {
if (vestingOf[beneficiary].totalAmount > 0) revert VestingAlreadyExists();
vestingOf[beneficiary] = VestingSchedule({
totalAmount: totalAmount,
released: 0,
start: start,
cliff: start + cliffDuration,
duration: vestingDuration
});
emit VestingScheduleSet(
beneficiary,
totalAmount,
start,
start + cliffDuration,
vestingDuration
);
}
/// @notice Calculate how many tokens have vested for an address.
function vestedAmountOf(address account) public view returns (uint256) {
VestingSchedule memory schedule = vestingOf[account];
// No vesting schedule = all tokens are vested (freely transferable)
if (schedule.totalAmount == 0) return balanceOf(account);
// Before cliff = nothing vested
if (block.timestamp < schedule.cliff) return 0;
// After full duration = everything vested
if (block.timestamp >= schedule.start + schedule.duration) {
return schedule.totalAmount;
}
// Linear vesting between cliff and end
uint256 elapsed = block.timestamp - schedule.start;
return (schedule.totalAmount * elapsed) / schedule.duration;
}
/// @notice Calculate transferable (vested and unreleased) tokens.
function transferableOf(address account) public view returns (uint256) {
VestingSchedule memory schedule = vestingOf[account];
// No vesting = full balance transferable
if (schedule.totalAmount == 0) return balanceOf(account);
uint256 vested = vestedAmountOf(account);
uint256 locked = schedule.totalAmount > vested
? schedule.totalAmount - vested
: 0;
uint256 balance = balanceOf(account);
return balance > locked ? balance - locked : 0;
}
function _update(address from, address to, uint256 amount) internal override {
// Skip vesting checks for mints, burns, and controller operations
if (from == address(0) || to == address(0) || msg.sender == controller) {
super._update(from, to, amount);
return;
}
VestingSchedule storage schedule = vestingOf[from];
// No vesting schedule = normal transfer
if (schedule.totalAmount == 0) {
super._update(from, to, amount);
return;
}
// Before cliff = no transfers allowed
if (block.timestamp < schedule.cliff) revert CliffNotReached();
// Check transferable amount
uint256 transferable = transferableOf(from);
if (amount > transferable) revert InsufficientVestedBalance();
// Track released amount for accounting
schedule.released += amount;
super._update(from, to, amount);
}
}
Key Design Decisions:
- Vesting is per-address, set by project owner after minting
- No vesting schedule = freely transferable (normal ERC20 behavior)
- Cliff period: no transfers until cliff is reached
- Linear vesting after cliff
- Controller operations (mint/burn for payments/cash outs) bypass vesting
Usage Pattern:
// 1. Deploy and set as project token
VestingProjectToken token = new VestingProjectToken(...);
CONTROLLER.setTokenFor(projectId, IJBToken(address(token)));
// 2. Team member receives tokens via payment or reserved distribution
// (tokens minted by controller - no vesting restriction on mint)
// 3. Project owner sets vesting schedule
token.setVestingSchedule(
teamMember,
1_000_000e18, // 1M tokens vest
uint40(block.timestamp), // Start now
365 days, // 1 year cliff
4 * 365 days // 4 year total vest
);
// Result:
// - Year 0-1: 0 tokens transferable (cliff)
// - Year 1: 250k tokens transferable (25% vested)
// - Year 2: 500k tokens transferable (50% vested)
// - Year 4+: All tokens transferable
Combining with Treasury Vesting:
| Layer |
Protects |
Mechanism |
| Token vesting |
Holder's tokens |
Transfer restrictions |
| Treasury vesting |
Treasury funds |
Payout limits |
For comprehensive protection, use both:
- Treasury vesting (Pattern 1): Prevents premature fund withdrawal
- Token vesting: Prevents premature token sales by recipients
When to Use Token Vesting vs Treasury Vesting:
| Scenario |
Use Token Vesting |
Use Treasury Vesting |
| Team allocations with cliff |
✅ |
Optional |
| Investor lock-ups |
✅ |
Optional |
| Recurring payroll/grants |
❌ |
✅ |
| Milestone-based releases |
❌ |
✅ |
| All-holder protection |
❌ |
✅ |
| Per-person schedules |
✅ |
❌ |
Tradeoffs:
- Adds complexity vs standard token
- Vesting schedules are permanent once set
- Does not prevent cash outs (controller operations are exempt)
- Must set schedule after minting, not before
Example: Concentration Limited Token
Prevent any single holder from accumulating too large a share:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ConcentrationLimitedToken is ERC20 {
uint256 public maxHolderBps = 200; // 2% max per holder
address public immutable controller;
uint256 public immutable projectId;
mapping(address => bool) public isExempt;
constructor(
string memory name,
string memory symbol,
address _controller,
uint256 _projectId
) ERC20(name, symbol) {
controller = _controller;
projectId = _projectId;
isExempt[_controller] = true; // Controller always exempt
}
function decimals() public pure override returns (uint8) { return 18; }
function canBeAddedTo(uint256 _projectId) external view returns (bool) {
return _projectId == projectId;
}
function mint(address to, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_mint(to, amount);
}
function burn(address from, uint256 amount) external {
require(msg.sender == controller, "UNAUTHORIZED");
_burn(from, amount);
}
function _update(address from, address to, uint256 amount) internal override {
// Skip checks for mints, burns, and exempt addresses
if (from == address(0) || to == address(0) || isExempt[to]) {
super._update(from, to, amount);
return;
}
// Check concentration limit
uint256 maxBalance = (totalSupply() * maxHolderBps) / 10000;
require(balanceOf(to) + amount <= maxBalance, "EXCEEDS_MAX_HOLDING");
super._update(from, to, amount);
}
function setExempt(address account, bool exempt) external {
require(msg.sender == controller, "UNAUTHORIZED");
isExempt[account] = exempt;
}
}
Use cases:
- Encourage broad token distribution
- Prevent governance centralization
- Reduce market manipulation risk
Tradeoff: Liquidity pools and the controller must be marked exempt. New holders during early high-supply periods may hit limits before supply grows.
When to Use This Pattern
| Use Case |
Custom Token? |
Alternative |
| Simple fundraising |
No |
Use credits or JBERC20 |
| Transfer fees/taxes |
Yes |
- |
| Rebasing mechanics |
Yes |
- |
| Governance voting |
Yes |
External governance |
| Pre-existing token |
Yes |
Migrate to new project |
| Per-holder token vesting |
Yes |
- |
| Treasury fund vesting |
No |
Use payout limits (Pattern 1) |
| Compliance restrictions |
Yes |
- |
| Editable name/symbol |
Yes |
Redeploy token |
| Concentration limits |
Yes |
- |
Key Tradeoffs
| Aspect |
Standard Token |
Custom Token |
| Complexity |
Low |
High |
| Audit burden |
Audited by JB |
Your responsibility |
| Gas costs |
Optimized |
Variable |
| Integration |
Seamless |
Requires testing |
| Flexibility |
Limited |
Full control |
| Risk |
Low |
Higher (custom code) |
Critical Constraints
- 18 decimals mandatory - All Juicebox math assumes 18 decimals
- Controller must be authorized - Mi
…(truncated)
1---
2name: jb-patterns
3description: |
4 Common Juicebox V5 design patterns for vesting, NFT treasuries, terminal wrappers, yield integration, and
5 governance-minimal configurations. Use when: (1) need treasury vesting without custom contracts, (2) building
6 NFT-gated redemptions, (3) extending revnet functionality via pay wrappers, (4) implementing custom ERC20
7 tokens, (5) integrating yield protocols like Aave, (6) deciding between native mechanics vs custom code.
8 Covers 11 patterns including terminal wrapper for dynamic pay-time splits, yield-generating hooks for
9 Aave/DeFi integration, and token interception. Golden rule: prefer configuration over custom contracts.
10metadata:
11 source: https://skillmd.com/skills/modbender/jb-patterns
12---
13
14# Juicebox V5 Design Patterns
15
16Proven patterns for common use cases using native Juicebox mechanics. **Always prefer configuration over custom contracts.**
17
18## Golden Rule
19
20> Before writing custom code, ask: "Can this be achieved with payout limits, surplus allowance, splits, and cycling rulesets?"
21
22---
23
24## Pattern 1: Vesting via Native Mechanics
25
26**Use case**: Release funds to a beneficiary over time (e.g., team vesting, milestone-based releases)
27
28**Solution**: Use cycling rulesets with payout limits
29
30### How It Works
31
32| Mechanism | Behavior | Use For |
33|-----------|----------|---------|
34| **Payout Limit** | Resets each cycle | Recurring distributions (vesting) |
35| **Surplus Allowance** | One-time per ruleset | Discretionary treasury access |
36| **Cycle Duration** | Determines distribution frequency | Monthly = 30 days |
37
38### Configuration
39
40```solidity
41JBRulesetConfig({
42 duration: 30 days, // Monthly cycles
43 // ... other config
44 fundAccessLimitGroups: [
45 JBFundAccessLimitGroup({
46 terminal: address(TERMINAL),
47 token: JBConstants.NATIVE_TOKEN,
48 payoutLimits: [
49 JBCurrencyAmount({
50 amount: 6.67 ether, // Monthly vesting amount
51 currency: nativeCurrency
52 })
53 ],
54 surplusAllowances: [
55 JBCurrencyAmount({
56 amount: 20 ether, // One-time treasury (doesn't reset)
57 currency: nativeCurrency
58 })
59 ]
60 })
61 ]
62});
63```
64
65### Capital Flow
66
67```
68Month 0: Balance = 100 ETH
69 Surplus = Balance - Payout Limit = 93.33 ETH (redeemable)
70
71Month 1: Team calls sendPayoutsOf() → receives 6.67 ETH
72 Balance = 93.33 ETH
73 Surplus = 86.67 ETH
74
75Month 12: All vested, Balance = 20 ETH (treasury allowance)
76```
77
78### Key Insight
79
80- **Payout limits protect vesting funds** from redemption
81- **Surplus = unvested funds** available for token holder cash outs
82- **No custom contracts needed**
83
84---
85
86## Pattern 2: NFT-Gated Treasury
87
88**Use case**: Sell NFTs, allow holders to redeem against treasury surplus
89
90**Solution**: Use nana-721-hook-v5 with native cash outs
91
92### Configuration
93
941. Deploy project with `JB721TiersHookProjectDeployer`
952. Configure 721 hook as data hook for pay AND cash out
963. Set `cashOutTaxRate: 0` for full redemption value
97
98```solidity
99JBRulesetMetadata({
100 cashOutTaxRate: 0, // Full redemption
101 useDataHookForPay: true, // 721 hook mints NFTs
102 useDataHookForCashOut: true, // 721 hook handles burns
103 dataHook: address(0), // Set by deployer
104 // ...
105});
106```
107
108### How Cash Outs Work
109
1101. User calls `cashOutTokensOf()` on terminal
1112. 721 hook intercepts, calculates: `(NFT price / total prices) × surplus`
1123. NFT is burned, ETH sent to user
113
114**No custom cash out hook needed** - the 721 hook handles everything.
115
116---
117
118## Pattern 3: Governance-Minimal Treasury
119
120**Use case**: Immutable treasury with no admin controls
121
122**Solution**: Transfer ownership to burn address after setup
123
124### Configuration
125
126```solidity
127// 1. Deploy project with restrictive metadata
128JBRulesetMetadata({
129 allowOwnerMinting: false,
130 allowTerminalMigration: false,
131 allowSetTerminals: false,
132 allowSetController: false,
133 allowAddAccountingContext: false,
134 allowAddPriceFeed: false,
135 // ...
136});
137
138// 2. After deployment, burn ownership
139PROJECTS.transferFrom(deployer, 0x000000000000000000000000000000000000dEaD, projectId);
140```
141
142### What This Achieves
143
144- No one can change rulesets
145- No one can add/remove terminals
146- No one can mint tokens arbitrarily
147- Payouts/cash outs work as configured forever
148
149---
150
151## Pattern 4: Split Recipients Without Custom Hooks
152
153**Use case**: Distribute payouts to multiple addresses
154
155**Solution**: Use native splits with direct beneficiaries
156
157### Configuration
158
159```solidity
160JBSplit[] memory splits = new JBSplit[](3);
161
162splits[0] = JBSplit({
163 percent: 500_000_000, // 50%
164 beneficiary: payable(team1),
165 projectId: 0,
166 hook: IJBSplitHook(address(0)), // No hook needed!
167 // ...
168});
169
170splits[1] = JBSplit({
171 percent: 300_000_000, // 30%
172 beneficiary: payable(team2),
173 // ...
174});
175
176splits[2] = JBSplit({
177 percent: 200_000_000, // 20%
178 beneficiary: payable(treasury),
179 // ...
180});
181```
182
183**Only use split hooks when you need custom logic** (e.g., swapping tokens, adding to LP).
184
185---
186
187## Pattern 5: NFT + Vesting Combined
188
189**Use case**: Sell NFTs with funds vesting to team over time, holders can exit by burning
190
191**Solution**: Combine patterns 1 + 2
192
193### Architecture
194
195```
196┌─────────────────────────────────────────────────┐
197│ JB Project with 721 Hook │
198│ │
199│ • NFT tier: 100 supply, 1 ETH each │
200│ • Payout limit: 6.67 ETH/month (vesting) │
201│ • Surplus allowance: 20 ETH (treasury) │
202│ • Cash out tax: 0% │
203│ • Owner: burn address │
204│ │
205│ Treasury Flow: │
206│ ├── Month 0: 80 ETH surplus (all unvested) │
207│ ├── Month 6: 40 ETH surplus │
208│ └── Month 12: 0 ETH surplus (fully vested) │
209│ │
210│ NFT Holder: Can burn anytime for pro-rata │
211│ share of current surplus │
212└─────────────────────────────────────────────────┘
213```
214
215### Complete Example
216
217See the Drip x Juicebox deployment script for a full implementation:
218- 100 NFTs at 1 ETH each
219- 20 ETH immediate treasury (surplus allowance)
220- 80 ETH vests over 12 months (payout limits)
221- NFT holders can burn to exit at any time
222- Zero custom contracts
223
224---
225
226## Pattern 6: Custom NFT Content via Resolver
227
228**Use case**: NFT project with custom artwork, composable assets, or dynamic metadata while using 721-hook off-the-shelf
229
230**Solution**: Implement `IJB721TokenUriResolver` for custom content, use standard 721-hook for treasury mechanics
231
232### Why This Pattern?
233
234The 721-hook handles all the hard stuff:
235- Payment processing and tier selection
236- Token minting and supply tracking
237- Cash out weight calculations
238- Reserved token mechanics
239
240You only need custom code for **content generation** (artwork, metadata, composability).
241
242### Architecture
243
244```
245┌─────────────────────────────────────────────────────────────┐
246│ Standard 721-Hook (off-the-shelf) │
247│ ├── Handles payments, minting, cash outs │
248│ ├── Manages tier supply and pricing │
249│ └── Calls tokenUriResolver.tokenUriOf() for metadata │
250│ │ │
251│ ▼ │
252│ ┌─────────────────────────────────────────────────────┐ │
253│ │ Custom TokenUriResolver (your code) │ │
254│ │ ├── Implements IJB721TokenUriResolver │ │
255│ │ ├── tokenUriOf() → dynamic SVG/metadata │ │
256│ │ └── Custom behaviors (composability, decoration) │ │
257│ └─────────────────────────────────────────────────────┘ │
258└─────────────────────────────────────────────────────────────┘
259```
260
261### Interface
262
263```solidity
264interface IJB721TokenUriResolver {
265 /// @notice Get the token URI for a given token.
266 /// @param hook The 721 hook address.
267 /// @param tokenId The token ID.
268 /// @return The token URI (typically base64-encoded JSON with SVG).
269 function tokenUriOf(address hook, uint256 tokenId)
270 external view returns (string memory);
271}
272```
273
274### Basic Resolver Implementation
275
276```solidity
277// SPDX-License-Identifier: MIT
278pragma solidity ^0.8.23;
279
280import {IJB721TokenUriResolver} from "@bananapus/721-hook/src/interfaces/IJB721TokenUriResolver.sol";
281import {IJB721TiersHook} from "@bananapus/721-hook/src/interfaces/IJB721TiersHook.sol";
282
283contract CustomTokenUriResolver is IJB721TokenUriResolver {
284 /// @notice Generate token URI with custom artwork/metadata.
285 function tokenUriOf(address hook, uint256 tokenId)
286 external view override returns (string memory)
287 {
288 // Get tier info from the hook
289 IJB721TiersHook tiersHook = IJB721TiersHook(hook);
290 uint256 tierId = tiersHook.tierIdOfToken(tokenId);
291
292 // Generate your custom metadata/artwork
293 string memory name = _getNameForTier(tierId);
294 string memory svg = _generateSvgForToken(tokenId, tierId);
295
296 // Return base64-encoded JSON
297 return string(abi.encodePacked(
298 "data:application/json;base64,",
299 Base64.encode(bytes(abi.encodePacked(
300 '{"name":"', name, '",',
301 '"image":"data:image/svg+xml;base64,', Base64.encode(bytes(svg)), '"}'
302 )))
303 ));
304 }
305
306 function _getNameForTier(uint256 tierId) internal view returns (string memory) {
307 // Your tier naming logic
308 }
309
310 function _generateSvgForToken(uint256 tokenId, uint256 tierId) internal view returns (string memory) {
311 // Your SVG generation logic
312 }
313}
314```
315
316### Advanced: Composable NFTs (Banny Pattern)
317
318For composable NFTs where items can be attached to base tokens:
319
320```solidity
321contract ComposableTokenUriResolver is IJB721TokenUriResolver {
322 // Track which items are attached to which base tokens
323 mapping(address hook => mapping(uint256 baseTokenId => uint256[])) public attachedItems;
324
325 // Prevent changes for a duration (e.g., 7 days)
326 mapping(address hook => mapping(uint256 tokenId => uint256)) public lockedUntil;
327
328 /// @notice Attach items to a base token.
329 function decorateWith(
330 address hook,
331 uint256 baseTokenId,
332 uint256[] calldata itemIds
333 ) external {
334 // Verify caller owns both base token and items
335 require(IJB721TiersHook(hook).ownerOf(baseTokenId) == msg.sender);
336 require(lockedUntil[hook][baseTokenId] < block.timestamp, "LOCKED");
337
338 for (uint256 i; i < itemIds.length; i++) {
339 require(IJB721TiersHook(hook).ownerOf(itemIds[i]) == msg.sender);
340 // Transfer item to this contract (escrow while attached)
341 IJB721TiersHook(hook).transferFrom(msg.sender, address(this), itemIds[i]);
342 }
343
344 attachedItems[hook][baseTokenId] = itemIds;
345 }
346
347 /// @notice Lock outfit changes for 7 days.
348 function lockChangesFor(address hook, uint256 baseTokenId) external {
349 require(IJB721TiersHook(hook).ownerOf(baseTokenId) == msg.sender);
350 lockedUntil[hook][baseTokenId] = block.timestamp + 7 days;
351 }
352
353 /// @notice Generate composite SVG from base + attached items.
354 function tokenUriOf(address hook, uint256 tokenId) external view override returns (string memory) {
355 uint256[] memory items = attachedItems[hook][tokenId];
356
357 // Generate layered SVG combining base + all attached items
358 string memory svg = _generateCompositeSvg(hook, tokenId, items);
359
360 return _encodeAsDataUri(svg);
361 }
362}
363```
364
365### Deployment Integration
366
367```solidity
368// 1. Deploy your custom resolver
369CustomTokenUriResolver resolver = new CustomTokenUriResolver();
370
371// 2. Configure 721 hook with resolver
372REVDeploy721TiersHookConfig memory hookConfig = REVDeploy721TiersHookConfig({
373 baseline721HookConfiguration: JBDeploy721TiersHookConfig({
374 // ... tier configs
375 tokenUriResolver: IJB721TokenUriResolver(address(resolver)),
376 // ...
377 }),
378 // ...
379});
380
381// 3. Deploy project/revnet with hook config
382deployer.deployWith721sFor(projectId, hookConfig, ...);
383```
384
385### When to Use This Pattern
386
387| Requirement | Use Resolver? |
388|-------------|---------------|
389| Static tier images (IPFS) | No - use `encodedIPFSUri` in tier config |
390| Dynamic/generative art | **Yes** |
391| Composable/layered NFTs | **Yes** |
392| On-chain SVG storage | **Yes** |
393| Token-specific metadata | **Yes** |
394| Standard ERC-721 metadata | No - use default |
395
396### Reference Implementation
397
398**banny-retail-v5**: https://github.com/mejango/banny-retail-v5
399- `Banny721TokenUriResolver.sol` - Composable SVG NFTs with outfit decoration
400- `Deploy.s.sol` - Deployment with custom resolver
401- `Drop1.s.sol` - Adding tiers with custom categories
402
403Key features demonstrated:
404- On-chain SVG storage with hash verification
405- Composable outfits (attach items to base Banny)
406- Outfit locking (7-day freeze)
407- Category-based slot system
408- Multi-chain deployment via Revnet
409
410---
411
412## Pattern 7: Prediction Games with Dynamic Cash Out Weights
413
414**Use case**: Games where outcomes determine payout distribution (prediction markets, fantasy sports, competitions)
415
416**Solution**: Extend 721-hook with custom delegate, use on-chain governance for outcome resolution
417
418### Why This Pattern Requires Extending 721-Hook
419
420Unlike Pattern 6 (resolver-only), prediction games need to change **core treasury mechanics**:
421
422| Requirement | Why Resolver Isn't Enough |
423|-------------|---------------------------|
424| Dynamic cash out weights | Cash out calculation is in the hook, not resolver |
425| First-owner tracking | Rewards original minters, not current holders |
426| Phase enforcement | Different rules per game phase |
427| Governance integration | Scorecard ratification triggers weight changes |
428
429### Architecture
430
431```
432┌─────────────────────────────────────────────────────────────┐
433│ Game Lifecycle (via Juicebox Rulesets) │
434│ │
435│ COUNTDOWN → MINT → REFUND → SCORING → COMPLETE │
436│ │ │ │ │ │ │
437│ │ Players Early Holders Winners │
438│ │ mint exit vote on cash out │
439│ │ NFTs OK scorecard winnings │
440│ │
441├─────────────────────────────────────────────────────────────┤
442│ Custom Delegate (extends JB721Hook) │
443│ ├── Tracks first owners (for fair reward distribution) │
444│ ├── Phase-aware cash out logic │
445│ ├── Dynamic tier weights (set by governor) │
446│ └── Enforces phase restrictions │
447│ │
448├─────────────────────────────────────────────────────────────┤
449│ Governor Contract │
450│ ├── NFT holders propose scorecards │
451│ ├── Tier-weighted voting (own 25% of tier = 25% of votes) │
452│ ├── 50% quorum required for ratification │
453│ └── Ratification sets tier cash out weights │
454└─────────────────────────────────────────────────────────────┘
455```
456
457### Game Phases
458
459```solidity
460enum DefifaGamePhase {
461 COUNTDOWN, // Game announced, no minting yet
462 MINT, // Players can mint NFTs (pick teams)
463 REFUND, // Early exit window (get mint cost back)
464 SCORING, // Game over, holders vote on scorecard
465 COMPLETE, // Scorecard ratified, winners cash out
466 NO_CONTEST_INEVITABLE, // Not enough participation
467 NO_CONTEST // Game cancelled, full refunds
468}
469```
470
471### Dynamic Cash Out Weights
472
473Standard 721-hook: `cashOutWeight = tierPrice` (fixed)
474
475Defifa pattern: `cashOutWeight = scorecardWeight[tierId]` (dynamic)
476
477```solidity
478// Total weight is 1e18 (100%), distributed among tiers by scorecard
479uint256 constant TOTAL_CASH_OUT_WEIGHT = 1e18;
480
481struct DefifaTierCashOutWeight {
482 uint256 id; // Tier ID
483 uint256 cashOutWeight; // Share of total (e.g., 0.5e18 = 50%)
484}
485
486// Example: 4-team tournament, Team A wins
487// Team A: 1e18 (100% of pot)
488// Team B: 0
489// Team C: 0
490// Team D: 0
491
492// Example: Fantasy league with scoring
493// Team A (1st): 0.5e18 (50%)
494// Team B (2nd): 0.3e18 (30%)
495// Team C (3rd): 0.15e18 (15%)
496// Team D (4th): 0.05e18 (5%)
497```
498
499### First Owner Tracking
500
501Critical for fair games - rewards go to original minters, not secondary buyers:
502
503```solidity
504// Track who first minted each token
505mapping(uint256 tokenId => address) public firstOwnerOf;
506
507// In _processPayment():
508firstOwnerOf[tokenId] = beneficiary;
509
510// In cash out calculation:
511// Only firstOwnerOf[tokenId] receives the full reward
512// Current owner can transfer, but original minter gets payout
513```
514
515### Governor Voting
516
517```solidity
518// Attestation power = share of tier tokens you own
519// If you own 25 of 100 tokens in Tier 1, you have 25% of Tier 1's voting power
520
521function attestToScorecardFrom(
522 address attester,
523 DefifaScorecard calldata scorecard
524) external {
525 // Verify attester hasn't already voted
526 // Add attester's voting power to scorecard
527 // If quorum reached, scorecard can be ratified
528}
529
530function ratifyScorecard(DefifaScorecard calldata scorecard) external {
531 // Verify scorecard has 50% attestation across all minted tiers
532 // Set tier cash out weights on delegate
533 // Game moves to COMPLETE phase
534}
535```
536
537### When to Use This Pattern
538
539| Use Case | Fits Pattern? |
540|----------|---------------|
541| Sports predictions | **Yes** - teams = tiers, outcomes = weights |
542| Fantasy leagues | **Yes** - players draft teams, scoring determines payouts |
543| Tournament brackets | **Yes** - bracket picks = tiers |
544| Election predictions | **Yes** - candidates = tiers |
545| Price predictions | **Yes** - price ranges = tiers |
546| Art competitions | **Yes** - entries = tiers, votes = weights |
547| Standard NFT collection | **No** - use Pattern 6 instead |
548| Fixed-price redemptions | **No** - use native 721-hook |
549
550### Key Implementation Considerations
551
5521. **Phase transitions via rulesets**: Use ruleset durations to enforce timing
5532. **Refund window**: Allow early exit before outcomes are known
5543. **Quorum design**: Too high = deadlock, too low = manipulation
5554. **First-owner vs current-owner**: Decide who receives rewards
5565. **No-contest handling**: What if not enough participation?
557
558### Reference Implementation
559
560**defifa-collection-deployer-v5**: https://github.com/BallKidz/defifa-collection-deployer-v5
561
562Key contracts:
563- `DefifaDelegate.sol` - Extends JB721Hook with phase logic and dynamic weights
564- `DefifaGovernor.sol` - On-chain voting for scorecard ratification
565- `DefifaDeployer.sol` - Factory for launching games
566- `DefifaTokenUriResolver.sol` - Dynamic metadata showing pot share
567
568Features demonstrated:
569- Phase-based game lifecycle
570- Tier-weighted governance voting
571- Dynamic cash out weight redistribution
572- First-owner tracking for fair rewards
573- No-contest handling for failed games
574
575---
576
577## Pattern 8: Custom ERC20 Project Tokens
578
579**Use case**: Projects requiring custom tokenomics beyond standard mint/burn mechanics
580
581**Solution**: Implement `IJBToken` interface and use `setTokenFor()` instead of `deployERC20For()`
582
583### Why This Pattern?
584
585Default Juicebox tokens (credits or JBERC20) work for most projects, but some use cases require custom token logic:
586
587| Default Token Limitation | Custom Token Solution |
588|--------------------------|----------------------|
589| No transfer fees | Implement tax-on-transfer |
590| Fixed supply mechanics | Use rebasing/elastic supply |
591| No governance features | Extend ERC20Votes |
592| Immutable name/symbol | Add setName/setSymbol functions |
593| Uniform holder treatment | Add allowlists/denylists |
594
595### Architecture
596
597```
598┌─────────────────────────────────────────────────────────────┐
599│ Juicebox Protocol (unchanged) │
600│ ├── JBController calls mint/burn on token │
601│ ├── JBTokens tracks credits + token supply │
602│ └── JBMultiTerminal handles payments/cash outs │
603│ │ │
604│ ▼ │
605│ ┌─────────────────────────────────────────────────────┐ │
606│ │ Custom ERC20 Token (your code) │ │
607│ │ ├── Implements IJBToken interface │ │
608│ │ ├── Authorizes JBController for mint/burn │ │
609│ │ ├── Uses 18 decimals (REQUIRED) │ │
610│ │ └── Custom logic: taxes, rebasing, governance, etc │ │
611│ └─────────────────────────────────────────────────────┘ │
612└─────────────────────────────────────────────────────────────┘
613```
614
615### Interface Requirements
616
617```solidity
618interface IJBToken is IERC20 {
619 /// @notice Must return true for the target project ID
620 function canBeAddedTo(uint256 projectId) external view returns (bool);
621
622 /// @notice Called by JBController when payments are received
623 function mint(address holder, uint256 amount) external;
624
625 /// @notice Called by JBController when tokens are cashed out
626 function burn(address holder, uint256 amount) external;
627}
628```
629
630### Example: Transfer Tax Token
631
632Revenue-generating token that collects fees on every transfer:
633
634```solidity
635// SPDX-License-Identifier: MIT
636pragma solidity ^0.8.23;
637
638import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
639
640contract TaxedProjectToken is ERC20 {
641 uint256 public constant TAX_BPS = 100; // 1%
642 address public immutable controller;
643 address public immutable treasury;
644 uint256 public immutable projectId;
645
646 constructor(
647 string memory name,
648 string memory symbol,
649 address _controller,
650 uint256 _projectId,
651 address _treasury
652 ) ERC20(name, symbol) {
653 controller = _controller;
654 projectId = _projectId;
655 treasury = _treasury;
656 }
657
658 function decimals() public pure override returns (uint8) { return 18; }
659
660 function canBeAddedTo(uint256 _projectId) external view returns (bool) {
661 return _projectId == projectId;
662 }
663
664 function mint(address to, uint256 amount) external {
665 require(msg.sender == controller, "UNAUTHORIZED");
666 _mint(to, amount);
667 }
668
669 function burn(address from, uint256 amount) external {
670 require(msg.sender == controller, "UNAUTHORIZED");
671 _burn(from, amount);
672 }
673
674 function _update(address from, address to, uint256 amount) internal override {
675 // No tax on mints, burns, or controller operations
676 if (from == address(0) || to == address(0) || msg.sender == controller) {
677 super._update(from, to, amount);
678 return;
679 }
680
681 // Apply transfer tax
682 uint256 tax = (amount * TAX_BPS) / 10000;
683 super._update(from, treasury, tax);
684 super._update(from, to, amount - tax);
685 }
686}
687```
688
689**Deployment**:
690```solidity
691// 1. Deploy custom token (before or after project creation)
692TaxedProjectToken token = new TaxedProjectToken(
693 "Taxed Token",
694 "TAX",
695 address(CONTROLLER),
696 projectId,
697 treasuryAddress
698);
699
700// 2. Set as project token (requires SET_TOKEN permission)
701CONTROLLER.setTokenFor(projectId, IJBToken(address(token)));
702```
703
704### Example: Governance Token with Voting
705
706Enable on-chain governance while maintaining treasury mechanics:
707
708```solidity
709// SPDX-License-Identifier: MIT
710pragma solidity ^0.8.23;
711
712import {ERC20Votes, ERC20} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
713import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
714import {Nonces} from "@openzeppelin/contracts/utils/Nonces.sol";
715
716contract GovernanceProjectToken is ERC20Votes {
717 address public immutable controller;
718 uint256 public immutable projectId;
719
720 constructor(
721 string memory name,
722 string memory symbol,
723 address _controller,
724 uint256 _projectId
725 ) ERC20(name, symbol) EIP712(name, "1") {
726 controller = _controller;
727 projectId = _projectId;
728 }
729
730 function decimals() public pure override returns (uint8) { return 18; }
731
732 function canBeAddedTo(uint256 _projectId) external view returns (bool) {
733 return _projectId == projectId;
734 }
735
736 function mint(address to, uint256 amount) external {
737 require(msg.sender == controller, "UNAUTHORIZED");
738 _mint(to, amount);
739 }
740
741 function burn(address from, uint256 amount) external {
742 require(msg.sender == controller, "UNAUTHORIZED");
743 _burn(from, amount);
744 }
745
746 // Inherits: delegate(), delegateBySig(), getVotes(), getPastVotes(), etc.
747}
748```
749
750**Usage with Governor**:
751```solidity
752// Deploy governor that uses token's voting power
753GovernorBravo governor = new GovernorBravo(
754 GovernanceProjectToken(token),
755 timelockAddress,
756 votingDelay,
757 votingPeriod,
758 proposalThreshold
759);
760
761// Token holders delegate and vote
762token.delegate(voterAddress); // Self-delegate to activate voting
763governor.propose(...);
764governor.castVote(proposalId, support);
765```
766
767### Example: Editable Name/Symbol Token
768
769Allow project owners to rebrand without deploying a new token:
770
771```solidity
772// SPDX-License-Identifier: MIT
773pragma solidity ^0.8.23;
774
775import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
776import {IJBProjects} from "@bananapus/core/src/interfaces/IJBProjects.sol";
777
778contract EditableProjectToken is ERC20 {
779 IJBProjects public immutable PROJECTS;
780 address public immutable controller;
781 uint256 public immutable projectId;
782
783 string private _tokenName;
784 string private _tokenSymbol;
785
786 event NameUpdated(string oldName, string newName);
787 event SymbolUpdated(string oldSymbol, string newSymbol);
788
789 constructor(
790 string memory initialName,
791 string memory initialSymbol,
792 address _controller,
793 uint256 _projectId,
794 IJBProjects projects
795 ) ERC20(initialName, initialSymbol) {
796 _tokenName = initialName;
797 _tokenSymbol = initialSymbol;
798 controller = _controller;
799 projectId = _projectId;
800 PROJECTS = projects;
801 }
802
803 modifier onlyProjectOwner() {
804 require(msg.sender == PROJECTS.ownerOf(projectId), "NOT_OWNER");
805 _;
806 }
807
808 function name() public view override returns (string memory) {
809 return _tokenName;
810 }
811
812 function symbol() public view override returns (string memory) {
813 return _tokenSymbol;
814 }
815
816 function decimals() public pure override returns (uint8) { return 18; }
817
818 function canBeAddedTo(uint256 _projectId) external view returns (bool) {
819 return _projectId == projectId;
820 }
821
822 function mint(address to, uint256 amount) external {
823 require(msg.sender == controller, "UNAUTHORIZED");
824 _mint(to, amount);
825 }
826
827 function burn(address from, uint256 amount) external {
828 require(msg.sender == controller, "UNAUTHORIZED");
829 _burn(from, amount);
830 }
831
832 /// @notice Update token name. Only callable by project owner.
833 function setName(string calldata newName) external onlyProjectOwner {
834 emit NameUpdated(_tokenName, newName);
835 _tokenName = newName;
836 }
837
838 /// @notice Update token symbol. Only callable by project owner.
839 function setSymbol(string calldata newSymbol) external onlyProjectOwner {
840 emit SymbolUpdated(_tokenSymbol, newSymbol);
841 _tokenSymbol = newSymbol;
842 }
843}
844```
845
846**Use cases**:
847- Project rebranding without migrating liquidity
848- Seasonal/event-based name changes
849- Fixing typos discovered post-launch
850- Community-voted name updates
851
852**Tradeoff**: Some DEXs and aggregators cache token metadata. Changes may not propagate immediately to all interfaces.
853
854### Example: Vesting Token
855
856Enforce time-based vesting at the token level - useful for team allocations, investor locks, or contributor rewards where tokens should vest over time:
857
858```solidity
859// SPDX-License-Identifier: MIT
860pragma solidity ^0.8.23;
861
862import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
863import {IJBProjects} from "@bananapus/core/src/interfaces/IJBProjects.sol";
864
865/// @notice Project token with per-address vesting schedules.
866/// @dev Vesting restricts transfers, not minting/burning. Combined with treasury
867/// vesting (payout limits), this creates layered protection.
868contract VestingProjectToken is ERC20 {
869 struct VestingSchedule {
870 uint256 totalAmount; // Total tokens in this schedule
871 uint256 released; // Already released/transferred
872 uint40 start; // Vesting start timestamp
873 uint40 cliff; // Cliff end timestamp (0 = no cliff)
874 uint40 duration; // Total vesting duration from start
875 }
876
877 IJBProjects public immutable PROJECTS;
878 address public immutable controller;
879 uint256 public immutable projectId;
880
881 mapping(address => VestingSchedule) public vestingOf;
882
883 event VestingScheduleSet(
884 address indexed beneficiary,
885 uint256 totalAmount,
886 uint40 start,
887 uint40 cliff,
888 uint40 duration
889 );
890
891 error CliffNotReached();
892 error InsufficientVestedBalance();
893 error VestingAlreadyExists();
894
895 constructor(
896 string memory name,
897 string memory symbol,
898 address _controller,
899 uint256 _projectId,
900 IJBProjects projects
901 ) ERC20(name, symbol) {
902 controller = _controller;
903 projectId = _projectId;
904 PROJECTS = projects;
905 }
906
907 modifier onlyProjectOwner() {
908 require(msg.sender == PROJECTS.ownerOf(projectId), "NOT_OWNER");
909 _;
910 }
911
912 function decimals() public pure override returns (uint8) { return 18; }
913
914 function canBeAddedTo(uint256 _projectId) external view returns (bool) {
915 return _projectId == projectId;
916 }
917
918 function mint(address to, uint256 amount) external {
919 require(msg.sender == controller, "UNAUTHORIZED");
920 _mint(to, amount);
921 }
922
923 function burn(address from, uint256 amount) external {
924 require(msg.sender == controller, "UNAUTHORIZED");
925 _burn(from, amount);
926 }
927
928 /// @notice Set a vesting schedule for an address.
929 /// @dev Call this AFTER minting tokens to the beneficiary.
930 /// @param beneficiary Address whose tokens will vest.
931 /// @param totalAmount Total tokens subject to vesting (should match balance).
932 /// @param start When vesting begins (can be in the past).
933 /// @param cliffDuration Seconds until cliff ends (0 for no cliff).
934 /// @param vestingDuration Total seconds for full vesting from start.
935 function setVestingSchedule(
936 address beneficiary,
937 uint256 totalAmount,
938 uint40 start,
939 uint40 cliffDuration,
940 uint40 vestingDuration
941 ) external onlyProjectOwner {
942 if (vestingOf[beneficiary].totalAmount > 0) revert VestingAlreadyExists();
943
944 vestingOf[beneficiary] = VestingSchedule({
945 totalAmount: totalAmount,
946 released: 0,
947 start: start,
948 cliff: start + cliffDuration,
949 duration: vestingDuration
950 });
951
952 emit VestingScheduleSet(
953 beneficiary,
954 totalAmount,
955 start,
956 start + cliffDuration,
957 vestingDuration
958 );
959 }
960
961 /// @notice Calculate how many tokens have vested for an address.
962 function vestedAmountOf(address account) public view returns (uint256) {
963 VestingSchedule memory schedule = vestingOf[account];
964
965 // No vesting schedule = all tokens are vested (freely transferable)
966 if (schedule.totalAmount == 0) return balanceOf(account);
967
968 // Before cliff = nothing vested
969 if (block.timestamp < schedule.cliff) return 0;
970
971 // After full duration = everything vested
972 if (block.timestamp >= schedule.start + schedule.duration) {
973 return schedule.totalAmount;
974 }
975
976 // Linear vesting between cliff and end
977 uint256 elapsed = block.timestamp - schedule.start;
978 return (schedule.totalAmount * elapsed) / schedule.duration;
979 }
980
981 /// @notice Calculate transferable (vested and unreleased) tokens.
982 function transferableOf(address account) public view returns (uint256) {
983 VestingSchedule memory schedule = vestingOf[account];
984
985 // No vesting = full balance transferable
986 if (schedule.totalAmount == 0) return balanceOf(account);
987
988 uint256 vested = vestedAmountOf(account);
989 uint256 locked = schedule.totalAmount > vested
990 ? schedule.totalAmount - vested
991 : 0;
992
993 uint256 balance = balanceOf(account);
994 return balance > locked ? balance - locked : 0;
995 }
996
997 function _update(address from, address to, uint256 amount) internal override {
998 // Skip vesting checks for mints, burns, and controller operations
999 if (from == address(0) || to == address(0) || msg.sender == controller) {
1000 super._update(from, to, amount);
1001 return;
1002 }
1003
1004 VestingSchedule storage schedule = vestingOf[from];
1005
1006 // No vesting schedule = normal transfer
1007 if (schedule.totalAmount == 0) {
1008 super._update(from, to, amount);
1009 return;
1010 }
1011
1012 // Before cliff = no transfers allowed
1013 if (block.timestamp < schedule.cliff) revert CliffNotReached();
1014
1015 // Check transferable amount
1016 uint256 transferable = transferableOf(from);
1017 if (amount > transferable) revert InsufficientVestedBalance();
1018
1019 // Track released amount for accounting
1020 schedule.released += amount;
1021
1022 super._update(from, to, amount);
1023 }
1024}
1025```
1026
1027**Key Design Decisions**:
1028- Vesting is per-address, set by project owner after minting
1029- No vesting schedule = freely transferable (normal ERC20 behavior)
1030- Cliff period: no transfers until cliff is reached
1031- Linear vesting after cliff
1032- Controller operations (mint/burn for payments/cash outs) bypass vesting
1033
1034**Usage Pattern**:
1035```solidity
1036// 1. Deploy and set as project token
1037VestingProjectToken token = new VestingProjectToken(...);
1038CONTROLLER.setTokenFor(projectId, IJBToken(address(token)));
1039
1040// 2. Team member receives tokens via payment or reserved distribution
1041// (tokens minted by controller - no vesting restriction on mint)
1042
1043// 3. Project owner sets vesting schedule
1044token.setVestingSchedule(
1045 teamMember,
1046 1_000_000e18, // 1M tokens vest
1047 uint40(block.timestamp), // Start now
1048 365 days, // 1 year cliff
1049 4 * 365 days // 4 year total vest
1050);
1051
1052// Result:
1053// - Year 0-1: 0 tokens transferable (cliff)
1054// - Year 1: 250k tokens transferable (25% vested)
1055// - Year 2: 500k tokens transferable (50% vested)
1056// - Year 4+: All tokens transferable
1057```
1058
1059**Combining with Treasury Vesting**:
1060
1061| Layer | Protects | Mechanism |
1062|-------|----------|-----------|
1063| Token vesting | Holder's tokens | Transfer restrictions |
1064| Treasury vesting | Treasury funds | Payout limits |
1065
1066For comprehensive protection, use both:
10671. **Treasury vesting** (Pattern 1): Prevents premature fund withdrawal
10682. **Token vesting**: Prevents premature token sales by recipients
1069
1070**When to Use Token Vesting vs Treasury Vesting**:
1071
1072| Scenario | Use Token Vesting | Use Treasury Vesting |
1073|----------|-------------------|---------------------|
1074| Team allocations with cliff | ✅ | Optional |
1075| Investor lock-ups | ✅ | Optional |
1076| Recurring payroll/grants | ❌ | ✅ |
1077| Milestone-based releases | ❌ | ✅ |
1078| All-holder protection | ❌ | ✅ |
1079| Per-person schedules | ✅ | ❌ |
1080
1081**Tradeoffs**:
1082- Adds complexity vs standard token
1083- Vesting schedules are permanent once set
1084- Does not prevent cash outs (controller operations are exempt)
1085- Must set schedule after minting, not before
1086
1087---
1088
1089### Example: Concentration Limited Token
1090
1091Prevent any single holder from accumulating too large a share:
1092
1093```solidity
1094// SPDX-License-Identifier: MIT
1095pragma solidity ^0.8.23;
1096
1097import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
1098
1099contract ConcentrationLimitedToken is ERC20 {
1100 uint256 public maxHolderBps = 200; // 2% max per holder
1101 address public immutable controller;
1102 uint256 public immutable projectId;
1103 mapping(address => bool) public isExempt;
1104
1105 constructor(
1106 string memory name,
1107 string memory symbol,
1108 address _controller,
1109 uint256 _projectId
1110 ) ERC20(name, symbol) {
1111 controller = _controller;
1112 projectId = _projectId;
1113 isExempt[_controller] = true; // Controller always exempt
1114 }
1115
1116 function decimals() public pure override returns (uint8) { return 18; }
1117
1118 function canBeAddedTo(uint256 _projectId) external view returns (bool) {
1119 return _projectId == projectId;
1120 }
1121
1122 function mint(address to, uint256 amount) external {
1123 require(msg.sender == controller, "UNAUTHORIZED");
1124 _mint(to, amount);
1125 }
1126
1127 function burn(address from, uint256 amount) external {
1128 require(msg.sender == controller, "UNAUTHORIZED");
1129 _burn(from, amount);
1130 }
1131
1132 function _update(address from, address to, uint256 amount) internal override {
1133 // Skip checks for mints, burns, and exempt addresses
1134 if (from == address(0) || to == address(0) || isExempt[to]) {
1135 super._update(from, to, amount);
1136 return;
1137 }
1138
1139 // Check concentration limit
1140 uint256 maxBalance = (totalSupply() * maxHolderBps) / 10000;
1141 require(balanceOf(to) + amount <= maxBalance, "EXCEEDS_MAX_HOLDING");
1142
1143 super._update(from, to, amount);
1144 }
1145
1146 function setExempt(address account, bool exempt) external {
1147 require(msg.sender == controller, "UNAUTHORIZED");
1148 isExempt[account] = exempt;
1149 }
1150}
1151```
1152
1153**Use cases**:
1154- Encourage broad token distribution
1155- Prevent governance centralization
1156- Reduce market manipulation risk
1157
1158**Tradeoff**: Liquidity pools and the controller must be marked exempt. New holders during early high-supply periods may hit limits before supply grows.
1159
1160### When to Use This Pattern
1161
1162| Use Case | Custom Token? | Alternative |
1163|----------|---------------|-------------|
1164| Simple fundraising | No | Use credits or JBERC20 |
1165| Transfer fees/taxes | **Yes** | - |
1166| Rebasing mechanics | **Yes** | - |
1167| Governance voting | **Yes** | External governance |
1168| Pre-existing token | **Yes** | Migrate to new project |
1169| Per-holder token vesting | **Yes** | - |
1170| Treasury fund vesting | No | Use payout limits (Pattern 1) |
1171| Compliance restrictions | **Yes** | - |
1172| Editable name/symbol | **Yes** | Redeploy token |
1173| Concentration limits | **Yes** | - |
1174
1175### Key Tradeoffs
1176
1177| Aspect | Standard Token | Custom Token |
1178|--------|----------------|--------------|
1179| Complexity | Low | High |
1180| Audit burden | Audited by JB | Your responsibility |
1181| Gas costs | Optimized | Variable |
1182| Integration | Seamless | Requires testing |
1183| Flexibility | Limited | Full control |
1184| Risk | Low | Higher (custom code) |
1185
1186### Critical Constraints
1187
11881. **18 decimals mandatory** - All Juicebox math assumes 18 decimals
11892. **Controller must be authorized** - Mint/burn must work without approval
11903. **One token per project** - Can't swap tokens after setting
11914. **totalSupply() accuracy** - Cash outs depend on correct supply
11925. **No fee-on-transfer during mint** - Minted amount must equal requested
1193
1194### Deployment Checklist
1195
1196- [ ] Token implements `canBeAddedTo(projectId)` returning true
1197- [ ] Token uses exactly 18 decimals
1198- [ ] Controller address authorized for mint()
1199- [ ] Controller address authorized for burn() (without approval)
1200- [ ] Custom logic (taxes, limits) exempts controller operations
1201- [ ] Tested with Juicebox payment flow
1202- [ ] Tested with Juicebox cash out flow
1203- [ ] Tested credit claiming after token is set
1204- [ ] Security audit completed (recommended)
1205
1206---
1207
1208## Decision Tree: When to Write Custom Code
1209
1210```
1211Need custom payment logic?
1212├── Can 721 hook handle it? → Use 721 hook
1213├── Can buyback hook handle it? → Use buyback hook
1214└── Neither works? → Write custom pay hook
1215
1216Need custom redemption logic?
1217├── Does 721 hook's burn-to-redeem work? → Use 721 hook
1218├── Is redemption just against surplus? → Use native cash out
1219└── Need external data source? → Write custom cash out hook
1220
1221Need custom payout routing?
1222├── Can direct beneficiary addresses work? → Use native splits
1223├── Need token swapping? → Write split hook
1224├── Need LP deposits? → Write split hook
1225└── Just multi-recipient? → Use native splits
1226
1227Need vesting/time-locks?
1228├── Treasury funds over time? → Use cycling rulesets + payout limits
1229├── Milestone-based releases? → Queue multiple rulesets
1230├── Per-holder token locks? → Custom ERC20 with vesting schedules
1231├── Investor/team cliffs? → Custom ERC20 with vesting schedules
1232└── Complex conditions? → Consider Revnet or custom
1233
1234Need time-limited campaign?
1235├── Fundraise then close forever? → Two rulesets (active + paused)
1236├── Want immutability? → Burn ownership after deploy
1237└── May run another campaign? → Keep ownership
1238
1239Need custom NFT content?
1240├── Static images per tier? → Use encodedIPFSUri in tier config
1241├── Dynamic/generative art? → Write IJB721TokenUriResolver
1242├── Composable/layered NFTs? → Write IJB721TokenUriResolver
1243└── On-chain SVG? → Write IJB721TokenUriResolver
1244
1245Need prediction/game mechanics?
1246├── Fixed redemption values? → Use standard 721-hook
1247├── Outcome-based payouts? → Extend 721-hook (Defifa pattern)
1248├── On-chain outcome voting? → Add Governor contract
1249└── First-owner rewards? → Track in custom delegate
1250
1251Need custom token mechanics?
1252├── Standard ERC20 sufficient? → Use deployERC20For()
1253├── Transfer taxes/fees? → Custom ERC20 with _update override
1254├── Governance voting? → Custom ERC20Votes
1255├── Rebasing/elastic supply? → Custom ERC20 (careful with totalSupply)
1256├── Editable name/symbol? → Custom ERC20 with setName/setSymbol
1257├── Concentration limits? → Custom ERC20 with max holder checks
1258├── Per-holder vesting/cliffs? → Custom ERC20 with vesting schedules
1259└── Pre-existing token? → Wrap with IJBToken interface
1260
1261Need extended pay functionality on locked project/revnet?
1262├── Dynamic splits at pay time? → Terminal wrapper
1263├── Atomic pay + distribute? → Terminal wrapper
1264├── Token interception/staking? → Terminal wrapper (beneficiary-to-self)
1265├── Multi-hop payments? → Terminal wrapper
1266├── Block certain payments? → CAN'T DO (permissionless is a feature)
1267└── Standard payments work fine? → Use MultiTerminal directly
1268```
1269
1270---
1271
1272## Anti-Patterns to Avoid
1273
1274### 1. Wrapping the 721 Hook
1275
1276**Wrong**: Creating a data hook that wraps/delegates to 721 hook
1277**Right**: Use 721 hook directly, achieve vesting via ruleset configuration
1278
1279### 2. Custom Vesting Contracts for Treasury Funds
1280
1281**Wrong**: Writing a VestingSplitHook to hold and release funds
1282**Right**: Use payout limits (reset each cycle) for recurring distributions
1283
1284**Exception**: Per-holder token vesting (team cliffs, investor locks) IS appropriate as a custom ERC20. See Pattern 8 - Vesting Token.
1285
1286### 3. Multiple Queued Rulesets for Simple Cycles
1287
1288**Wrong**: Queueing 12 rulesets for 12-month vesting
1289**Right**: One ruleset with 30-day duration that cycles automatically
1290
1291### 4. Split Hooks for Direct Transfers
1292
1293**Wrong**: Split hook that just forwards to an address
1294**Right**: Set the address as direct split beneficiary
1295
1296### 5. Custom Cash Out Hooks for Standard Redemptions
1297
1298**Wrong**: Writing hook to calculate pro-rata redemption
1299**Right**: Set `cashOutTaxRate: 0` and let terminal handle it
1300
1301---
1302
1303## Pattern 9: Time-Limited Campaign
1304
1305**Use case**: Fundraise for a specific period, then close payments permanently
1306
1307**Solution**: Deploy with two queued rulesets - active campaign, then paused
1308
1309### Why This Pattern?
1310
1311Many projects don't need ongoing payments forever. A time-limited campaign is cleaner:
1312- Crowdfunds with a deadline
1313- NFT mints with a defined window
1314- Grant rounds with cutoff dates
1315- "Set it and forget it" treasuries
1316
1317### Configuration
1318
1319```solidity
1320// Ruleset 1: Active Campaign
1321JBRulesetConfig({
1322 duration: 30 days, // Campaign length
1323 weight: 1e18, // Token issuance rate
1324 decayPercent: 0,
1325 approvalHook: IJBRulesetApprovalHook(address(0)),
1326 metadata: JBRulesetMetadata({
1327 // ... normal settings
1328 pausePay: false, // Payments ENABLED
1329 }),
1330 // ... splits, fund access, etc.
1331});
1332
1333// Ruleset 2: Campaign End (queued immediately)
1334JBRulesetConfig({
1335 duration: 0, // Lasts forever
1336 weight: 0, // No more tokens issued
1337 decayPercent: 0,
1338 approvalHook: IJBRulesetApprovalHook(address(0)),
1339 metadata: JBRulesetMetadata({
1340 pausePay: true, // Payments DISABLED
1341 // Keep cash outs enabled if desired
1342 }),
1343 // No payout limits needed - campaign is over
1344});
1345```
1346
1347### Ownership Options
1348
1349After deployment, the project owner decides:
1350
1351**Option A: Keep Ownership**
1352- Can queue new rulesets later (run another campaign)
1353- Can adjust splits or fund access
1354- Maintains flexibility
1355
1356**Option B: Lock Forever**
1357```solidity
1358// Transfer ownership to burn address
1359PROJECTS.transferFrom(
1360 deployer,
1361 0x000000000000000000000000000000000000dEaD,
1362 projectId
1363);
1364```
1365- No one can ever change the rules
1366- Fully trustless and immutable
1367- Cannot be undone
1368
1369### Complete Flow
1370
1371```
1372Deploy with 2 rulesets
1373 │
1374 ▼
1375┌─────────────────────────────────────┐
1376│ Ruleset 1: Active Campaign │
1377│ ├── Duration: 30 days │
1378│ ├── Payments: enabled │
1379│ └── Tokens issued to payers │
1380└─────────────────────────────────────┘
1381 │
1382 │ (30 days pass automatically)
1383 ▼
1384┌─────────────────────────────────────┐
1385│ Ruleset 2: Campaign Over │
1386│ ├── Duration: forever │
1387│ ├── Payments: paused │
1388│ └── Cash outs still work │
1389└─────────────────────────────────────┘
1390 │
1391 ▼
1392 Owner decides:
1393 ├── Keep ownership → can modify later
1394 └── Burn ownership → locked forever
1395```
1396
1397### When to Use
1398
1399| Scenario | Good Fit? |
1400|----------|-----------|
1401| One-time crowdfund | ✅ |
1402| NFT mint with deadline | ✅ |
1403| Grant distribution round | ✅ |
1404| Ongoing membership/subscription | ❌ Use cycling rulesets |
1405| Revnet with autonomous issuance | ❌ Use Revnet deployer |
1406
1407### Key Benefits
1408
14091. **Simple** - Just two rulesets, no custom contracts
14102. **Clear expectations** - Everyone knows when it ends
14113. **Optional immutability** - Lock it or keep flexibility
14124. **No ongoing management** - Set and forget
1413
1414---
1415
1416## Pattern 10: Terminal Wrapper (Pay Wrapper)
1417
1418**Use case**: Extend payment functionality without modifying rulesets - especially for revnets where hooks can't be edited
1419
1420**Solution**: Create an `IJBTerminal` that wraps `JBMultiTerminal`, like Swap Terminal does
1421
1422### Why This Pattern?
1423
1424Revnets and locked projects can't modify ruleset data hooks. But you can still add functionality by wrapping the terminal:
1425
1426| Need | How Wrapper Solves It |
1427|------|----------------------|
1428| Dynamic splits at pay time | Parse from metadata, configure before forwarding |
1429| Pay + distribute atomically | Bundle operations in one tx |
1430| Token interception | Set beneficiary to wrapper, then stake/forward |
1431| Referral tracking | Parse referrer from metadata, record on-chain |
1432| Multi-hop payments | Receive tokens, swap, pay another project |
1433
1434### Core Architecture
1435
1436```solidity
1437contract PayWithSplitsTerminal is IJBTerminal {
1438 IJBMultiTerminal public immutable MULTI_TERMINAL;
1439 IJBController public immutable CONTROLLER;
1440
1441 function pay(
1442 uint256 projectId,
1443 address token,
1444 uint256 amount,
1445 address beneficiary,
1446 uint256 minReturnedTokens,
1447 string calldata memo,
1448 bytes calldata metadata
1449 ) external payable returns (uint256 beneficiaryTokenCount) {
1450 // 1. Parse custom metadata
1451 (JBSplit[] memory splits, bytes memory innerMetadata) = _parseMetadata(metadata);
1452
1453 // 2. Configure splits if provided
1454 if (splits.length > 0) {
1455 _configureSplits(projectId, splits);
1456 }
1457
1458 // 3. Forward to underlying terminal
1459 beneficiaryTokenCount = MULTI_TERMINAL.pay{value: msg.value}(
1460 projectId, token, amount, beneficiary,
1461 minReturnedTokens, memo, innerMetadata
1462 );
1463
1464 // 4. Distribute reserved tokens
1465 CONTROLLER.sendReservedTokensToSplitsOf(projectId);
1466
1467 return beneficiaryTokenCount;
1468 }
1469}
1470```
1471
1472### Beneficiary-to-Self Pattern
1473
1474Intercept tokens by making the wrapper the beneficiary:
1475
1476```solidity
1477function payAndStake(uint256 projectId, ..., bytes calldata metadata) external payable {
1478 (address finalDestination, bytes memory stakingParams) = abi.decode(metadata, (address, bytes));
1479
1480 // Wrapper receives tokens
1481 uint256 tokenCount = MULTI_TERMINAL.pay{value: msg.value}(
1482 projectId, token, amount,
1483 address(this), // <-- Beneficiary is wrapper
1484 minReturnedTokens, "", ""
1485 );
1486
1487 // Do something with them
1488 _stakeTokens(projectToken, tokenCount, finalDestination, stakingParams);
1489}
1490```
1491
1492### Critical Mental Model
1493
1494```
1495┌─────────────────────────────────────────────────────────────────┐
1496│ WRAPPER IS ADDITIVE │
1497├─────────────────────────────────────────────────────────────────┤
1498│ Client A ──► PayWrapper ──► JBMultiTerminal │
1499│ (gets special features) │
1500│ │
1501│ Client B ─────────────────► JBMultiTerminal │
1502│ (still works!) │
1503│ │
1504│ BOTH ARE VALID. Wrapper cannot block direct access. │
1505│ This is a FEATURE. Permissionless = good. │
1506└─────────────────────────────────────────────────────────────────┘
1507```
1508
1509**Bad thinking**: "I'll use a wrapper to block payments that don't meet criteria X"
1510
1511**Good thinking**: "I'll provide enhanced functionality for clients that opt in"
1512
1513### Comparison with Swap Terminal
1514
1515Swap Terminal is the canonical example:
1516
1517```
1518User pays USDC ──► SwapTerminal ──► Swaps to ETH ──► JBMultiTerminal
1519```
1520
1521Your wrapper follows the same architecture with different transformation logic.
1522
1523### Cash Out Wrappers
1524
1525The same pattern applies to cash outs. Wrap `cashOutTokensOf` to intercept redeemed funds:
1526
1527```solidity
1528/// @notice Cash out with automatic bridging of redeemed funds.
1529function cashOutAndBridge(
1530 address holder,
1531 uint256 projectId,
1532 uint256 tokenCount,
1533 address tokenToReclaim,
1534 uint256 minTokensReclaimed,
1535 address beneficiary,
1536 uint256 destChainId, // Custom: where to bridge
1537 bytes calldata metadata
1538) external returns (uint256 reclaimAmount) {
1539 // 1. Cash out to THIS contract (intercept funds)
1540 reclaimAmount = MULTI_TERMINAL.cashOutTokensOf(
1541 holder,
1542 projectId,
1543 tokenCount,
1544 tokenToReclaim,
1545 minTokensReclaimed,
1546 address(this), // <-- Wrapper receives funds
1547 metadata
1548 );
1549
1550 // 2. Bridge the redeemed funds to destination chain
1551 _bridgeFunds(tokenToReclaim, reclaimAmount, beneficiary, destChainId);
1552
1553 return reclaimAmount;
1554}
1555
1556/// @notice Cash out with automatic swap to different token.
1557function cashOutAndSwap(
1558 address holder,
1559 uint256 projectId,
1560 uint256 tokenCount,
1561 address tokenToReclaim,
1562 uint256 minTokensReclaimed,
1563 address tokenOut, // Custom: swap to this token
1564 uint256 minAmountOut, // Custom: slippage protection
1565 address beneficiary,
1566 bytes calldata metadata
1567) external returns (uint256 amountOut) {
1568 // 1. Cash out to this contract
1569 uint256 reclaimAmount = MULTI_TERMINAL.cashOutTokensOf(
1570 holder,
1571 projectId,
1572 tokenCount,
1573 tokenToReclaim,
1574 minTokensReclaimed,
1575 address(this),
1576 metadata
1577 );
1578
1579 // 2. Swap redeemed tokens
1580 amountOut = _swap(tokenToReclaim, tokenOut, reclaimAmount, minAmountOut);
1581
1582 // 3. Send swapped tokens to beneficiary
1583 _sendFunds(tokenOut, amountOut, beneficiary);
1584
1585 return amountOut;
1586}
1587```
1588
1589### When to Use
1590
1591| Scenario | Terminal Wrapper? | Alternative |
1592|----------|-------------------|-------------|
1593| **Pay Wrappers** | | |
1594| Revnet needs new pay-time features | **Yes** | Can't modify hooks |
1595| Dynamic splits specified by payer | **Yes** | Native splits are static |
1596| Atomic pay + distribute | **Yes** | Two separate txs |
1597| Token interception/staking | **Yes** | - |
1598| **Cash Out Wrappers** | | |
1599| Cash out + bridge in one tx | **Yes** | Two separate txs |
1600| Cash out + swap to different token | **Yes** | Manual swap after |
1601| Cash out + stake redeemed funds | **Yes** | - |
1602| Cash out + LP deposit | **Yes** | - |
1603| **Both** | | |
1604| Simple operations with existing hooks | No | Use MultiTerminal directly |
1605| Need to block payments/cashouts | **No** | Wrappers can't enforce this |
1606
1607### Complete Example: Pay-Time Splits Terminal
1608
1609```solidity
1610// SPDX-License-Identifier: MIT
1611pragma solidity ^0.8.23;
1612
1613import {IJBTerminal} from "@bananapus/core/src/interfaces/IJBTerminal.sol";
1614import {IJBMultiTerminal} from "@bananapus/core/src/interfaces/IJBMultiTerminal.sol";
1615import {IJBController} from "@bananapus/core/src/interfaces/IJBController.sol";
1616import {JBSplit} from "@bananapus/core/src/structs/JBSplit.sol";
1617import {JBSplitGroup} from "@bananapus/core/src/structs/JBSplitGroup.sol";
1618import {JBConstants} from "@bananapus/core/src/libraries/JBConstants.sol";
1619import {JBPermissionIds} from "@bananapus/permission-ids/src/JBPermissionIds.sol";
1620import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
1621import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
1622
1623/// @notice Terminal wrapper that allows payers to specify reserved token splits at pay time.
1624/// @dev Useful for revnets where ruleset hooks can't be modified post-deploy.
1625/// @dev Follows JBSwapTerminalRegistry pattern with shared _acceptFunds helper.
1626contract PayWithSplitsTerminal is IJBTerminal {
1627 using SafeERC20 for IERC20;
1628
1629 // ═══════════════════════════════════════════════════════════════════════
1630 // ERRORS
1631 // ═══════════════════════════════════════════════════════════════════════
1632
1633 error InvalidSplitTotal();
1634
1635 // ═══════════════════════════════════════════════════════════════════════
1636 // CONSTANTS
1637 // ═══════════════════════════════════════════════════════════════════════
1638
1639 /// @notice Split group ID for reserved tokens.
1640 uint256 public constant RESERVED_TOKEN_GROUP = 1;
1641
1642 /// @notice The underlying terminal this wrapper forwards to.
1643 IJBMultiTerminal public immutable MULTI_TERMINAL;
1644
1645 /// @notice The controller for setting splits and distributing reserved tokens.
1646 IJBController public immutable CONTROLLER;
1647
1648 // ═══════════════════════════════════════════════════════════════════════
1649 // CONSTRUCTOR
1650 // ═══════════════════════════════════════════════════════════════════════
1651
1652 /// @param _multiTerminal The JBMultiTerminal to wrap.
1653 /// @param _controller The JBController for this deployment.
1654 constructor(IJBMultiTerminal _multiTerminal, IJBController _controller) {
1655 MULTI_TERMINAL = _multiTerminal;
1656 CONTROLLER = _controller;
1657 }
1658
1659 // ═══════════════════════════════════════════════════════════════════════
1660 // EXTERNAL FUNCTIONS
1661 // ═══════════════════════════════════════════════════════════════════════
1662
1663 /// @notice Pay a project with optional dynamic splits specified in metadata.
1664 /// @dev If metadata contains splits, they're applied before payment. Reserved tokens
1665 /// are distributed after payment completes.
1666 /// @param projectId The project to pay.
1667 /// @param token The token to pay with (JBConstants.NATIVE_TOKEN for ETH).
1668 /// @param amount The amount to pay (ignored for ETH, uses msg.value).
1669 /// @param beneficiary Who receives the project tokens.
1670 /// @param minReturnedTokens Minimum tokens to receive (slippage protection).
1671 /// @param memo Payment memo.
1672 /// @param metadata ABI-encoded (JBSplit[] splits, bytes innerMetadata).
1673 /// - splits: Reserved token split configuration (empty array to skip)
1674 /// - innerMetadata: Passed through to MultiTerminal (for hooks, etc.)
1675 /// @return beneficiaryTokenCount The number of tokens minted to beneficiary.
1676 function pay(
1677 uint256 projectId,
1678 address token,
1679 uint256 amount,
1680 address beneficiary,
1681 uint256 minReturnedTokens,
1682 string calldata memo,
1683 bytes calldata metadata
1684 ) external payable returns (uint256 beneficiaryTokenCount) {
1685 bytes memory innerMetadata;
1686
1687 // Parse and apply splits if metadata provided
1688 if (metadata.length > 0) {
1689 JBSplit[] memory splits;
1690 (splits, innerMetadata) = abi.decode(metadata, (JBSplit[], bytes));
1691
1692 if (splits.length > 0) {
1693 _validateAndSetSplits(projectId, splits);
1694 }
1695 }
1696
1697 // Accept funds and get value to forward
1698 uint256 valueToSend = _acceptFunds(token, amount, address(MULTI_TERMINAL));
1699
1700 // Forward payment to MultiTerminal
1701 beneficiaryTokenCount = MULTI_TERMINAL.pay{value: valueToSend}(
1702 projectId,
1703 token,
1704 amount,
1705 beneficiary,
1706 minReturnedTokens,
1707 memo,
1708 innerMetadata
1709 );
1710
1711 // Distribute reserved tokens to the configured splits
1712 CONTROLLER.sendReservedTokensToSplitsOf(projectId);
1713
1714 return beneficiaryTokenCount;
1715 }
1716
1717 /// @notice Add to a project's balance without receiving tokens.
1718 /// @dev Pass-through to MultiTerminal.
1719 function addToBalanceOf(
1720 uint256 projectId,
1721 address token,
1722 uint256 amount,
1723 bool shouldReturnHeldFees,
1724 string calldata memo,
1725 bytes calldata metadata
1726 ) external payable {
1727 // Accept funds and get value to forward
1728 uint256 valueToSend = _acceptFunds(token, amount, address(MULTI_TERMINAL));
1729
1730 MULTI_TERMINAL.addToBalanceOf{value: valueToSend}(
1731 projectId,
1732 token,
1733 amount,
1734 shouldReturnHeldFees,
1735 memo,
1736 metadata
1737 );
1738 }
1739
1740 /// @notice Check accounting contexts accepted by underlying terminal.
1741 function accountingContextForTokenOf(
1742 uint256 projectId,
1743 address token
1744 ) external view returns (JBAccountingContext memory) {
1745 return MULTI_TERMINAL.accountingContextForTokenOf(projectId, token);
1746 }
1747
1748 /// @notice Get all accounting contexts for a project.
1749 function accountingContextsOf(
1750 uint256 projectId
1751 ) external view returns (JBAccountingContext[] memory) {
1752 return MULTI_TERMINAL.accountingContextsOf(projectId);
1753 }
1754
1755 /// @notice Get current surplus in a project's terminal.
1756 function currentSurplusOf(
1757 uint256 projectId,
1758 JBAccountingContext[] calldata accountingContexts,
1759 uint256 decimals,
1760 uint256 currency
1761 ) external view returns (uint256) {
1762 return MULTI_TERMINAL.currentSurplusOf(
1763 projectId,
1764 accountingContexts,
1765 decimals,
1766 currency
1767 );
1768 }
1769
1770 // ═══════════════════════════════════════════════════════════════════════
1771 // INTERNAL FUNCTIONS
1772 // ═══════════════════════════════════════════════════════════════════════
1773
1774 /// @notice Accept funds from the caller and prepare them for forwarding.
1775 /// @dev For ERC20s: transfers from sender, approves spender.
1776 /// @dev For ETH: returns msg.value to forward.
1777 /// @dev Pattern from JBSwapTerminalRegistry - consolidates token handling.
1778 /// @param token The token being paid (NATIVE_TOKEN for ETH).
1779 /// @param amount The amount being paid.
1780 /// @param spender The address that will spend the tokens (the terminal).
1781 /// @return valueToSend The ETH value to forward (0 for ERC20s).
1782 function _acceptFunds(
1783 address token,
1784 uint256 amount,
1785 address spender
1786 ) internal returns (uint256 valueToSend) {
1787 if (token == JBConstants.NATIVE_TOKEN) {
1788 // For ETH, just return msg.value to forward
1789 return msg.value;
1790 }
1791
1792 // For ERC20s: pull tokens from sender
1793 IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
1794
1795 // Approve the spender (terminal) to pull tokens
1796 IERC20(token).forceApprove(spender, amount);
1797
1798 // No ETH to forward for ERC20 payments
1799 return 0;
1800 }
1801
1802 /// @notice Validate splits sum to 100% and set them on the controller.
1803 /// @dev This wrapper must have SET_SPLIT_GROUPS permission on the project.
1804 function _validateAndSetSplits(uint256 projectId, JBSplit[] memory splits) internal {
1805 // Validate splits sum to 100%
1806 uint256 total;
1807 for (uint256 i; i < splits.length; i++) {
1808 total += splits[i].percent;
1809 }
1810 if (total != JBConstants.SPLITS_TOTAL_PERCENT) revert InvalidSplitTotal();
1811
1812 // Get current ruleset ID
1813 (JBRuleset memory ruleset,) = CONTROLLER.currentRulesetOf(projectId);
1814
1815 // Build split group
1816 JBSplitGroup[] memory groups = new JBSplitGroup[](1);
1817 groups[0] = JBSplitGroup({
1818 groupId: RESERVED_TOKEN_GROUP,
1819 splits: splits
1820 });
1821
1822 // Set splits (requires SET_SPLIT_GROUPS permission)
1823 CONTROLLER.setSplitGroupsOf(projectId, ruleset.id, groups);
1824 }
1825
1826 /// @notice Required for receiving ETH refunds from terminal.
1827 receive() external payable {}
1828}
1829```
1830
1831### Client-Side Usage (TypeScript)
1832
1833```typescript
1834import {
1835 encodeFunctionData,
1836 encodeAbiParameters,
1837 parseAbiParameters,
1838 parseUnits,
1839 Address
1840} from 'viem';
1841
1842const SPLITS_TOTAL_PERCENT = 1_000_000_000n; // 1e9
1843
1844// Build split configuration
1845function encodeSplits(recipients: { address: Address; percent: number }[]) {
1846 // Convert percentages (0-100) to JB format (0-1e9)
1847 const splits = recipients.map(r => ({
1848 preferredProjectId: 0n,
1849 preferredBeneficiary: r.address,
1850 percent: BigInt(Math.floor(r.percent * 10_000_000)), // 1% = 10_000_000
1851 lockedUntil: 0n,
1852 hook: '0x0000000000000000000000000000000000000000' as Address,
1853 }));
1854
1855 return splits;
1856}
1857
1858// Encode metadata for pay call
1859function encodePayMetadata(
1860 splits: ReturnType<typeof encodeSplits>,
1861 innerMetadata: `0x${string}` = '0x'
1862) {
1863 return encodeAbiParameters(
1864 parseAbiParameters([
1865 '(uint256 preferredProjectId, address preferredBeneficiary, uint256 percent, uint256 lockedUntil, address hook)[]',
1866 'bytes'
1867 ]),
1868 [splits, innerMetadata]
1869 );
1870}
1871
1872// Example: Pay with dynamic splits
1873async function payWithSplits(
1874 walletClient: WalletClient,
1875 wrapperAddress: Address,
1876 projectId: bigint,
1877 paymentAmount: bigint,
1878 recipients: { address: Address; percent: number }[]
1879) {
1880 const splits = encodeSplits(recipients);
1881 const metadata = encodePayMetadata(splits);
1882
1883 const NATIVE_TOKEN = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
1884
1885 const hash = await walletClient.writeContract({
1886 address: wrapperAddress,
1887 abi: PAY_WITH_SPLITS_ABI,
1888 functionName: 'pay',
1889 args: [
1890 projectId,
1891 NATIVE_TOKEN,
1892 paymentAmount,
1893 walletClient.account.address, // beneficiary
1894 0n, // minReturnedTokens
1895 'Payment with custom splits',
1896 metadata
1897 ],
1898 value: paymentAmount
1899 });
1900
1901 return hash;
1902}
1903
1904// Usage
1905await payWithSplits(
1906 walletClient,
1907 '0x...wrapper',
1908 3n, // projectId
1909 parseUnits('1', 18), // 1 ETH
1910 [
1911 { address: '0xaaa...', percent: 50 }, // 50% to address A
1912 { address: '0xbbb...', percent: 30 }, // 30% to address B
1913 { address: '0xccc...', percent: 20 }, // 20% to address C
1914 ]
1915);
1916```
1917
1918### Deployment & Permissions
1919
1920```solidity
1921// Deploy the wrapper
1922PayWithSplitsTerminal wrapper = new PayWithSplitsTerminal(
1923 IJBMultiTerminal(MULTI_TERMINAL_ADDRESS),
1924 IJBController(CONTROLLER_ADDRESS)
1925);
1926
1927// Grant SET_SPLIT_GROUPS permission to wrapper
1928// (Must be called by project owner or someone with SET_PERMISSIONS)
1929JBPermissionsData[] memory permissions = new JBPermissionsData[](1);
1930permissions[0] = JBPermissionsData({
1931 operator: address(wrapper),
1932 projectId: PROJECT_ID,
1933 permissionIds: _asSingletonArray(JBPermissionIds.SET_SPLIT_GROUPS)
1934});
1935
1936PERMISSIONS.setPermissionsFor(projectOwner, permissions);
1937```
1938
1939### Key Notes
1940
1941- Wrapper must be granted permissions if setting splits
1942- Multiple wrappers can exist for different purposes - they don't conflict
1943- Wrappers can be chained: WrapperA → WrapperB → MultiTerminal
1944- For revnets: often the ONLY way to add functionality post-deploy
1945- Validate metadata carefully - parsing adds attack surface
1946
1947---
1948
1949## Pattern 11: Yield-Generating Hook (Aave Integration)
1950
1951**Use case**: Deposit contributions to yield protocols (Aave, Compound, etc.), route yield to project balance while allowing principal cash-outs
1952
1953**Solution**: Combined pay/cash-out hook that deposits to Aave, tracks principal separately from yield
1954
1955### Why This Pattern?
1956
1957Create "YeeHaw" style funding where:
1958- Investor contributions earn yield via DeFi
1959- Investors can always cash out their principal
1960- Yield flows to project balance for team operations
1961- Clear separation between protected principal and operational yield
1962
1963### Architecture
1964
1965```
1966┌─────────────────────────────────────────────────────────────────┐
1967│ Payment Flow │
1968│ User pays → Hook deposits to Aave → Principal tracked │
1969│ │
1970│ Yield Flow │
1971│ Aave earns yield → Hook withdraws → addToBalanceOf() │
1972│ → Appears in project balance │
1973│ → Team uses sendPayoutsOf() │
1974│ │
1975│ Cash Out Flow │
1976│ User cashes out → Hook withdraws from Aave → Direct to user │
1977│ (bypasses terminal, separate from yield) │
1978└─────────────────────────────────────────────────────────────────┘
1979```
1980
1981### Core Hook Structure
1982
1983```solidity
1984contract YieldHook is IJBPayHook, IJBCashOutHook, IJBRulesetDataHook {
1985 IPool public immutable AAVE_POOL;
1986 IJBTerminal public immutable TERMINAL;
1987
1988 mapping(uint256 projectId => uint256) public principalDeposited;
1989 mapping(uint256 projectId => uint256) public principalWithdrawn;
1990 mapping(uint256 projectId => uint256) public yieldWithdrawn;
1991
1992 struct ProjectConfig {
1993 address principalToken; // USDC, ETH, etc.
1994 address aToken; // Corresponding aToken
1995 uint256 yieldThreshold; // Min yield before transfer
1996 bool active;
1997 }
1998}
1999```
2000
2001### Data Hook: Route Payments to Hook
2002
2003```solidity
2004function beforePayRecordedWith(
2005 JBBeforePayRecordedContext calldata context
2006) external view override returns (
2007 uint256 weight,
2008 JBPayHookSpecification[] memory hookSpecifications
2009) {
2010 weight = context.weight;
2011
2012 // Forward ALL payment funds to this hook for Aave deposit
2013 hookSpecifications = new JBPayHookSpecification[](1);
2014 hookSpecifications[0] = JBPayHookSpecification({
2015 hook: IJBPayHook(address(this)),
2016 amount: context.amount.value, // Must be explicit, not 0
2017 metadata: ""
2018 });
2019}
2020```
2021
2022### Pay Hook: Deposit to Aave
2023
2024```solidity
2025function afterPayRecordedWith(
2026 JBAfterPayRecordedContext calldata context
2027) external payable override {
2028 ProjectConfig storage config = projectConfigs[context.projectId];
2029 uint256 amount = context.forwardedAmount.value;
2030
2031 // Deposit to Aave
2032 IERC20(config.principalToken).forceApprove(address(AAVE_POOL), amount);
2033 AAVE_POOL.supply(config.principalToken, amount, address(this), 0);
2034
2035 // Track principal
2036 principalDeposited[context.projectId] += amount;
2037
2038 // Check if yield should be transferred
2039 _maybeTransferYield(context.projectId);
2040}
2041```
2042
2043### Cash Out Hook: Principal Withdrawal
2044
2045```solidity
2046function beforeCashOutRecordedWith(
2047 JBBeforeCashOutRecordedContext calldata context
2048) external view override returns (
2049 uint256 cashOutTaxRate,
2050 uint256 cashOutCount,
2051 uint256 totalSupply,
2052 JBCashOutHookSpecification[] memory hookSpecifications
2053) {
2054 // Calculate user's share of principal
2055 uint256 availablePrincipal = principalDeposited[context.projectId]
2056 - principalWithdrawn[context.projectId];
2057 uint256 userShare = (availablePrincipal * context.cashOutCount) / context.totalSupply;
2058
2059 cashOutTaxRate = 0; // No tax on principal
2060 cashOutCount = context.cashOutCount;
2061 totalSupply = context.totalSupply;
2062
2063 // Route to this hook for Aave withdrawal
2064 hookSpecifications = new JBCashOutHookSpecification[](1);
2065 hookSpecifications[0] = JBCashOutHookSpecification({
2066 hook: IJBCashOutHook(address(this)),
2067 amount: userShare,
2068 metadata: ""
2069 });
2070}
2071
2072function afterCashOutRecordedWith(
2073 JBAfterCashOutRecordedContext calldata context
2074) external payable override {
2075 ProjectConfig storage config = projectConfigs[context.projectId];
2076 uint256 amount = context.forwardedAmount.value;
2077
2078 // Withdraw principal from Aave directly to user
2079 AAVE_POOL.withdraw(config.principalToken, amount, context.beneficiary);
2080 principalWithdrawn[context.projectId] += amount;
2081}
2082```
2083
2084### Yield Management: Route to Project Balance
2085
2086```solidity
2087function _maybeTransferYield(uint256 projectId) internal {
2088 ProjectConfig storage config = projectConfigs[projectId];
2089 uint256 availableYield = _calculateAvailableYield(projectId);
2090
2091 if (availableYield >= config.yieldThreshold) {
2092 // Withdraw yield from Aave to this contract
2093 uint256 withdrawn = AAVE_POOL.withdraw(
2094 config.principalToken,
2095 availableYield,
2096 address(this)
2097 );
2098
2099 // Approve terminal
2100 IERC20(config.principalToken).forceApprove(address(TERMINAL), withdrawn);
2101
2102 // Add to project balance (team can then use sendPayoutsOf)
2103 TERMINAL.addToBalanceOf(
2104 projectId,
2105 config.principalToken,
2106 withdrawn,
2107 false, // shouldReturnHeldFees
2108 "", // memo
2109 "" // metadata
2110 );
2111
2112 yieldWithdrawn[projectId] += withdrawn;
2113 }
2114}
2115
2116function _calculateAvailableYield(uint256 projectId) internal view returns (uint256) {
2117 ProjectConfig storage config = projectConfigs[projectId];
2118 uint256 totalBalance = IERC20(config.aToken).balanceOf(address(this));
2119 uint256 principalRemaining = principalDeposited[projectId] - principalWithdrawn[projectId];
2120
2121 if (totalBalance > principalRemaining + yieldWithdrawn[projectId]) {
2122 return totalBalance - principalRemaining - yieldWithdrawn[projectId];
2123 }
2124 return 0;
2125}
2126```
2127
2128### Project Configuration
2129
2130```solidity
2131// Ruleset must enable data hooks
2132JBRulesetMetadata({
2133 useDataHookForPay: true, // Enable beforePay/afterPay
2134 useDataHookForCashOut: true, // Enable beforeCashOut/afterCashOut
2135 dataHook: address(yieldHook), // Your hook address
2136 // ...
2137});
2138```
2139
2140### When to Use
2141
2142| Scenario | Fits Pattern? |
2143|----------|---------------|
2144| Yield-backed funding | ✅ |
2145| Aave/Compound integration | ✅ |
2146| Principal-protected investing | ✅ |
2147| Staking rewards integration | ✅ (adapt for staking protocol) |
2148| Standard fundraising | ❌ Use native terminals |
2149| NFT-based funding | ❌ Use 721 hook |
2150
2151### Key Implementation Notes
2152
21531. **amount in JBPayHookSpecification**: Must be `context.amount.value` to forward funds, not 0
21542. **Yield routing**: Use `addToBalanceOf()` to add yield to project balance
21553. **Principal tracking**: Separate tracking for deposits vs withdrawals
21564. **Emergency fallback**: Include direct withdrawal function for emergencies
21575. **Gas optimization**: Use yield threshold to batch transfers
2158
2159### Reference
2160
2161- YeeHaw concept: Yield-backed crowdfunding
2162- Uses pattern from jb-yield-to-balance-pattern skill
2163
2164---
2165
2166## Reference Implementations
2167
2168- **Vesting + NFT**: Drip x Juicebox (see `/jb-project` for deployment script)
2169- **Autonomous Treasury**: Revnet (`revnet-core-v5`)
2170- **NFT Rewards**: Any project using `JB721TiersHookProjectDeployer`
2171- **Custom NFT Content**: [banny-retail-v5](https://github.com/mejango/banny-retail-v5) - composable SVG NFTs with outfit decoration
2172- **Prediction Games**: [defifa-collection-deployer-v5](https://github.com/BallKidz/defifa-collection-deployer-v5) - dynamic cash out weights with on-chain governance
2173- **Yield-Generating Hook**: YeeHaw concept - Aave integration for yield-backed funding
2174
2175## Related Skills
2176
2177- `/jb-simplify` - Checklist to reduce custom code
2178- `/jb-project` - Project deployment and configuration
2179- `/jb-ruleset` - Ruleset configuration details
2180- `/jb-v5-impl` - Deep implementation mechanics
2181- `/jb-terminal-wrapper` - Full terminal wrapper implementation details