@bananapus/core-v6 0.0.49 → 0.0.52

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.
@@ -28,8 +28,10 @@ import {IJBSplits} from "./interfaces/IJBSplits.sol";
28
28
  import {IJBTerminal} from "./interfaces/IJBTerminal.sol";
29
29
  import {IJBTerminalStore} from "./interfaces/IJBTerminalStore.sol";
30
30
  import {IJBTokens} from "./interfaces/IJBTokens.sol";
31
+ import {JBCashOutHookSpecsLib} from "./libraries/JBCashOutHookSpecsLib.sol";
31
32
  import {JBConstants} from "./libraries/JBConstants.sol";
32
33
  import {JBFees} from "./libraries/JBFees.sol";
34
+ import {JBHeldFeesLib} from "./libraries/JBHeldFeesLib.sol";
33
35
  import {JBMetadataResolver} from "./libraries/JBMetadataResolver.sol";
34
36
  import {JBPayoutSplitGroupLib} from "./libraries/JBPayoutSplitGroupLib.sol";
35
37
  import {JBRulesetMetadataResolver} from "./libraries/JBRulesetMetadataResolver.sol";
@@ -40,6 +42,7 @@ import {JBCashOutHookSpecification} from "./structs/JBCashOutHookSpecification.s
40
42
  import {JBFee} from "./structs/JBFee.sol";
41
43
  import {JBPayHookSpecification} from "./structs/JBPayHookSpecification.sol";
42
44
  import {JBRuleset} from "./structs/JBRuleset.sol";
45
+ import {JBRulesetMetadata} from "./structs/JBRulesetMetadata.sol";
43
46
  import {JBSingleAllowance} from "./structs/JBSingleAllowance.sol";
44
47
  import {JBSplit} from "./structs/JBSplit.sol";
45
48
  import {JBSplitHookContext} from "./structs/JBSplitHookContext.sol";
@@ -63,6 +66,9 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
63
66
  // --------------------------- custom errors ------------------------- //
64
67
  //*********************************************************************//
65
68
 
69
+ error JBMultiTerminal_BeneficiaryProjectFeeFreeInflowsPaused(uint256 projectId);
70
+ error JBMultiTerminal_BeneficiaryProjectHasNoAccountingContexts(uint256 projectId);
71
+ error JBMultiTerminal_BeneficiaryProjectNotPaid(uint256 projectId);
66
72
  error JBMultiTerminal_FeeTerminalNotFound(address token);
67
73
  error JBMultiTerminal_MintNotAllowed(uint256 projectId, uint256 splitProjectId, address terminal);
68
74
  error JBMultiTerminal_NoMsgValueAllowed(uint256 value);
@@ -75,22 +81,10 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
75
81
  error JBMultiTerminal_TokenNotAccepted(address token);
76
82
  error JBMultiTerminal_UnderMin(uint256 value, uint256 min);
77
83
 
78
- //*********************************************************************//
79
- // ------------------------- public constants ------------------------ //
80
- //*********************************************************************//
81
-
82
- /// @notice This terminal's fee (as a fraction out of `JBConstants.MAX_FEE`).
83
- /// @dev Fees are charged on payouts to addresses and surplus allowance usage, as well as cash outs while the
84
- /// cash out tax rate is less than 100%.
85
- uint256 public constant override FEE = 25; // 2.5%
86
-
87
84
  //*********************************************************************//
88
85
  // ------------------------ internal constants ----------------------- //
89
86
  //*********************************************************************//
90
87
 
91
- /// @notice Project ID #1 receives fees. It should be the first project launched during the deployment process.
92
- uint256 internal constant _FEE_BENEFICIARY_PROJECT_ID = 1;
93
-
94
88
  /// @notice The number of seconds fees can be held for.
95
89
  uint256 internal constant _FEE_HOLDING_SECONDS = 2_419_200; // 28 days
96
90
 
@@ -220,6 +214,94 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
220
214
  }
221
215
  }
222
216
 
217
+ /// @notice Atomically cash out `holder`'s tokens of `projectId` and add the reclaim to
218
+ /// `beneficiaryProjectId`'s balance (no project tokens minted on the destination side).
219
+ /// @dev Equivalent to calling `cashOutTokensOf` followed by `addToBalanceOf` on the destination project,
220
+ /// except the source-side cash out fee is skipped. The equivalent fee is bound on the destination project's
221
+ /// side instead: `_feeFreeSurplusOf[beneficiaryProjectId]` is credited by the first of the destination
222
+ /// project's accounting contexts on this terminal whose balance grows during the routing.
223
+ /// @dev The destination terminal is `DIRECTORY.primaryTerminalOf(beneficiaryProjectId, tokenToReclaim)` —
224
+ /// which may itself be a router that swaps before adding to balance.
225
+ /// @dev Held-fee return on the destination side is hardcoded to `false`. This entrypoint is for cross-project
226
+ /// balance top-ups only, not for unlocking the destination's held fees. Callers that want to combine
227
+ /// cash-out → add-to-balance with `shouldReturnHeldFees: true` must do it explicitly via two separate calls.
228
+ /// @dev The destination project's current ruleset can set `pauseCrossProjectFeeFreeInflows` to opt out — the
229
+ /// call then reverts. If no delivery to the destination project lands on this terminal under any of the
230
+ /// destination project's accounting contexts, the call also reverts so the source-side fee skip never
231
+ /// becomes a leak.
232
+ /// @param holder The account whose project tokens are being burned.
233
+ /// @param projectId The ID of the source project being cashed out from.
234
+ /// @param cashOutCount The number of source-project tokens to burn, as a fixed point number with 18 decimals.
235
+ /// @param tokenToReclaim The terminal token reclaimed from the source project's surplus.
236
+ /// @param beneficiaryProjectId The destination project receiving the reclaim.
237
+ /// @param cashOutMetadata Bytes forwarded to the source project's data hook and any cashout hook specifications.
238
+ /// @param addToBalanceMetadata Bytes forwarded to the destination project's `addToBalanceOf` event.
239
+ /// @return reclaimAmount The gross reclaim amount returned by the store.
240
+ function addToBalanceAfterCashOutTokensOf(
241
+ address holder,
242
+ uint256 projectId,
243
+ uint256 cashOutCount,
244
+ address tokenToReclaim,
245
+ uint256 beneficiaryProjectId,
246
+ bytes calldata cashOutMetadata,
247
+ bytes calldata addToBalanceMetadata
248
+ )
249
+ external
250
+ override
251
+ returns (uint256 reclaimAmount)
252
+ {
253
+ // Caller must hold (or be operator with) `CASH_OUT_TOKENS` permission on the source `holder`/`projectId`.
254
+ // Burning A's tokens is the load-bearing side effect — gating it stays at the same authority bar as the
255
+ // direct `cashOutTokensOf` entrypoint.
256
+ _requireCashOutPermissionFrom({holder: holder, projectId: projectId});
257
+
258
+ // Destination opt-out check: B's current ruleset can set `pauseCrossProjectFeeFreeInflows = true` to
259
+ // refuse cross-project fee-free credits. Without this gate, anyone holding A's tokens could push a
260
+ // deferred-fee credit onto `_feeFreeSurplusOf[B]` without B consenting.
261
+ _requireBeneficiaryAcceptsFeeFreeInflows(beneficiaryProjectId);
262
+
263
+ // Burn source-project tokens, run cashout-side hooks, take any hook fees, and cap source fee-free.
264
+ // No separate destination beneficiary exists — the caller is the only address attached to this flow,
265
+ // used as the `CashOutTokens` event slot and credited any hook-fee project tokens.
266
+ reclaimAmount = _executeCrossProjectCashOut({
267
+ holder: holder,
268
+ projectId: projectId,
269
+ cashOutCount: cashOutCount,
270
+ tokenToReclaim: tokenToReclaim,
271
+ beneficiary: _msgSender(),
272
+ cashOutMetadata: cashOutMetadata
273
+ });
274
+
275
+ // Nothing to route if the data hook returned zero reclaim.
276
+ if (reclaimAmount == 0) return 0;
277
+
278
+ // Resolve B's primary terminal for the reclaim token. Could be this terminal (same-terminal short-
279
+ // circuit) or a router that swaps before depositing. Reverts if no primary terminal is registered.
280
+ IJBTerminal destinationTerminal = _resolveBeneficiaryTerminal(beneficiaryProjectId, tokenToReclaim);
281
+
282
+ // Snapshot B's per-context balances on this terminal BEFORE routing. The post-routing comparison
283
+ // identifies the bucket the reclaim actually landed in (matters for cross-token routes where a router
284
+ // swaps to a different token in B's accounting-context list).
285
+ (JBAccountingContext[] memory contexts, uint256[] memory balancesBefore) =
286
+ _snapshotBeneficiaryContextBalances(beneficiaryProjectId);
287
+
288
+ // Route via `_efficientAddToBalance` — handles same-terminal vs cross-terminal (with the standard
289
+ // `_beforeTransferTo`/`_afterTransferTo` allowance dance) and hardcodes `shouldReturnHeldFees: false`,
290
+ // so this entrypoint cannot be used to unlock B's held fees on top of the source-side fee skip.
291
+ _efficientAddToBalance({
292
+ terminal: destinationTerminal,
293
+ projectId: beneficiaryProjectId,
294
+ token: tokenToReclaim,
295
+ amount: reclaimAmount,
296
+ metadata: addToBalanceMetadata
297
+ });
298
+
299
+ // Credit `_feeFreeSurplusOf[B]` on the first of B's contexts whose balance grew. This binds the
300
+ // skipped source-side fee on the destination side: B's next non-feeless cashout pays it. Reverts if
301
+ // no context grew (no delivery landed) — without delivery, the fee skip would leak.
302
+ _creditFirstGrowingBeneficiaryContext(beneficiaryProjectId, contexts, balancesBefore);
303
+ }
304
+
223
305
  /// @notice Adds funds (terminal tokens) to a project's balance without minting project tokens. Useful for topping
