@bananapus/core-v6 0.0.27 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ADMINISTRATION.md CHANGED
@@ -123,7 +123,7 @@ Admin privileges and their scope in nana-core-v6.
123
123
  |----------|--------------|---------------|-------|-------------|
124
124
  | `addAccountingContextsFor` | Project owner, operator, or the project's controller | ADD_ACCOUNTING_CONTEXTS (20) | Per project | Adds tokens that the terminal will accept for a project. Requires the ruleset's `allowAddAccountingContext` flag (if a ruleset exists). |
125
125
  | `cashOutTokensOf` | Token holder or operator | CASH_OUT_TOKENS (4) | Per project | Cashes out project tokens for a share of the project's surplus. Fees are charged unless the beneficiary is feeless or the cash out tax rate is zero. |
126
- | `migrateBalanceOf` | Project owner or operator | MIGRATE_TERMINAL (6) | Per project | Migrates a project's balance from this terminal to another. The destination terminal must accept the same token. The ruleset must have `allowTerminalMigration` enabled (checked in JBTerminalStore). |
126
+ | `migrateBalanceOf` | Project owner or operator | MIGRATE_TERMINAL (6) | Per project | Migrates a project's balance from this terminal to another. The destination terminal must accept the same token. The ruleset must have `allowTerminalMigration` enabled (checked in JBTerminalStore). The standard 2.5% protocol fee is charged when migrating to a non-feeless terminal. |
127
127
  | `sendPayoutsOf` | Anyone (unless `ownerMustSendPayouts` is set) | SEND_PAYOUTS (5) if `ownerMustSendPayouts` | Per project | Sends payouts to the project's payout split group up to the payout limit. Anyone can call unless the ruleset has `ownerMustSendPayouts` enabled, which requires the project owner or an operator with SEND_PAYOUTS permission. |
128
128
  | `useAllowanceOf` | Project owner or operator | USE_ALLOWANCE (17) | Per project | Withdraws funds from the project's surplus up to the surplus allowance. Fees are charged unless the owner or beneficiary is feeless. |
129
129
  | `pay` | Anyone | N/A | N/A | Pays a project with tokens. No permission required. |
@@ -88,7 +88,7 @@ Holder -> JBMultiTerminal.cashOutTokensOf()
88
88
  -> Fee skipped if beneficiary is feeless
89
89
  ```
90
90
 
91
- **Critical note**: The beneficiary receives the reclaim amount BEFORE cash out hooks execute. Fees are taken AFTER hooks. `_feeFreeSurplusOf[projectId][token]` accumulates the value of fee-free intra-terminal payouts. After any outflow (payouts, `useAllowanceOf`, non-zero-tax or feeless cashouts), the counter is capped at the remaining balance non-fee-free funds leave first. During zero-tax cashout, the 2.5% fee applies only up to this surplus amount (then depletes it), preventing a round-trip fee bypass. Cleared on terminal migration.
91
+ **Critical note**: The beneficiary receives the reclaim amount BEFORE cash out hooks execute. Fees are taken AFTER hooks. `_feeFreeSurplusOf[projectId][token]` accumulates the value of fee-free intra-terminal payouts. After any outflow (payouts, `useAllowanceOf`, non-zero-tax or feeless cashouts), the counter is capped at the remaining balance -- non-fee-free funds leave first. During zero-tax cashout, the 2.5% fee applies only up to this surplus amount (then depletes it), preventing a round-trip fee bypass. Cleared on terminal migration (the migration fee settles this liability).
92
92
 
93
93
  ### Payout Flow (`sendPayoutsOf`)
94
94
 
package/CHANGE_LOG.md CHANGED
@@ -48,6 +48,14 @@ Also in this release:
48
48
  - **`via_ir = true`**: Added to `foundry.toml` to enable the Solidity IR optimizer pipeline, reducing deployed bytecode size (EIP-170 compliance).
49
49
  - Internal helpers extracted: `_accountingContextOf` and `_tokenAmountOf` on `JBMultiTerminal`, `_splitTokenCount` on `JBController`.
50
50
 
51
+ ### 0.6 JBMultiTerminal -- Migration Fee
52
+
53
+ `migrateBalanceOf` now charges the standard 2.5% protocol fee when migrating to a non-feeless terminal, consistent with all other fund egress. This also settles any `_feeFreeSurplusOf` liability that would otherwise be lost on the new terminal. The fee is deducted from the migrated balance before transfer. Feeless terminals are exempt.
54
+
55
+ ### 0.7 JBMultiTerminal -- Self-Pay Revert
56
+
57
+ `_pay` now reverts with `JBMultiTerminal_MintNotAllowed()` when `payer == address(this)`. This prevents same-project intra-terminal payout splits (where `preferAddToBalance == false`) from minting tokens against existing balance without new funds entering the system. The try-catch in `JBPayoutSplitGroupLib` catches this revert and restores the balance via `recordAddedBalanceFor`. Projects that want to mint should do so explicitly via the controller.
58
+
51
59
  ---
52
60
 
53
61
  ## 1. Breaking Changes
@@ -182,6 +190,13 @@ Parameters changed from `memory` to `calldata` for gas efficiency.
182
190
 
183
191
  ## 3. Event Changes
184
192
 
193
+ ### 3.0 Indexer Notes
194
+
195
+ For subgraph migrations, this repo is the protocol-level anchor:
196
+ - when an event signature gains parameters, prefer widening the existing entity schema instead of treating it as an unrelated event stream;
197
+ - preview/noop behavior in core-v6 means some routing diagnostics now come from returned hook specs rather than only from emitted callback events;
198
+ - if your v5 graph correlated protocol actions to hook callbacks only, re-check those assumptions against v6 preview/noop patterns.
199
+
185
200
  ### 3.1 New Events
186
201
 
187
202
  See section 2.2 above.
package/RISKS.md CHANGED
@@ -52,13 +52,13 @@ No `ReentrancyGuard` is used. The system relies on state ordering and the `Inade
52
52
  | `processHeldFeesOf` | `delete _heldFeesOf[...][currentIndex]`, `_nextHeldFeeIndexOf` incremented | `_processFee` -> `this.executeProcessFee` -> `terminal.pay` | LOW -- index advanced before external call; re-reads from storage each iteration |
53
53
  | `_sendReservedTokensToSplitsOf` | `pendingReservedTokenBalanceOf` zeroed, tokens minted to controller | Split hooks, terminal payments | LOW -- pending balance cleared before minting prevents double-distribution |
54
54
  | `_useAllowanceOf` | `STORE.recordUsedAllowanceOf` (allowance consumed, balance decremented) | `_takeFeeFrom` (fee payment/holding), `_transferFrom` (beneficiary) | LOW -- allowance consumed before calls |
55
- | `migrateBalanceOf` | `STORE.recordTerminalMigration` (balance zeroed) | `to.addToBalanceOf` | LOW -- balance zeroed before transfer |
55
+ | `migrateBalanceOf` | `STORE.recordTerminalMigration` (balance zeroed), `_takeFeeFrom` (if non-feeless destination) | `to.addToBalanceOf` | LOW -- balance zeroed before transfer, fee deducted before transfer |
56
56
 
57
57
  ### Cross-Function Reentrancy to Explore
58
58
 
59
59
  - **Pay hook -> `cashOutTokensOf`**: After `_pay` mints tokens, a pay hook could call `cashOutTokensOf`. The cash out sees post-payment balance and post-mint supply. Not profitable after fees in tested scenarios, but verify with data hooks that modify weights.
60
60
  - **Cash out hook -> `pay`**: During `_cashOutTokensOf`, after tokens are burned and beneficiary is paid, a cash out hook could call `pay()` adding to the balance. Fees haven't been taken yet at this point. Verify the fee calculation on `amountEligibleForFees` isn't affected.
61
- - **Split hook -> `pay` on same project**: During `sendPayoutsOf`, a split hook receives funds and calls `pay()` on the same project. Payout limit is consumed, but the payment increases balance and mints tokens. The funds came from the project's own balance, so no value creation -- but verify the accounting.
61
+ - **Split hook -> `pay` on same project**: During `sendPayoutsOf`, a split hook receives funds and calls `pay()` on the same project. Payout limit is consumed, but the payment increases balance and mints tokens. The funds came from the project's own balance, so no value creation -- but verify the accounting. Note: `_pay` now reverts with `MintNotAllowed` when `payer == address(this)` to prevent same-project intra-terminal payout splits from minting tokens against existing balance. The try-catch in the split group lib catches this and restores the balance.
62
62
  - **Fee processing -> any re-entry**: `_processFee` uses `this.executeProcessFee` (external call via try-catch). Inside, it calls `terminal.pay()` on project #1. If project #1 has a pay hook that calls back, the fee amount is already deducted.
63
63
 
64
64
  ### Key Backstop