224
306
  /// up a project or returning funds. Can also unlock previously held fees by returning them to the project's
225
307
  /// balance.
@@ -287,8 +369,7 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
287
369
  override
288
370
  returns (uint256 reclaimAmount)
289
371
  {
290
- // Enforce permissions.
291
- _requirePermissionFrom({account: holder, projectId: projectId, permissionId: JBPermissionIds.CASH_OUT_TOKENS});
372
+ _requireCashOutPermissionFrom({holder: holder, projectId: projectId});
292
373
 
293
374
  reclaimAmount = _cashOutTokensOf({
294
375
  holder: holder,
@@ -412,6 +493,7 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
412
493
  projectId: split.projectId,
413
494
  token: token,
414
495
  amount: netPayoutAmount,
496
+ payer: address(this),
415
497
  beneficiary: beneficiary,
416
498
  metadata: metadata
417
499
  });
@@ -473,9 +555,10 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
473
555
 
474
556
  _efficientPay({
475
557
  terminal: feeTerminal,
476
- projectId: _FEE_BENEFICIARY_PROJECT_ID,
558
+ projectId: JBConstants.FEE_BENEFICIARY_PROJECT_ID,
477
559
  token: token,
478
560
  amount: amount,
561
+ payer: address(this),
479
562
  beneficiary: beneficiary,
480
563
  metadata: metadata
481
564
  });
@@ -538,7 +621,10 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
538
621
  // Migration to a non-feeless terminal incurs the standard 2.5% fee, same as any other fund egress.
539
622
  // This also settles any fee-free surplus liability that would otherwise be lost on the new terminal.
540
623
  uint256 feeAmount;
541
- if (!_isFeeless({addr: address(to), projectId: projectId}) && projectId != _FEE_BENEFICIARY_PROJECT_ID) {
624
+ if (
625
+ !_isFeeless({addr: address(to), projectId: projectId})
626
+ && projectId != JBConstants.FEE_BENEFICIARY_PROJECT_ID
627
+ ) {
542
628
  feeAmount = _takeFeeFrom({
543
629
  projectId: projectId,
544
630
  token: token,
@@ -620,6 +706,78 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
620
706
  _checkMin({value: beneficiaryTokenCount, min: minReturnedTokens});
621
707
  }
622
708
 
709
+ /// @notice Atomically cash out `holder`'s tokens of `projectId` and pay the reclaim into `beneficiaryProjectId`.
710
+ /// @dev Equivalent to calling `cashOutTokensOf` followed by `pay` on the destination project, except the
711
+ /// source-side cash out fee is skipped. The equivalent fee is bound on the destination project's side instead:
712
+ /// `_feeFreeSurplusOf[beneficiaryProjectId]` is credited by the first of the destination project's accounting
713
+ /// contexts on this terminal whose balance grows during the routing.
714
+ /// @dev The destination terminal is `DIRECTORY.primaryTerminalOf(beneficiaryProjectId, tokenToReclaim)` —
715
+ /// which may itself be a router that swaps before paying the destination.
716
+ /// @dev The destination project's current ruleset can set `pauseCrossProjectFeeFreeInflows` to opt out — the
717
+ /// call then reverts. If no delivery to the destination project lands on this terminal under any of the
718
+ /// destination project's accounting contexts, the call also reverts so the source-side fee skip never becomes
719
+ /// a leak.
720
+ /// @param holder The account whose project tokens are being burned.
721
+ /// @param projectId The ID of the source project being cashed out from.
722
+ /// @param cashOutCount The number of source-project tokens to burn, as a fixed point number with 18 decimals.
723
+ /// @param tokenToReclaim The terminal token reclaimed from the source project's surplus.
724
+ /// @param beneficiaryProjectId The destination project receiving the reclaim.
725
+ /// @param beneficiary The address that receives the newly minted destination-project tokens.
726
+ /// @param minTokensOut The minimum number of destination-project tokens that must be minted, otherwise revert.
727
+ /// @param cashOutMetadata Bytes forwarded to the source project's data hook and any cashout hook specifications.
728
+ /// @param payMetadata Bytes forwarded to the destination project's pay flow.
729
+ /// @return reclaimAmount The gross reclaim amount returned by the store.
730
+ /// @return beneficiaryTokenCount The number of destination-project tokens minted to `beneficiary`.
731
+ function payAfterCashOutTokensOf(
732
+ address holder,
733
+ uint256 projectId,
734
+ uint256 cashOutCount,
735
+ address tokenToReclaim,
736
+ uint256 beneficiaryProjectId,
737
+ address beneficiary,
738
+ uint256 minTokensOut,
739
+ bytes calldata cashOutMetadata,
740
+ bytes calldata payMetadata
741
+ )
742
+ external
743
+ override
744
+ returns (uint256 reclaimAmount, uint256 beneficiaryTokenCount)
745
+ {
746
+ // Caller must hold (or be operator with) `CASH_OUT_TOKENS` permission on the source `holder`/`projectId`.
747
+ // Burning A's tokens is the load-bearing side effect — gating it stays at the same authority bar as the
748
+ // direct `cashOutTokensOf` entrypoint.
749
+ _requireCashOutPermissionFrom({holder: holder, projectId: projectId});
750
+
751
+ // Destination opt-out check: B's current ruleset can set `pauseCrossProjectFeeFreeInflows = true` to
752
+ // refuse cross-project fee-free credits. Without this gate, anyone holding A's tokens could push a
753
+ // deferred-fee credit onto `_feeFreeSurplusOf[B]` without B consenting.
754
+ _requireBeneficiaryAcceptsFeeFreeInflows(beneficiaryProjectId);
755
+
756
+ // Burn source-project tokens, run cashout-side hooks, take any hook fees, and cap source fee-free.
757
+ reclaimAmount = _executeCrossProjectCashOut({
758
+ holder: holder,
759
+ projectId: projectId,
760
+ cashOutCount: cashOutCount,
761
+ tokenToReclaim: tokenToReclaim,
762
+ beneficiary: beneficiary,
763
+ cashOutMetadata: cashOutMetadata
764
+ });
765
+
766
+ // Nothing to route if the data hook returned zero reclaim.
767
+ if (reclaimAmount != 0) {
768
+ beneficiaryTokenCount = _routeReclaimToBeneficiaryProject({
769
+ tokenToReclaim: tokenToReclaim,
770
+ reclaimAmount: reclaimAmount,
771
+ beneficiaryProjectId: beneficiaryProjectId,
772
+ beneficiary: beneficiary,
773
+ payMetadata: payMetadata
774
+ });
775
+ }
776
+
777
+ // Mint floor: how many destination-project tokens were issued for the inbound pay.
778
+ _checkMin({value: beneficiaryTokenCount, min: minTokensOut});
779
+ }
780
+
623
781
  /// @notice Processes held fees for a project, sending them to the protocol's fee project. Fees are held for 28 days
624
782
  /// after a payout — processing them finalizes the fee payment.
625
783
  /// @dev Only processes fees whose `unlockTimestamp` has passed. Stops early if it encounters a still-locked fee.
@@ -631,59 +789,15 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
631
789
  /// @param token The token to process held fees for.
632
790
  /// @param count The number of fees to process.
633
791
  function processHeldFeesOf(uint256 projectId, address token, uint256 count) external override {
634
- // Keep a reference to the terminal that'll receive the fees.
635
- IJBTerminal feeTerminal = _primaryTerminalOf({projectId: _FEE_BENEFICIARY_PROJECT_ID, token: token});
636
-
637
- // Process each fee. Re-read the index and array length from storage each iteration to account for reentrant
638
- // calls that may have already advanced the index or cleaned up the array.
639
- for (uint256 i; i < count;) {
640
- // Read the current index from storage (not a cached value) to prevent reentrancy from
641
- // causing double-processing.
642
- uint256 currentIndex = _nextHeldFeeIndexOf[projectId][token];
643
-
644
- // If all fees have been processed, break to cleanup.
645
- if (currentIndex >= _heldFeesOf[projectId][token].length) break;
646
-
647
- // Keep a reference to the held fee being iterated on.
648
- JBFee memory heldFee = _heldFeesOf[projectId][token][currentIndex];
649
-
650
- // Can't process fees that aren't yet unlocked. Fees unlock sequentially in the array, so nothing left to do
651
- // if the current fee isn't yet unlocked.
652
- // forge-lint: disable-next-line(block-timestamp)
653
- if (heldFee.unlockTimestamp > block.timestamp) break;
654
-
655
- // Delete the entry and advance the index *before* the external call. This is intentional:
656
- // 1. It prevents reentrancy from reprocessing the same fee.
657
- // 2. If `_processFee` fails (try-catch), the fee amount is returned to the project's balance via
658
- // `_recordAddedBalanceFor` — the fee is forgiven rather than retried. This is a deliberate design
659
- // choice: projects should not have funds permanently stuck because the fee route is misconfigured or
660
- // reverting.
661
- // A `FeeReverted` event is emitted so the forgiveness is observable off-chain.
662
- delete _heldFeesOf[projectId][token][currentIndex];
663
- _nextHeldFeeIndexOf[projectId][token] = currentIndex + 1;
664
-
665
- // Process the fee.
666
- _processFee({
667
- projectId: projectId,
668
- token: token,
669
- amount: _feeAmountFrom(heldFee.amount),
670
- beneficiary: heldFee.beneficiary,
671
- feeTerminal: feeTerminal,
672
- wasHeld: true
673
- });
674
- unchecked {
675
- ++i;
676
- }
677
- }
678
-
679
- // If all held fees have been processed, reset the array and index entirely to bound storage growth.
680
- if (
681
- _nextHeldFeeIndexOf[projectId][token] >= _heldFeesOf[projectId][token].length
682
- && _heldFeesOf[projectId][token].length > 0
683
- ) {
684
- delete _heldFeesOf[projectId][token];
685
- delete _nextHeldFeeIndexOf[projectId][token];
686
- }
792
+ JBHeldFeesLib.processHeldFees({
793
+ heldFeesOf: _heldFeesOf,
794
+ nextHeldFeeIndexOf: _nextHeldFeeIndexOf,
795
+ directory: DIRECTORY,
796
+ store: STORE,
797
+ projectId: projectId,
798
+ token: token,
799
+ count: count
800
+ });
687
801
  }
688
802
 
689
803
  /// @notice Distributes funds from a project's balance to its payout split recipients, up to the current ruleset's
@@ -1154,25 +1268,15 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1154
1268
  // Cache whether the beneficiary is feeless.
1155
1269
  bool beneficiaryIsFeeless = _isFeeless({addr: beneficiary, projectId: projectId});
1156
1270
 
1157
- {
1158
- // Cache the controller to avoid a redundant external call (also used inside STORE.recordCashOutFor).
1159
- IJBController controller = _controllerOf(projectId);
1160
-
1161
- // Record the cash out.
1162
- (ruleset, reclaimAmount, cashOutTaxRate, hookSpecifications) = STORE.recordCashOutFor({
1163
- holder: holder,
1164
- projectId: projectId,
1165
- cashOutCount: cashOutCount,
1166
- tokenToReclaim: tokenToReclaim,
1167
- beneficiaryIsFeeless: beneficiaryIsFeeless,
1168
- metadata: metadata
1169
- });
1170
-
1171
- // Burn the project tokens.
1172
- if (cashOutCount != 0) {
1173
- controller.burnTokensOf({holder: holder, projectId: projectId, tokenCount: cashOutCount, memo: ""});
1174
- }
1175
- }
1271
+ // Record the cash out and burn the project tokens.
1272
+ (ruleset, reclaimAmount, cashOutTaxRate, hookSpecifications) = _recordAndBurnCashOut({
1273
+ holder: holder,
1274
+ projectId: projectId,
1275
+ cashOutCount: cashOutCount,
1276
+ tokenToReclaim: tokenToReclaim,
1277
+ beneficiaryIsFeeless: beneficiaryIsFeeless,
1278
+ metadata: metadata
1279
+ });
1176
1280
 
1177
1281
  // Keep a reference to the amount being reclaimed that is subject to fees.
1178
1282
  uint256 amountEligibleForFees;
@@ -1212,7 +1316,8 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1212
1316
  // If the data hook returned cash out hook specifications, fulfill them.
1213
1317
  if (hookSpecifications.length != 0) {
1214
1318
  // Fulfill the cash out hook specifications.
1215
- amountEligibleForFees += _fulfillCashOutHookSpecificationsFor({
1319
+ amountEligibleForFees += JBCashOutHookSpecsLib.fulfill({
1320
+ feelessAddresses: FEELESS_ADDRESSES,
1216
1321
  projectId: projectId,
1217
1322
  holder: holder,
1218
1323
  cashOutCount: cashOutCount,
@@ -1268,6 +1373,62 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1268
1373
  if (value < min) revert JBMultiTerminal_UnderMin(value, min);
1269
1374
  }
1270
1375
 
1376
+ /// @notice Find the first of B's accounting contexts whose balance grew during the routing, credit
1377
+ /// `_feeFreeSurplusOf[beneficiaryProjectId][token]` by the delta, cap to remaining balance, and return.
1378
+ /// Reverts with `JBMultiTerminal_BeneficiaryProjectNotPaid` if no context grew — without delivery, the
1379
+ /// skipped source-side fee can't be bound and would leak.
1380
+ /// @dev Shared by `_routeReclaimToBeneficiaryProject` and `_routeReclaimAsAddToBalance`. The "first
1381
+ /// growing context wins" rule matches a well-behaved router that picks one of B's tokens (the post-swap
1382
+ /// token) and deposits into that single bucket.
1383
+ /// @param beneficiaryProjectId The destination project.
1384
+ /// @param contexts Accounting contexts captured before the routing.
1385
+ /// @param balancesBefore Pre-routing balances aligned to `contexts` by index.
1386
+ function _creditFirstGrowingBeneficiaryContext(
1387
+ uint256 beneficiaryProjectId,
1388
+ JBAccountingContext[] memory contexts,
1389
+ uint256[] memory balancesBefore
1390
+ )
1391
+ internal
1392
+ {
1393
+ // Walk B's accounting contexts in declared order. The first context whose balance grew is treated as
1394
+ // the bucket the router chose to deposit into (typically the post-swap token in a cross-token route).
1395
+ // We bind the deferred source-side fee to that bucket and stop — subsequent grown contexts are ignored
1396
+ // by design, capping the credit at one delivery delta even if a misbehaving router somehow split the
1397
+ // deposit across multiple buckets.
1398
+ for (uint256 i; i < contexts.length;) {
1399
+ // Read B's post-routing balance for this context's token. Compared against the pre-routing snapshot
1400
+ // captured by `_snapshotBeneficiaryContextBalances` to detect the delivery delta.
1401
+ uint256 balanceAfter =
1402
+ STORE.balanceOf({terminal: address(this), projectId: beneficiaryProjectId, token: contexts[i].token});
1403
+
1404
+ if (balanceAfter > balancesBefore[i]) {
1405
+ // Credit the delivery delta into B's fee-free counter for this token. `unchecked` is safe:
1406
+ // `balanceAfter > balancesBefore[i]` is the loop condition, so the subtraction can't underflow,
1407
+ // and the addition can't overflow before the underlying balance does (terminal balance is the
1408
+ // upper bound on any cumulative credit — see the cap call below).
1409
+ unchecked {
1410
+ _feeFreeSurplusOf[beneficiaryProjectId][contexts[i].token] += balanceAfter - balancesBefore[i];
1411
+ }
1412
+
1413
+ // Cap the credit at B's current balance for this token. If pay/addToBalance hooks pulled funds
1414
+ // back out during routing, the post-balance read inside `_capFeeFreeSurplus` clamps the
1415
+ // counter so it never exceeds what's actually sitting in B's bucket. Without this, B's later
1416
+ // zero-tax cashouts would over-fee phantom amounts.
1417
+ _capFeeFreeSurplus({projectId: beneficiaryProjectId, token: contexts[i].token});
1418
+ return;
1419
+ }
1420
+
1421
+ unchecked {
1422
+ ++i;
1423
+ }
1424
+ }
1425
+
1426
+ // No context grew. Either the destination terminal silently dropped the funds or routed them
1427
+ // elsewhere (e.g. to a different terminal not registered as B's primary). Revert the entire
1428
+ // cross-project flow so the source-side fee skip never becomes a leak — A's burn is undone too.
1429
+ revert JBMultiTerminal_BeneficiaryProjectNotPaid(beneficiaryProjectId);
1430
+ }
1431
+
1271
1432
  /// @notice Fund a project either by calling this terminal's internal `addToBalance` function or by calling the
1272
1433
  /// recipient terminal's `addToBalance` function.
1273
1434
  /// @param terminal The terminal on which the project is expecting to receive funds.
@@ -1317,40 +1478,135 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1317
1478
  uint256 projectId,
1318
1479
  address token,
1319
1480
  uint256 amount,
1481
+ address payer,
1320
1482
  address beneficiary,
1321
1483
  bytes memory metadata
1322
1484
  )
1323
1485
  internal
1486
+ returns (uint256 newlyIssuedTokenCount)
1324
1487
  {
1325
1488
  if (terminal == IJBTerminal(address(this))) {
1326
- _pay({
1489
+ return _pay({
1327
1490
  projectId: projectId,
1328
1491
  token: token,
1329
1492
  amount: amount,
1330
- payer: address(this),
1493
+ payer: payer,
1331
1494
  beneficiary: beneficiary,
1332
1495
  memo: "",
1333
1496
  metadata: metadata
1334
1497
  });
1335
- } else {
1336
- // Trigger any inherited pre-transfer logic.
1337
- // Keep a reference to the amount that'll be paid as a `msg.value`.
1338
- uint256 payValue = _beforeTransferTo({to: address(terminal), token: token, amount: amount});
1498
+ }
1499
+
1500
+ // Cross-terminal: standard pre/post transfer + external `pay()`. `minReturnedTokens: 0` because callers
1501
+ // own their own slippage gate (e.g. `_checkMin(beneficiaryTokenCount, minTokensOut)`).
1502
+ uint256 payValue = _beforeTransferTo({to: address(terminal), token: token, amount: amount});
1503
+
1504
+ newlyIssuedTokenCount = terminal.pay{value: payValue}({
1505
+ projectId: projectId,
1506
+ token: token,
1507
+ amount: amount,
1508
+ beneficiary: beneficiary,
1509
+ minReturnedTokens: 0,
1510
+ memo: "",
1511
+ metadata: metadata
1512
+ });
1513
+
1514
+ _afterTransferTo({to: address(terminal), token: token});
1515
+ }
1516
+
1517
+ /// @notice Shared cashout-prep step for both cross-project entrypoints (`_payAfterCashOutTokensOf` and
1518
+ /// `_addToBalanceAfterCashOutTokensOf`). Records the cashout with `beneficiaryIsFeeless: true`, burns the
1519
+ /// holder's project tokens, runs cashout-side hook specs, caps the source's fee-free surplus, and takes
1520
+ /// hook fees. Returns the gross reclaim amount that the caller must then route to the destination project.
1521
+ /// @dev `beneficiary` is recorded in the `CashOutTokens` event and credited any fee-project tokens minted
1522
+ /// from hook fees. For pay it's the user-supplied destination beneficiary; for addToBalance the caller
1523
+ /// passes `_msgSender()` (no separate recipient exists).
1524
+ /// @param holder The account whose source-project tokens are being burned.
1525
+ /// @param projectId The ID of the source project being cashed out from.
1526
+ /// @param cashOutCount The number of source-project tokens to burn.
1527
+ /// @param tokenToReclaim The terminal token reclaimed from the source project's surplus.
1528
+ /// @param beneficiary The address recorded in the event slot and credited any hook-fee project tokens.
1529
+ /// @param cashOutMetadata Bytes forwarded to the source project's data hook and any cashout hook specs.
1530
+ /// @return reclaimAmount The gross reclaim amount returned by the store.
1531
+ function _executeCrossProjectCashOut(
1532
+ address holder,
1533
+ uint256 projectId,
1534
+ uint256 cashOutCount,
1535
+ address tokenToReclaim,
1536
+ address beneficiary,
1537
+ bytes memory cashOutMetadata
1538
+ )
1539
+ internal
1540
+ returns (uint256 reclaimAmount)
1541
+ {
1542
+ // Record the cash out and burn the project tokens. `beneficiaryIsFeeless: true` — the equivalent fee
1543
+ // is bound on the destination side via the `_feeFreeSurplusOf[beneficiaryProjectId]` credit computed
1544
+ // from the delivery delta in the routing step. The external entrypoint reverts if delivery falls short,
1545
+ // so this can never become a leak.
1546
+ (
1547
+ JBRuleset memory ruleset,
1548
+ uint256 _reclaim,
1549
+ uint256 cashOutTaxRate,
1550
+ JBCashOutHookSpecification[] memory hookSpecifications
1551
+ ) = _recordAndBurnCashOut({
1552
+ holder: holder,
1553
+ projectId: projectId,
1554
+ cashOutCount: cashOutCount,
1555
+ tokenToReclaim: tokenToReclaim,
1556
+ beneficiaryIsFeeless: true,
1557
+ metadata: cashOutMetadata
1558
+ });
1559
+ reclaimAmount = _reclaim;
1560
+
1561
+ emit CashOutTokens({
1562
+ rulesetId: ruleset.id,
1563
+ rulesetCycleNumber: ruleset.cycleNumber,
1564
+ projectId: projectId,
1565
+ holder: holder,
1566
+ beneficiary: beneficiary,
1567
+ cashOutCount: cashOutCount,
1568
+ cashOutTaxRate: cashOutTaxRate,
1569
+ reclaimAmount: reclaimAmount,
1570
+ metadata: cashOutMetadata,
1571
+ caller: _msgSender()
1572
+ });
1573
+
1574
+ // Only hook-spec amounts are fee-eligible here; the destination portion is intentionally feeless.
1575
+ uint256 amountEligibleForFees;
1339
1576
 
1340
- // Send the fee.
1341
- // If this terminal's token is ETH, send it in msg.value.
1342
- terminal.pay{value: payValue}({
1577
+ // Hook fees still apply (those funds leave the protocol to external hooks). Hook context sees
1578
+ // `address(this)` as the beneficiary since the terminal is custodying the reclaim mid-flow.
1579
+ if (hookSpecifications.length != 0) {
1580
+ amountEligibleForFees = JBCashOutHookSpecsLib.fulfill({
1581
+ feelessAddresses: FEELESS_ADDRESSES,
1343
1582
  projectId: projectId,
1344
- token: token,
1345
- amount: amount,
1346
- beneficiary: beneficiary,
1347
- minReturnedTokens: 0,
1348
- memo: "",
1349
- metadata: metadata
1583
+ beneficiaryReclaimAmount: _tokenAmountOf({
1584
+ projectId: projectId, token: tokenToReclaim, value: reclaimAmount
1585
+ }),
1586
+ holder: holder,
1587
+ cashOutCount: cashOutCount,
1588
+ metadata: cashOutMetadata,
1589
+ ruleset: ruleset,
1590
+ cashOutTaxRate: cashOutTaxRate,
1591
+ beneficiary: payable(address(this)),
1592
+ specifications: hookSpecifications
1350
1593
  });
1594
+ }
1595
+
1596
+ // Cap the source project's fee-free surplus at remaining balance after the outflow. Same invariant as
1597
+ // `_cashOutTokensOf`: every cashout path keeps `_feeFreeSurplusOf[projectId]` consistent with the
1598
+ // post-outflow balance so later zero-tax cashouts from A don't fee phantom amounts.
1599
+ _capFeeFreeSurplus({projectId: projectId, token: tokenToReclaim});
1351
1600
 
1352
- // Revoke the temporary pull allowance now that the recipient terminal call has finished.
1353
- _afterTransferTo({to: address(terminal), token: token});
1601
+ // Take the fee on the hook amounts.
1602
+ if (amountEligibleForFees != 0) {
1603
+ _takeFeeFrom({
1604
+ projectId: projectId,
1605
+ token: tokenToReclaim,
1606
+ amount: amountEligibleForFees,
1607
+ beneficiary: beneficiary,
1608
+ shouldHoldFees: false
1609
+ });
1354
1610
  }
1355
1611
  }
1356
1612
 
@@ -1388,106 +1644,6 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1388
1644
  _afterTransferTo({to: address(terminal), token: token});
1389
1645
  }
1390
1646
 
1391
- /// @notice Fulfills a list of cash out hook specifications.
1392
- /// @param projectId The ID of the project to cash out from.
1393
- /// @param beneficiaryReclaimAmount The number of tokens to cash out from the project.
1394
- /// @param holder The address holding the tokens to cash out.
1395
- /// @param cashOutCount The number of tokens to cash out.
1396
- /// @param metadata Bytes to send along to the emitted event and cash out hooks as applicable.
1397
- /// @param ruleset The ruleset active during this cash out as a `JBRuleset` struct.
1398
- /// @param cashOutTaxRate The cash out tax rate influencing the reclaim amount, out of
1399
- /// `JBConstants.MAX_CASH_OUT_TAX_RATE`. @param beneficiary The address which will receive any terminal tokens that
1400
- /// are cashed out.
1401
- /// @param specifications The hook specifications to fulfill.
1402
- /// @return amountEligibleForFees The amount of funds which were allocated to cash out hooks and are eligible for
1403
- /// fees.
1404
- function _fulfillCashOutHookSpecificationsFor(
1405
- uint256 projectId,
1406
- JBTokenAmount memory beneficiaryReclaimAmount,
1407
- address holder,
1408
- uint256 cashOutCount,
1409
- bytes memory metadata,
1410
- JBRuleset memory ruleset,
1411
- uint256 cashOutTaxRate,
1412
- address payable beneficiary,
1413
- JBCashOutHookSpecification[] memory specifications
1414
- )
1415
- internal
1416
- returns (uint256 amountEligibleForFees)
1417
- {
1418
- // Keep a reference to cash out context for the cash out hooks.
1419
- JBAfterCashOutRecordedContext memory context = JBAfterCashOutRecordedContext({
1420
- holder: holder,
1421
- projectId: projectId,
1422
- rulesetId: ruleset.id,
1423
- cashOutCount: cashOutCount,
1424
- reclaimedAmount: beneficiaryReclaimAmount,
1425
- forwardedAmount: beneficiaryReclaimAmount,
1426
- cashOutTaxRate: cashOutTaxRate,
1427
- beneficiary: beneficiary,
1428
- hookMetadata: "",
1429
- cashOutMetadata: metadata
1430
- });
1431
-
1432
- for (uint256 i; i < specifications.length;) {
1433
- // Set the specification being iterated on.
1434
- JBCashOutHookSpecification memory specification = specifications[i];
1435
-
1436
- // A noop specification is informational only and doesn't trigger the hook.
1437
- if (specification.noop) {
1438
- unchecked {
1439
- ++i;
1440
- }
1441
- continue;
1442
- }
1443
-
1444
- // Get the fee for the specified amount.
1445
- uint256 specificationAmountFee = _isFeeless({addr: address(specification.hook), projectId: projectId})
1446
- ? 0
1447
- : _feeAmountFrom(specification.amount);
1448
-
1449
- // Add the specification's amount to the amount eligible for fees.
1450
- if (specificationAmountFee != 0) {
1451
- amountEligibleForFees += specification.amount;
1452
- specification.amount -= specificationAmountFee;
1453
- }
1454
-
1455
- // Pass the correct token `forwardedAmount` to the hook.
1456
- context.forwardedAmount = JBTokenAmount({
1457
- value: specification.amount,
1458
- token: beneficiaryReclaimAmount.token,
1459
- decimals: beneficiaryReclaimAmount.decimals,
1460
- currency: beneficiaryReclaimAmount.currency
1461
- });
1462
-
1463
- // Pass the correct metadata from the data hook's specification.
1464
- context.hookMetadata = specification.metadata;
1465
-
1466
- // Trigger any inherited pre-transfer logic.
1467
- // Keep a reference to the amount that'll be paid as a `msg.value`.
1468
- uint256 payValue = _beforeTransferTo({
1469
- to: address(specification.hook), token: beneficiaryReclaimAmount.token, amount: specification.amount
1470
- });
1471
-
1472
- // Fulfill the specification.
1473
- specification.hook.afterCashOutRecordedWith{value: payValue}(context);
1474
-
1475
- // Revoke the temporary pull allowance now that the hook call has finished.
1476
- _afterTransferTo({to: address(specification.hook), token: beneficiaryReclaimAmount.token});
1477
-
1478
- emit HookAfterRecordCashOut({
1479
- hook: specification.hook,
1480
- context: context,
1481
- specificationAmount: specification.amount,
1482
- fee: specificationAmountFee,
1483
- caller: _msgSender()
1484
- });
1485
- unchecked {
1486
- ++i;
1487
- }
1488
- }
1489
- }
1490
-
1491
1647
  /// @notice Fulfills a list of pay hook specifications.
1492
1648
  /// @param projectId The ID of the project to pay.
1493
1649
  /// @param specifications The pay hook specifications to be fulfilled.
@@ -1583,6 +1739,7 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1583
1739
  /// applicable.
1584
1740
  /// @param memo A memo to pass along to the emitted event.
1585
1741
  /// @param metadata Bytes to send along to the emitted event, as well as the data hook and pay hook if applicable.
1742
+ /// @return newlyIssuedTokenCount The number of project tokens minted to `beneficiary` as a result of this payment.
1586
1743
  function _pay(
1587
1744
  uint256 projectId,
1588
1745
  address token,
@@ -1593,6 +1750,7 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1593
1750
  bytes memory metadata
1594
1751
  )
1595
1752
  internal
1753
+ returns (uint256 newlyIssuedTokenCount)
1596
1754
  {
1597
1755
  // Keep a reference to the token amount to forward to the store.
1598
1756
  JBTokenAmount memory tokenAmount = _tokenAmountOf({projectId: projectId, token: token, value: amount});
@@ -1605,9 +1763,6 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1605
1763
  payer: payer, amount: tokenAmount, projectId: projectId, beneficiary: beneficiary, metadata: metadata
1606
1764
  });
1607
1765
 
1608
- // Keep a reference to the number of tokens issued for the beneficiary.
1609
- uint256 newlyIssuedTokenCount;
1610
-
1611
1766
  // Mint tokens if needed.
1612
1767
  if (tokenCount != 0) {
1613
1768
  // Set the token count to be the number of tokens minted for the beneficiary instead of the total
@@ -1667,33 +1822,15 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1667
1822
  )
1668
1823
  internal
1669
1824
  {
1670
- try this.executeProcessFee({
1671
- projectId: projectId, token: token, amount: amount, beneficiary: beneficiary, feeTerminal: feeTerminal
1672
- }) {
1673
- emit ProcessFee({
1674
- projectId: projectId,
1675
- token: token,
1676
- amount: amount,
1677
- wasHeld: wasHeld,
1678
- beneficiary: beneficiary,
1679
- caller: _msgSender()
1680
- });
1681
- } catch (bytes memory reason) {
1682
- // Fee processing failed — intentionally forgive the fee and return the amount to the project.
1683
- // The held-fee entry (if any) was already deleted by `processHeldFeesOf` before this call, so there is no
1684
- // retry path. This is by design: a broken or misconfigured fee route should not permanently lock project
1685
- // funds. The `FeeReverted` event makes this observable off-chain.
1686
- emit FeeReverted({
1687
- projectId: projectId,
1688
- token: token,
1689
- feeProjectId: _FEE_BENEFICIARY_PROJECT_ID,
1690
- amount: amount,
1691
- reason: reason,
1692
- caller: _msgSender()
1693
- });
1694
-
1695
- _recordAddedBalanceFor({projectId: projectId, token: token, amount: amount});
1696
- }
1825
+ JBHeldFeesLib.processFee({
1826
+ store: STORE,
1827
+ projectId: projectId,
1828
+ token: token,
1829
+ amount: amount,
1830
+ beneficiary: beneficiary,
1831
+ feeTerminal: feeTerminal,
1832
+ wasHeld: wasHeld
1833
+ });
1697
1834
  }
1698
1835
 
1699
1836
  /// @notice Records an added balance for a project.
@@ -1706,6 +1843,74 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1706
1843
  STORE.recordAddedBalanceFor({projectId: projectId, token: token, amount: amount});
1707
1844
  }
1708
1845
 
1846
+ /// @notice Records a cash out in the terminal store and burns the holder's project tokens.
1847
+ /// @dev Shared between `_cashOutTokensOf` and `_payAfterCashOutTokensOf`. The two flows differ in what
1848
+ /// happens AFTER the burn (where the reclaim goes, how fees are taken), but the record-and-burn step is
1849
+ /// identical.
1850
+ /// @param holder The account whose project tokens are being burned.
1851
+ /// @param projectId The ID of the project the project tokens belong to.
1852
+ /// @param cashOutCount The number of project tokens to burn.
1853
+ /// @param tokenToReclaim The terminal token to reclaim from the project's surplus.
1854
+ /// @param beneficiaryIsFeeless Whether the cash out's beneficiary is a feeless address (passed through
1855
+ /// to the data hook context via the store).
1856
+ /// @param metadata Bytes to send along to the data hook.
1857
+ /// @return ruleset The ruleset the cash out is being made during.
1858
+ /// @return reclaimAmount The amount of terminal tokens to be reclaimed.
1859
+ /// @return cashOutTaxRate The cash out tax rate being used.
1860
+ /// @return hookSpecifications The cash out hook specifications returned by the data hook.
1861
+ function _recordAndBurnCashOut(
1862
+ address holder,
1863
+ uint256 projectId,
1864
+ uint256 cashOutCount,
1865
+ address tokenToReclaim,
1866
+ bool beneficiaryIsFeeless,
1867
+ bytes memory metadata
1868
+ )
1869
+ internal
1870
+ returns (
1871
+ JBRuleset memory ruleset,
1872
+ uint256 reclaimAmount,
1873
+ uint256 cashOutTaxRate,
1874
+ JBCashOutHookSpecification[] memory hookSpecifications
1875
+ )
1876
+ {
1877
+ // Cache the controller to avoid a redundant external call (also used inside STORE.recordCashOutFor).
1878
+ IJBController controller = _controllerOf(projectId);
1879
+
1880
+ // Record the cash out.
1881
+ (ruleset, reclaimAmount, cashOutTaxRate, hookSpecifications) = STORE.recordCashOutFor({
1882
+ holder: holder,
1883
+ projectId: projectId,
1884
+ cashOutCount: cashOutCount,
1885
+ tokenToReclaim: tokenToReclaim,
1886
+ beneficiaryIsFeeless: beneficiaryIsFeeless,
1887
+ metadata: metadata
1888
+ });
1889
+
1890
+ // Burn the project tokens.
1891
+ if (cashOutCount != 0) {
1892
+ controller.burnTokensOf({holder: holder, projectId: projectId, tokenCount: cashOutCount, memo: ""});
1893
+ }
1894
+ }
1895
+
1896
+ /// @notice Resolve B's primary terminal for the reclaim token, reverting if the directory has no entry.
1897
+ /// @dev Shared by `_routeReclaimToBeneficiaryProject` and `_routeReclaimAsAddToBalance`.
1898
+ function _resolveBeneficiaryTerminal(
1899
+ uint256 beneficiaryProjectId,
1900
+ address tokenToReclaim
1901
+ )
1902
+ internal
1903
+ view
1904
+ returns (IJBTerminal destinationTerminal)
1905
+ {
1906
+ destinationTerminal = DIRECTORY.primaryTerminalOf({projectId: beneficiaryProjectId, token: tokenToReclaim});
1907
+ if (address(destinationTerminal) == address(0)) {
1908
+ revert JBMultiTerminal_RecipientProjectTerminalNotFound({
1909
+ projectId: beneficiaryProjectId, token: tokenToReclaim
1910
+ });
1911
+ }
1912
+ }
1913
+
1709
1914
  /// @notice Returns held fees to the project who paid them based on the specified amount.
1710
1915
  /// @dev Partial replenishments use the raw floor calculation so repaying a dust amount cannot both credit the
1711
1916
  /// payer project and leave the fee project owed the 1-unit minimum fee.
@@ -1716,73 +1921,52 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1716
1921
  /// @return returnedFees The amount of held fees that were returned, as a fixed point number with the same number of
1717
1922
  /// decimals as the token's accounting context.
1718
1923
  function _returnHeldFees(uint256 projectId, address token, uint256 amount) internal returns (uint256 returnedFees) {
1719
- // Keep a reference to the start index.
1720
- uint256 startIndex = _nextHeldFeeIndexOf[projectId][token];
1721
-
1722
- // Get a reference to the project's held fees.
1723
- uint256 numberOfHeldFees = _heldFeesOf[projectId][token].length;
1724
-
1725
- // If the start index is greater than or equal to the number of held fees, return 0.
1726
- if (startIndex >= numberOfHeldFees) return 0;
1727
-
1728
- // Get a reference to the leftover amount once all fees have been settled.
1729
- uint256 leftoverAmount = amount;
1730
-
1731
- // Keep a reference to the number of iterations to perform.
1732
- uint256 count = numberOfHeldFees - startIndex;
1733
-
1734
- // Keep a reference to the new start index.
1735
- uint256 newStartIndex = startIndex;
1736
-
1737
- // Process each fee.
1738
- for (uint256 i; i < count;) {
1739
- // Save the fee being iterated on.
1740
- JBFee memory heldFee = _heldFeesOf[projectId][token][startIndex + i];
1741
-
1742
- if (leftoverAmount == 0) {
1743
- break;
1744
- } else {
1745
- // Notice here we take `feeAmountFrom` on the stored `.amount`.
1746
- uint256 feeAmount = _feeAmountFrom(heldFee.amount);
1747
-
1748
- // Keep a reference to the amount from which the fee was taken.
1749
- uint256 amountPaidOut = heldFee.amount - feeAmount;
1750
-
1751
- if (leftoverAmount >= amountPaidOut) {
1752
- unchecked {
1753
- leftoverAmount -= amountPaidOut;
1754
- returnedFees += feeAmount;
1755
- }
1756
-
1757
- // Move the start index forward to the held fee after the current one.
1758
- newStartIndex = startIndex + i + 1;
1759
- } else {
1760
- feeAmount = JBFees.feeAmountResultingIn({amountAfterFee: leftoverAmount, feePercent: FEE});
1761
-
1762
- // Get fee from `leftoverAmount`.
1763
- unchecked {
1764
- _heldFeesOf[projectId][token][startIndex + i].amount -= (leftoverAmount + feeAmount);
1765
- returnedFees += feeAmount;
1766
- }
1767
- leftoverAmount = 0;
1768
- }
1769
- }
1770
- unchecked {
1771
- ++i;
1772
- }
1773
- }
1774
-
1775
- // Update the next held fee index.
1776
- if (startIndex != newStartIndex) _nextHeldFeeIndexOf[projectId][token] = newStartIndex;
1777
-
1778
- emit ReturnHeldFees({
1924
+ returnedFees = JBHeldFeesLib.returnHeldFees({
1925
+ heldFeesOf: _heldFeesOf,
1926
+ nextHeldFeeIndexOf: _nextHeldFeeIndexOf,
1779
1927
  projectId: projectId,
1780
1928
  token: token,
1781
- amount: amount,
1782
- returnedFees: returnedFees,
1783
- leftoverAmount: leftoverAmount,
1784
- caller: _msgSender()
1929
+ amount: amount
1930
+ });
1931
+ }
1932
+
1933
+ /// @notice Routes the cashout reclaim to B's primary terminal as a `pay` and credits B's fee-free
1934
+ /// surplus by the delivery delta on the first of B's accounting contexts that grew.
1935
+ /// @dev Extracted from the external `payAfterCashOutTokensOf` to keep that function under the
1936
+ /// via-IR-free stack ceiling. Uses `_efficientPay` (handles same-terminal vs cross-terminal with
1937
+ /// `_beforeTransferTo`/`_afterTransferTo`). `minReturnedTokens: 0` is enforced inside `_efficientPay`;
1938
+ /// the user-facing mint floor is `_checkMin(beneficiaryTokenCount, minTokensOut)` in the caller.
1939
+ /// @param tokenToReclaim The token reclaimed from the source project.
1940
+ /// @param reclaimAmount The amount of `tokenToReclaim` being routed.
1941
+ /// @param beneficiaryProjectId The destination project.
1942
+ /// @param beneficiary The address that receives the newly minted destination-project tokens.
1943
+ /// @param payMetadata Bytes forwarded to the destination project's pay flow.
1944
+ /// @return beneficiaryTokenCount The number of destination-project tokens minted to `beneficiary`.
1945
+ function _routeReclaimToBeneficiaryProject(
1946
+ address tokenToReclaim,
1947
+ uint256 reclaimAmount,
1948
+ uint256 beneficiaryProjectId,
1949
+ address beneficiary,
1950
+ bytes memory payMetadata
1951
+ )
1952
+ internal
1953
+ returns (uint256 beneficiaryTokenCount)
1954
+ {
1955
+ IJBTerminal destinationTerminal = _resolveBeneficiaryTerminal(beneficiaryProjectId, tokenToReclaim);
1956
+ (JBAccountingContext[] memory contexts, uint256[] memory balancesBefore) =
1957
+ _snapshotBeneficiaryContextBalances(beneficiaryProjectId);
1958
+
1959
+ beneficiaryTokenCount = _efficientPay({
1960
+ terminal: destinationTerminal,
1961
+ projectId: beneficiaryProjectId,
1962
+ token: tokenToReclaim,
1963
+ amount: reclaimAmount,
1964
+ payer: _msgSender(),
1965
+ beneficiary: beneficiary,
1966
+ metadata: payMetadata
1785
1967
  });
1968
+
1969
+ _creditFirstGrowingBeneficiaryContext(beneficiaryProjectId, contexts, balancesBefore);
1786
1970
  }
1787
1971
 
1788
1972
  /// @notice Sends payouts to a project's payout split group using the specified ruleset.
@@ -1901,7 +2085,31 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1901
2085
  });
1902
2086
  }
1903
2087
 
1904
- /// @notice Takes a fee into the platform's project (with the `_FEE_BENEFICIARY_PROJECT_ID`).
2088
+ /// @notice Snapshot B's accounting contexts and pre-routing balances on this terminal.
2089
+ /// @dev Shared by `_routeReclaimToBeneficiaryProject` and `_routeReclaimAsAddToBalance`. Reverts if B has
2090
+ /// no accounting contexts on this terminal — without buckets to deliver into, nothing can land here.
2091
+ function _snapshotBeneficiaryContextBalances(uint256 beneficiaryProjectId)
2092
+ internal
2093
+ view
2094
+ returns (JBAccountingContext[] memory contexts, uint256[] memory balancesBefore)
2095
+ {
2096
+ contexts = STORE.accountingContextsOf({terminal: address(this), projectId: beneficiaryProjectId});
2097
+
2098
+ if (contexts.length == 0) {
2099
+ revert JBMultiTerminal_BeneficiaryProjectHasNoAccountingContexts(beneficiaryProjectId);
2100
+ }
2101
+
2102
+ balancesBefore = new uint256[](contexts.length);
2103
+ for (uint256 i; i < contexts.length;) {
2104
+ balancesBefore[i] =
2105
+ STORE.balanceOf({terminal: address(this), projectId: beneficiaryProjectId, token: contexts[i].token});
2106
+ unchecked {
2107
+ ++i;
2108
+ }
2109
+ }
2110
+ }
2111
+
2112
+ /// @notice Takes a fee into the platform's project (with the `JBConstants.FEE_BENEFICIARY_PROJECT_ID`).
1905
2113
  /// @param projectId The ID of the project paying the fee.
1906
2114
  /// @param token The address of the token that the fee is paid in.
1907
2115
  /// @param amount The fee's token amount, as a fixed point number with 18 decimals.
@@ -1936,13 +2144,14 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
1936
2144
  projectId: projectId,
1937
2145
  token: token,
1938
2146
  amount: amount,
1939
- fee: FEE,
2147
+ fee: JBConstants.FEE,
1940
2148
  beneficiary: beneficiary,
1941
2149
  caller: _msgSender()
1942
2150
  });
1943
2151
  } else {
1944
2152
  // Get the terminal that'll receive the fee if one wasn't provided.
1945
- IJBTerminal feeTerminal = _primaryTerminalOf({projectId: _FEE_BENEFICIARY_PROJECT_ID, token: token});
2153
+ IJBTerminal feeTerminal =
2154
+ _primaryTerminalOf({projectId: JBConstants.FEE_BENEFICIARY_PROJECT_ID, token: token});
1946
2155
 
1947
2156
  // Process the fee.
1948
2157
  _processFee({
@@ -2148,6 +2357,23 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
2148
2357
  return DIRECTORY.primaryTerminalOf({projectId: projectId, token: token});
2149
2358
  }
2150
2359
 
2360
+ /// @notice Revert if the destination project's current ruleset has opted out of cross-project fee-free
2361
+ /// inflows (`pauseCrossProjectFeeFreeInflows == true`). Shared by `payAfterCashOutTokensOf` and
2362
+ /// `addToBalanceAfterCashOutTokensOf`.
2363
+ function _requireBeneficiaryAcceptsFeeFreeInflows(uint256 beneficiaryProjectId) internal view {
2364
+ (, JBRulesetMetadata memory bMetadata) =
2365
+ _controllerOf(beneficiaryProjectId).currentRulesetOf(beneficiaryProjectId);
2366
+ if (bMetadata.pauseCrossProjectFeeFreeInflows) {
2367
+ revert JBMultiTerminal_BeneficiaryProjectFeeFreeInflowsPaused(beneficiaryProjectId);
2368
+ }
2369
+ }
2370
+
2371
+ /// @notice Require the caller to have `CASH_OUT_TOKENS` permission for `holder` on `projectId`. Shared by
2372
+ /// `cashOutTokensOf`, `payAfterCashOutTokensOf`, and `addToBalanceAfterCashOutTokensOf`.
2373
+ function _requireCashOutPermissionFrom(address holder, uint256 projectId) internal view {
2374
+ _requirePermissionFrom({account: holder, projectId: projectId, permissionId: JBPermissionIds.CASH_OUT_TOKENS});
2375
+ }
2376
+
2151
2377
  /// @notice Packages a payment amount with the token's accounting context.
2152
2378
  /// @param projectId The ID of the project the token amount belongs to.
2153
2379
  /// @param token The token to pay with.
@@ -2178,6 +2404,6 @@ contract JBMultiTerminal is JBPermissioned, ERC2771Context, IJBMultiTerminal {
2178
2404
  /// @param amount The amount before the fee is applied.
2179
2405
  /// @return The fee amount.
2180
2406
  function _feeAmountFrom(uint256 amount) private pure returns (uint256) {
2181
- return JBFees.feeAmountFrom({amountBeforeFee: amount, feePercent: FEE});
2407
+ return JBFees.standardFeeAmountFrom(amount);
2182
2408
  }
2183
2409
  }