@@ -77,7 +77,7 @@ No `ReentrancyGuard` is used. The system relies on state ordering and the `Inade
77
77
  ### Migration
78
78
 
79
79
  - **Controller migration** requires `allowSetController` in the current ruleset. During migration, `JBController.migrate()` reverts if there are pending reserved tokens. An attacker cannot front-run migration to inflate pending reserves (they'd need mint permission), but a project with organic pending reserves must distribute them first.
80
- - **Terminal migration** requires `allowTerminalMigration` in the current ruleset. Held fees are intentionally NOT migrated -- they belong to project #1. Verify that a project owner cannot use migration to escape held fee obligations.
80
+ - **Terminal migration** requires `allowTerminalMigration` in the current ruleset. Held fees are intentionally NOT migrated -- they belong to project #1. Migration to a non-feeless terminal charges the standard 2.5% protocol fee on the full balance, settling any `_feeFreeSurplusOf` liability.
81
81
  - **Directory updates** (`setTerminalsOf`, `setControllerOf`) are gated by `IJBDirectoryAccessControl` checks that read from the current ruleset's metadata flags. If the current ruleset allows these changes, anyone with the appropriate permission can redirect all of a project's fund flows.
82
82
 
83
83
  ### Ruleset Queuing
package/USER_JOURNEYS.md CHANGED
@@ -300,15 +300,18 @@ All user paths through the Juicebox V6 core protocol. For each journey: entry po
300
300
  - `to` -- Destination terminal
301
301
 
302
302
  **State changes**:
303
- 1. `JBTerminalStore.balanceOf[oldTerminal][projectId][token]` set to 0
304
- 2. Funds transferred to destination terminal via `to.addToBalanceOf()`
305
- 3. Destination terminal records the added balance
303
+ 1. `_feeFreeSurplusOf[projectId][token]` cleared
304
+ 2. `JBTerminalStore.balanceOf[oldTerminal][projectId][token]` set to 0
305
+ 3. If destination is non-feeless: 2.5% protocol fee deducted from balance via `_takeFeeFrom`
306
+ 4. Remaining funds transferred to destination terminal via `to.addToBalanceOf()`
307
+ 5. Destination terminal records the added balance
306
308
 
307
309
  **Events**: `MigrateTerminal(projectId, token, to, amount, caller)`
308
310
 
309
311
  **Edge cases**:
310
312
  - Requires `allowTerminalMigration` in current ruleset
311
313
  - Destination terminal must have accounting context for the token (validated via `accountingContextForTokenOf`)
314
+ - **Standard 2.5% protocol fee** is charged when migrating to a non-feeless terminal, consistent with all other fund egress. This also settles any `_feeFreeSurplusOf` liability.
312
315
  - **Held fees are NOT transferred** -- they remain in the old terminal. Held fees belong to the fee beneficiary (project #1), not the migrating project.
313
316
  - If balance is 0, no transfer occurs
314
317
  - This only migrates one token's balance. Must be called once per token.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bananapus/core-v6",
3
- "version": "0.0.27",
3
+ "version": "0.0.28",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,14 +26,14 @@
26
26
  "artifacts": "source ./.env && npx sphinx artifacts --org-id 'ea165b21-7cdc-4d7b-be59-ecdd4c26bee4' --project-name 'nana-core-v6'"
27
27
  },
28
28
  "dependencies": {
29
- "@bananapus/address-registry-v6": "^0.0.15",
29
+ "@bananapus/address-registry-v6": "^0.0.16",
30
30
  "@bananapus/permission-ids-v6": "^0.0.14",
31
- "@chainlink/contracts": "^1.3.0",
31
+ "@chainlink/contracts": "^1.5.0",
32
32
  "@openzeppelin/contracts": "^5.6.1",
33
33
  "@prb/math": "^4.1.1",
34
34
  "@uniswap/permit2": "github:Uniswap/permit2"
35
35
  },
36
36
  "devDependencies": {
37
- "@sphinx-labs/plugins": "^0.33.2"
37
+ "@sphinx-labs/plugins": "^0.33.3"
38
38
  }
39
39
  }
@@ -59,6 +59,7 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
59
59
  //*********************************************************************//
60
60
 
61
61
  error JBMultiTerminal_FeeTerminalNotFound(address token);
62
+ error JBMultiTerminal_MintNotAllowed();
62
63
  error JBMultiTerminal_NoMsgValueAllowed(uint256 value);
63
64
  error JBMultiTerminal_OverflowAlert(uint256 value, uint256 limit);
64
65
  error JBMultiTerminal_PermitAllowanceNotEnough(uint256 amount, uint256 allowance);
@@ -386,6 +387,15 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
386
387
  metadata: metadata
387
388
  });
388
389
  } else {
390
+ // Revert if this is a self-referencing payout (project paying itself via a split).
391
+ // Same-project pay splits would mint tokens against existing balance without new funds entering.
392
+ // Projects that want to mint should do so explicitly via the controller.
393
+ // Cross-project pay splits on the same terminal are allowed (different project receives the funds).
394
+ // The try-catch in the split group lib catches this revert and restores the balance.
395
+ if (terminal == this && split.projectId == projectId) {
396
+ revert JBMultiTerminal_MintNotAllowed();
397
+ }
398
+
389
399
  // Keep a reference to the beneficiary of the payment.
390
400
  address beneficiary = split.beneficiary != address(0) ? split.beneficiary : originalMessageSender;
391
401
 
@@ -492,12 +502,14 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
492
502
  revert JBMultiTerminal_TerminalTokensIncompatible({projectId: projectId, token: token, terminal: to});
493
503
  }
494
504
 
495
- // Clear fee-free surplus tracking before migration. The new terminal has no fee-free history.
496
- // This prevents stale fee-free surplus from persisting if the project later migrates back.
505
+ // Clear fee-free surplus tracking the fee-free liability is settled by the migration fee below.
497
506
  delete _feeFreeSurplusOf[projectId][token];
498
507
 
499
508
  // Terminal migration intentionally does not transfer held fees. Held fees belong to the
500
509
  // fee beneficiary (project #1), not the migrating project. They unlock after 28 days regardless of terminal.
510
+ // After migration, `processHeldFeesOf()` on this terminal still works — it reads from `_heldFeesOf` and
511
+ // sends fees to the fee project terminal. The migrated project's balance on this terminal is zero, but held
512
+ // fees are backed by the terminal's own token balance (not the project's recorded balance).
501
513
  // Record the migration in the store.
502
514
  // slither-disable-next-line reentrancy-events
503
515
  balance = STORE.recordTerminalMigration({projectId: projectId, token: token});
@@ -506,17 +518,33 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
506
518
 
507
519
  // Transfer the balance if needed.
508
520
  if (balance != 0) {
521
+ // Migration to a non-feeless terminal incurs the standard 2.5% fee, same as any other fund egress.
522
+ // This also settles any fee-free surplus liability that would otherwise be lost on the new terminal.
523
+ uint256 feeAmount;
524
+ if (!_isFeeless(address(to)) && projectId != _FEE_BENEFICIARY_PROJECT_ID) {
525
+ feeAmount = _takeFeeFrom({
526
+ projectId: projectId,
527
+ token: token,
528
+ amount: balance,
529
+ beneficiary: payable(_ownerOf(projectId)),
530
+ shouldHoldFees: false
531
+ });
532
+ }
533
+
534
+ // Transfer the balance minus the fee to the new terminal.
535
+ uint256 migrationAmount = balance - feeAmount;
536
+
509
537
  // Trigger any inherited pre-transfer logic.
510
538
  // If this terminal's token is the native token, send it in `msg.value`.
511
539
  // slither-disable-next-line reentrancy-events
512
- uint256 payValue = _beforeTransferTo({to: address(to), token: token, amount: balance});
540
+ uint256 payValue = _beforeTransferTo({to: address(to), token: token, amount: migrationAmount});
513
541
 
514
- // Withdraw the balance to transfer to the new terminal;
542
+ // Withdraw the balance to transfer to the new terminal.
515
543
  // slither-disable-next-line reentrancy-events
516
544
  to.addToBalanceOf{value: payValue}({
517
545
  projectId: projectId,
518
546
  token: token,
519
- amount: balance,
547
+ amount: migrationAmount,
520
548
  shouldReturnHeldFees: false,
521
549
  memo: "",
522
550
  metadata: bytes("")
@@ -584,13 +612,13 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
584
612
  /// @notice Process any fees that are being held for the project.
585
613
  /// @dev Reentrancy safety: the loop re-reads `_nextHeldFeeIndexOf` from storage each iteration and advances the
586
614
  /// index before the external `_processFee` call, so a reentrant call cannot double-process the same fee entry.
587
- /// @dev Phantom balance risk: after a terminal migration, held fees remain in this terminal but the backing tokens
588
- /// have been transferred to the new terminal via `migrateBalanceOf`. If `_processFee` reverts (e.g. the fee
589
- /// terminal rejects the payment), the catch block calls `_recordAddedBalanceFor`, which credits the project's
590
- /// recorded balance without any actual tokens arriving creating a phantom balance. This is an accepted
591
- /// trade-off:
592
- /// the alternative (losing the fee amount entirely on revert) is worse. Callers should be aware that processing
593
- /// held fees post-migration may inflate the project's recorded balance if any fee payments revert.
615
+ /// @dev Held fees after migration: held fees remain in this terminal after `migrateBalanceOf` because their backing
616
+ /// tokens are not part of `balanceOf` they were already deducted from the recorded balance during the payout
617
+ /// that
618
+ /// created them. The actual fee-backing tokens remain in this terminal's token holdings. If `_processFee` reverts
619
+ /// (e.g. the fee terminal rejects the payment), the catch block calls `_recordAddedBalanceFor` to credit the fee
620
+ /// amount back to the project. This credit is backed by the tokens that failed to transfer out. No phantom balance
621
+ /// is created because the tokens never left.
594
622
  /// @dev The index-increment-before-`_processFee` pattern is intentional: locked (not-yet-unlocked) fees are skipped
595
623
  /// via the `unlockTimestamp` check, and advancing the index before the external call prevents reentrancy from
596
624
  /// reprocessing the same fee entry.
package/test/TestFees.sol CHANGED
@@ -216,8 +216,9 @@ contract TestFees_Local is TestBaseWorkflow {
216
216
  // Send: Migration to terminal2
217
217
  _terminal.migrateBalanceOf(_projectId, JBConstants.NATIVE_TOKEN, _terminal2);
218
218
 
219
- // Check: Held Fee is processed and feeAmount remains in terminal
220
- assertEq(address(_terminal).balance, _feeAmount);
219
+ // Check: Held fee remains in terminal, plus migration fee paid to fee project (on same terminal)
220
+ uint256 _migrationFee = _nativeDistLimit * _terminal.FEE() / JBConstants.MAX_FEE;
221
+ assertEq(address(_terminal).balance, _feeAmount + _migrationFee);
221
222
 
222
223
  vm.stopPrank();
223
224
  }
@@ -265,8 +266,9 @@ contract TestFees_Local is TestBaseWorkflow {
265
266
  // Send: Migration to terminal2
266
267
  _terminal.migrateBalanceOf(_projectId, JBConstants.NATIVE_TOKEN, _terminal2);
267
268
 
268
- // Check: Held fee has been repaid, no balance remains.
269
- assertEq(address(_terminal).balance, 0);
269
+ // Check: Held fee has been repaid. Migration fee paid to fee project remains on this terminal.
270
+ uint256 _migrationFee = _nativePayAmount * _terminal.FEE() / JBConstants.MAX_FEE;
271
+ assertEq(address(_terminal).balance, _migrationFee);
270
272
 
271
273
  vm.stopPrank();
272
274
  }
@@ -6,6 +6,7 @@ import {JBMultiTerminal} from "../src/JBMultiTerminal.sol";
6
6
  import {IJBController} from "../src/interfaces/IJBController.sol";
7
7
  import {IJBRulesetApprovalHook} from "../src/interfaces/IJBRulesetApprovalHook.sol";
8
8
  import {JBConstants} from "../src/libraries/JBConstants.sol";
9
+ import {JBFees} from "../src/libraries/JBFees.sol";
9
10
  import {JBAccountingContext} from "../src/structs/JBAccountingContext.sol";
10
11
  import {JBFundAccessLimitGroup} from "../src/structs/JBFundAccessLimitGroup.sol";
11
12
  import {JBRulesetConfig} from "../src/structs/JBRulesetConfig.sol";
@@ -105,7 +106,7 @@ contract TestTerminalMigration_Local is TestBaseWorkflow {
105
106
  uint256 migratedBalance = _terminalA.migrateBalanceOf(_projectId, JBConstants.NATIVE_TOKEN, _terminalB);
106
107
  assertEq(migratedBalance, payAmount, "full balance should be migrated");
107
108
 
108
- // Step 4: Verify balances after migration
109
+ // Step 4: Verify balances after migration (fee project is exempt from migration fee)
109
110
  uint256 balanceAAfter = jbTerminalStore().balanceOf(address(_terminalA), _projectId, JBConstants.NATIVE_TOKEN);
110
111
  assertEq(balanceAAfter, 0, "terminal A should have zero after migration");
111
112
 
@@ -152,7 +153,7 @@ contract TestTerminalMigration_Local is TestBaseWorkflow {
152
153
  vm.prank(_projectOwner);
153
154
  _terminalA.migrateBalanceOf(_projectId, JBConstants.NATIVE_TOKEN, _terminalB);
154
155
 
155
- // Check surplus from terminal B
156
+ // Check surplus from terminal B (fee project exempt from migration fee)
156
157
  uint256 surplusAfter =
157
158
  _terminalB.currentSurplusOf(_projectId, new address[](0), 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
158
159
  assertEq(surplusAfter, surplusBefore, "surplus should be preserved after migration");
@@ -169,4 +170,105 @@ contract TestTerminalMigration_Local is TestBaseWorkflow {
169
170
  vm.expectRevert();
170
171
  _terminalA.migrateBalanceOf(_projectId, JBConstants.NATIVE_TOKEN, _terminalB);
171
172
  }
173
+
174
+ /// @notice Non-fee project migration charges the 2.5% fee; fee project balance increases.
175
+ function test_migration_nonFeeProject_chargesFee() public {
176
+ // Launch a second project (project 2) — this is NOT the fee project.
177
+ JBRulesetMetadata memory _metadata2 = JBRulesetMetadata({
178
+ reservedPercent: 0,
179
+ cashOutTaxRate: 0,
180
+ baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
181
+ pausePay: false,
182
+ pauseCreditTransfers: false,
183
+ allowOwnerMinting: false,
184
+ allowSetCustomToken: false,
185
+ allowTerminalMigration: true,
186
+ allowSetTerminals: true,
187
+ allowSetController: false,
188
+ allowAddAccountingContext: false,
189
+ allowAddPriceFeed: false,
190
+ ownerMustSendPayouts: false,
191
+ holdFees: false,
192
+ useTotalSurplusForCashOuts: false,
193
+ useDataHookForPay: false,
194
+ useDataHookForCashOut: false,
195
+ dataHook: address(0),
196
+ metadata: 0
197
+ });
198
+
199
+ JBRulesetConfig[] memory _rulesetConfig2 = new JBRulesetConfig[](1);
200
+ _rulesetConfig2[0].mustStartAtOrAfter = 0;
201
+ _rulesetConfig2[0].duration = 0;
202
+ _rulesetConfig2[0].weight = 1000 * 10 ** 18;
203
+ _rulesetConfig2[0].weightCutPercent = 0;
204
+ _rulesetConfig2[0].approvalHook = IJBRulesetApprovalHook(address(0));
205
+ _rulesetConfig2[0].metadata = _metadata2;
206
+ _rulesetConfig2[0].splitGroups = new JBSplitGroup[](0);
207
+ _rulesetConfig2[0].fundAccessLimitGroups = new JBFundAccessLimitGroup[](0);
208
+
209
+ JBAccountingContext[] memory _tokensToAccept = new JBAccountingContext[](1);
210
+ _tokensToAccept[0] = JBAccountingContext({
211
+ token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
212
+ });
213
+
214
+ JBTerminalConfig[] memory _terminalConfigs2 = new JBTerminalConfig[](2);
215
+ _terminalConfigs2[0] = JBTerminalConfig({terminal: _terminalA, accountingContextsToAccept: _tokensToAccept});
216
+ _terminalConfigs2[1] = JBTerminalConfig({terminal: _terminalB, accountingContextsToAccept: _tokensToAccept});
217
+
218
+ uint256 project2 = _controller.launchProjectFor({
219
+ owner: _projectOwner,
220
+ projectUri: "non-fee-project",
221
+ rulesetConfigurations: _rulesetConfig2,
222
+ terminalConfigurations: _terminalConfigs2,
223
+ memo: ""
224
+ });
225
+
226
+ // Confirm project 2 is NOT the fee project.
227
+ assertGt(project2, 1, "project2 should not be the fee project");
228
+
229
+ uint256 payAmount = 10 ether;
230
+
231
+ // Pay into terminal A for project 2.
232
+ vm.deal(_beneficiary, payAmount);
233
+ vm.prank(_beneficiary);
234
+ _terminalA.pay{value: payAmount}(project2, JBConstants.NATIVE_TOKEN, payAmount, _beneficiary, 0, "", "");
235
+
236
+ // Snapshot fee project balance before migration.
237
+ uint256 feeBalanceBefore = jbTerminalStore().balanceOf(address(_terminalA), 1, JBConstants.NATIVE_TOKEN);
238
+
239
+ // Migrate project 2 from terminal A to terminal B.
240
+ vm.prank(_projectOwner);
241
+ _terminalA.migrateBalanceOf(project2, JBConstants.NATIVE_TOKEN, _terminalB);
242
+
243
+ // Fee project balance should have increased (fee was charged).
244
+ uint256 feeBalanceAfter = jbTerminalStore().balanceOf(address(_terminalA), 1, JBConstants.NATIVE_TOKEN);
245
+ assertGt(feeBalanceAfter, feeBalanceBefore, "fee project should receive migration fee");
246
+
247
+ // Terminal B should have received payAmount minus the 2.5% fee.
248
+ uint256 expectedFee = JBFees.feeAmountFrom({amountBeforeFee: payAmount, feePercent: 25});
249
+ uint256 balanceBAfter = jbTerminalStore().balanceOf(address(_terminalB), project2, JBConstants.NATIVE_TOKEN);
250
+ assertEq(balanceBAfter, payAmount - expectedFee, "terminal B balance should reflect fee deduction");
251
+ }
252
+
253
+ /// @notice Fee project (project 1) migration is exempt from fees.
254
+ function test_migration_feeProject_noFeeCharged() public {
255
+ // _projectId is project 1, which IS the fee project.
256
+ assertEq(_projectId, 1, "project under test should be the fee project");
257
+
258
+ uint256 payAmount = 10 ether;
259
+
260
+ // Pay into terminal A for the fee project.
261
+ vm.deal(_beneficiary, payAmount);
262
+ vm.prank(_beneficiary);
263
+ _terminalA.pay{value: payAmount}(_projectId, JBConstants.NATIVE_TOKEN, payAmount, _beneficiary, 0, "", "");
264
+
265
+ // Migrate fee project from terminal A to terminal B.
266
+ vm.prank(_projectOwner);
267
+ uint256 migratedBalance = _terminalA.migrateBalanceOf(_projectId, JBConstants.NATIVE_TOKEN, _terminalB);
268
+ assertEq(migratedBalance, payAmount, "full balance should be migrated without fee");
269
+
270
+ // Terminal B should have the full amount (no fee deducted).
271
+ uint256 balanceBAfter = jbTerminalStore().balanceOf(address(_terminalB), _projectId, JBConstants.NATIVE_TOKEN);
272
+ assertEq(balanceBAfter, payAmount, "fee project should not be charged migration fee");
273
+ }
172
274
  }
@@ -318,10 +318,13 @@ contract FeeFreeSurplusLifecycleTest is TestBaseWorkflow {
318
318
  jbTerminalStore().balanceOf(address(_terminal), _recipientProjectId, JBConstants.NATIVE_TOKEN);
319
319
  assertEq(balanceAfterOnOldTerminal, 0, "Old terminal balance should be zero after migration");
320
320
 
321
- // Verify the new terminal received the balance.
321
+ // Verify the new terminal received the balance minus the 2.5% migration fee.
322
322
  uint256 balanceOnNewTerminal =
323
323
  jbTerminalStore().balanceOf(address(_terminal2), _recipientProjectId, JBConstants.NATIVE_TOKEN);
324
- assertEq(balanceOnNewTerminal, balanceBefore, "New terminal should have the migrated balance");
324
+ uint256 migrationFee = balanceBefore * 25 / 1000;
325
+ assertEq(
326
+ balanceOnNewTerminal, balanceBefore - migrationFee, "New terminal should have balance minus migration fee"
327
+ );
325
328
  }
326
329
 
327
330
  // --- Helpers ---
@@ -4,18 +4,14 @@ pragma solidity 0.8.28;
4
4
  import {JBMultiTerminal} from "../../../../src/JBMultiTerminal.sol";
5
5
  import {IJBDirectory} from "../../../../src/interfaces/IJBDirectory.sol";
6
6
  import {IJBFeelessAddresses} from "../../../../src/interfaces/IJBFeelessAddresses.sol";
7
- import {IJBRulesetApprovalHook} from "../../../../src/interfaces/IJBRulesetApprovalHook.sol";
8
7
  import {IJBSplitHook} from "../../../../src/interfaces/IJBSplitHook.sol";
9
8
  import {IJBTerminal} from "../../../../src/interfaces/IJBTerminal.sol";
10
9
  import {IJBTerminalStore} from "../../../../src/interfaces/IJBTerminalStore.sol";
11
10
  import {JBConstants} from "../../../../src/libraries/JBConstants.sol";
12
11
  import {JBFees} from "../../../../src/libraries/JBFees.sol";
13
12
  import {JBAccountingContext} from "../../../../src/structs/JBAccountingContext.sol";
14
- import {JBPayHookSpecification} from "../../../../src/structs/JBPayHookSpecification.sol";
15
- import {JBRuleset} from "../../../../src/structs/JBRuleset.sol";
16
13
  import {JBSplit} from "../../../../src/structs/JBSplit.sol";
17
14
  import {JBSplitHookContext} from "../../../../src/structs/JBSplitHookContext.sol";
18
- import {JBTokenAmount} from "../../../../src/structs/JBTokenAmount.sol";
19
15
  import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
20
16
  import {IERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
21
17
  import {JBMultiTerminalSetup} from "./JBMultiTerminalSetup.sol";
@@ -366,9 +362,7 @@ contract TestExecutePayout_Local is JBMultiTerminalSetup {
366
362
  }
367
363
 
368
364
  function test_GivenPreferAddToBalanceDNEQTrueAndTerminalEQThisAddress() external {
369
- // it will call internal _pay
370
-
371
- _setAccountingContext(_projectId, _usdc, 0, _usdcCurrency);
365
+ // it will revert with MintNotAllowed because same-project same-terminal pay splits are blocked
372
366
 
373
367
  // mock call to directory primaryTerminalOf
374
368
  mockExpect(
@@ -386,41 +380,8 @@ contract TestExecutePayout_Local is JBMultiTerminalSetup {
386
380
  hook: IJBSplitHook(address(0))
387
381
  });
388
382
 
389
- // needed for next mock call returns
390
- JBTokenAmount memory tokenAmount =
391
- JBTokenAmount({token: _usdc, decimals: 0, currency: _usdcCurrency, value: _defaultAmount});
392
- JBPayHookSpecification[] memory hookSpecifications = new JBPayHookSpecification[](0);
393
- JBRuleset memory returnedRuleset = JBRuleset({
394
- cycleNumber: 1,
395
- id: 1,
396
- basedOnId: 0,
397
- start: 0,
398
- duration: 0,
399
- weight: 0,
400
- weightCutPercent: 0,
401
- approvalHook: IJBRulesetApprovalHook(address(0)),
402
- metadata: 0
403
- });
404
-
405
- // mock call to JBTerminalStore recordPaymentFrom
406
- mockExpect(
407
- address(store),
408
- abi.encodeCall(
409
- IJBTerminalStore.recordPaymentFrom,
410
- (
411
- address(_terminal),
412
- tokenAmount,
413
- _projectId,
414
- address(this),
415
- bytes(abi.encodePacked(uint256(_projectId)))
416
- )
417
- ),
418
- abi.encode(returnedRuleset, 0, hookSpecifications)
419
- );
420
-
421
- // for safe ERC20 check of code length at token address
422
383
  vm.prank(address(_terminal));
423
-
384
+ vm.expectRevert(JBMultiTerminal.JBMultiTerminal_MintNotAllowed.selector);
424
385
  JBMultiTerminal(address(_terminal))
425
386
  .executePayout({
426
387
  split: _splitMemory,
@@ -11,6 +11,7 @@ import {JBAccountingContext} from "../../../../src/structs/JBAccountingContext.s
11
11
  import {JBPermissionIds} from "@bananapus/permission-ids-v6/src/JBPermissionIds.sol";
12
12
  import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
13
13
  import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
14
+ import {IJBFeelessAddresses} from "../../../../src/interfaces/IJBFeelessAddresses.sol";
14
15
  import {JBMultiTerminalSetup} from "./JBMultiTerminalSetup.sol";
15
16
 
16
17
  contract TestMigrateBalanceOf_Local is JBMultiTerminalSetup {
@@ -104,6 +105,13 @@ contract TestMigrateBalanceOf_Local is JBMultiTerminalSetup {
104
105
  function test_GivenTokenIsERC20() external whenPermissioned {
105
106
  // it will safeIncreaseAllowance and addToBalanceOf
106
107
 
108
+ // mock _isFeeless to return true (skip migration fee for this unit test)
109
+ mockExpect(
110
+ address(feelessAddresses),
111
+ abi.encodeCall(IJBFeelessAddresses.isFeeless, (address(_newTerminal))),
112
+ abi.encode(true)
113
+ );
114
+
107
115
  // for next mock
108
116
  // forge-lint: disable-next-line(unsafe-typecast)
109
117
  JBAccountingContext memory _context =
@@ -143,6 +151,13 @@ contract TestMigrateBalanceOf_Local is JBMultiTerminalSetup {
143
151
  function test_GivenTokenIsNative() external whenPermissioned {
144
152
  // it will addToBalanceOf with value in msgvalue
145
153
 
154
+ // mock _isFeeless to return true (skip migration fee for this unit test)
155
+ mockExpect(
156
+ address(feelessAddresses),
157
+ abi.encodeCall(IJBFeelessAddresses.isFeeless, (address(_newTerminal))),
158
+ abi.encode(true)
159
+ );
160
+
146
161
  // for next mock
147
162
  // forge-lint: disable-next-line(unsafe-typecast)
148
163
  JBAccountingContext memory _context =
@@ -0,0 +1,55 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity 0.8.28;
3
+
4
+ import {JBMultiTerminal} from "../../../../src/JBMultiTerminal.sol";
5
+ import {IJBDirectory} from "../../../../src/interfaces/IJBDirectory.sol";
6
+ import {JBConstants} from "../../../../src/libraries/JBConstants.sol";
7
+ import {JBSplit} from "../../../../src/structs/JBSplit.sol";
8
+ import {IJBSplitHook} from "../../../../src/interfaces/IJBSplitHook.sol";
9
+ import {JBMultiTerminalSetup} from "./JBMultiTerminalSetup.sol";
10
+
11
+ /// @notice Tests that a pay-type split back into the same terminal reverts with MintNotAllowed.
12
+ contract TestSelfPayRevert_Local is JBMultiTerminalSetup {
13
+ uint64 _projectId = 1;
14
+ uint256 _defaultAmount = 1e18;
15
+ address _sender = makeAddr("sender");
16
+ address _native = JBConstants.NATIVE_TOKEN;
17
+
18
+ function setUp() public {
19
+ super.multiTerminalSetup();
20
+ }
21
+
22
+ /// @notice When a split routes a pay back to the same project on the same terminal,
23
+ /// executePayout should revert with MintNotAllowed.
24
+ function test_RevertWhen_SplitPaysBackToSameTerminal() external {
25
+ // Build a split targeting the SAME project with preferAddToBalance = false (pay path).
26
+ JBSplit memory split = JBSplit({
27
+ preferAddToBalance: false,
28
+ percent: 1_000_000_000,
29
+ projectId: _projectId,
30
+ beneficiary: payable(_sender),
31
+ lockedUntil: 0,
32
+ hook: IJBSplitHook(address(0))
33
+ });
34
+
35
+ // Mock primaryTerminalOf to return this terminal (self-referencing).
36
+ mockExpect(
37
+ address(directory),
38
+ abi.encodeCall(IJBDirectory.primaryTerminalOf, (_projectId, _native)),
39
+ abi.encode(address(_terminal))
40
+ );
41
+
42
+ // executePayout requires msg.sender == address(this), so we call it via the terminal.
43
+ // The terminal's try-catch in the split group lib would normally catch this.
44
+ vm.prank(address(_terminal));
45
+ vm.expectRevert(JBMultiTerminal.JBMultiTerminal_MintNotAllowed.selector);
46
+ JBMultiTerminal(payable(address(_terminal)))
47
+ .executePayout({
48
+ split: split,
49
+ projectId: uint256(_projectId),
50
+ token: _native,
51
+ amount: _defaultAmount,
52
+ originalMessageSender: _sender
53
+ });
54
+ }
55
+ }