@rev-net/core-v6 0.0.36 → 0.0.37

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.
Files changed (28) hide show
  1. package/RISKS.md +11 -1
  2. package/package.json +9 -9
  3. package/src/REVLoans.sol +120 -83
  4. package/src/REVOwner.sol +3 -3
  5. package/test/REV.integrations.t.sol +14 -14
  6. package/test/REVInvincibility.t.sol +16 -16
  7. package/test/REVLifecycle.t.sol +32 -32
  8. package/test/REVLoansSourced.t.sol +15 -15
  9. package/test/TestCashOutCallerValidation.t.sol +8 -8
  10. package/test/TestConversionDocumentation.t.sol +2 -5
  11. package/test/TestCrossCurrencyReclaim.t.sol +72 -72
  12. package/test/TestLongTailEconomics.t.sol +56 -56
  13. package/test/TestSwapTerminalPermission.t.sol +21 -21
  14. package/test/audit/HiddenSupplyCashout.t.sol +61 -0
  15. package/test/audit/NemesisVerification.t.sol +97 -0
  16. package/test/audit/REVOwnerCurrencyMismatch.t.sol +188 -0
  17. package/test/audit/{CodexREVOwnerRemoteSurplusCurrencyMismatch.t.sol → REVOwnerRemoteSurplusCurrencyMismatch.t.sol} +4 -6
  18. package/test/audit/ReallocatePermission.t.sol +363 -0
  19. package/test/audit/RemoteLoanAccountingGap.t.sol +74 -0
  20. package/test/fork/TestCashOutFork.t.sol +48 -48
  21. package/test/fork/TestLoanAdversarialFork.t.sol +744 -0
  22. package/test/fork/TestLoanERC20Fork.t.sol +2 -8
  23. package/test/fork/TestPermit2PaymentFork.t.sol +32 -32
  24. package/test/regression/TestBurnPermissionRequired.t.sol +5 -5
  25. package/test/regression/TestCashOutBuybackFeeLeak.t.sol +8 -8
  26. /package/test/audit/{CodexCrossChainBuybackRouteMismatch.t.sol → CrossChainBuybackRouteMismatch.t.sol} +0 -0
  27. /package/test/audit/{NemesisOperatorDelegation.t.sol → OperatorDelegation.t.sol} +0 -0
  28. /package/test/audit/{CodexPhantomSurplusTerminal.t.sol → PhantomSurplusTerminal.t.sol} +0 -0
@@ -0,0 +1,188 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity 0.8.28;
3
+
4
+ import "forge-std/Test.sol";
5
+ import "@bananapus/core-v6/test/helpers/TestBaseWorkflow.sol";
6
+ import {IJBBuybackHookRegistry} from "@bananapus/buyback-hook-v6/src/interfaces/IJBBuybackHookRegistry.sol";
7
+ import {IJBRulesetDataHook} from "@bananapus/core-v6/src/interfaces/IJBRulesetDataHook.sol";
8
+ import {JBBeforeCashOutRecordedContext} from "@bananapus/core-v6/src/structs/JBBeforeCashOutRecordedContext.sol";
9
+ import {JBBeforePayRecordedContext} from "@bananapus/core-v6/src/structs/JBBeforePayRecordedContext.sol";
10
+ import {JBCashOutHookSpecification} from "@bananapus/core-v6/src/structs/JBCashOutHookSpecification.sol";
11
+ import {JBPayHookSpecification} from "@bananapus/core-v6/src/structs/JBPayHookSpecification.sol";
12
+ import {JBTokenAmount} from "@bananapus/core-v6/src/structs/JBTokenAmount.sol";
13
+ import {JBRuleset} from "@bananapus/core-v6/src/structs/JBRuleset.sol";
14
+ import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
15
+ import {IJBSuckerRegistry} from "@bananapus/suckers-v6/src/interfaces/IJBSuckerRegistry.sol";
16
+ import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
17
+ import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
18
+
19
+ import {REVOwner} from "../../src/REVOwner.sol";
20
+
21
+ /// @notice Mock sucker registry that returns configurable remote values.
22
+ /// @dev All functions are view/pure to avoid StateChangeDuringStaticCall when called from
23
+ /// REVOwner.beforeCashOutRecordedWith (which is a view function).
24
+ contract MockSuckerRegistry {
25
+ uint256 public remoteSurplusToReturn;
26
+ uint256 public remoteSupplyToReturn;
27
+
28
+ function setRemoteValues(uint256 supply, uint256 surplus) external {
29
+ remoteSupplyToReturn = supply;
30
+ remoteSurplusToReturn = surplus;
31
+ }
32
+
33
+ function isSuckerOf(uint256, address) external pure returns (bool) {
34
+ return false;
35
+ }
36
+
37
+ function remoteTotalSupplyOf(uint256) external view returns (uint256) {
38
+ return remoteSupplyToReturn;
39
+ }
40
+
41
+ function remoteSurplusOf(uint256, uint256, uint256) external view returns (uint256) {
42
+ return remoteSurplusToReturn;
43
+ }
44
+ }
45
+
46
+ /// @notice Minimal echo buyback registry that passes through cash out context unchanged.
47
+ contract EchoBuybackRegistry is IJBRulesetDataHook {
48
+ function beforeCashOutRecordedWith(JBBeforeCashOutRecordedContext calldata context)
49
+ external
50
+ pure
51
+ returns (
52
+ uint256 cashOutTaxRate,
53
+ uint256 cashOutCount,
54
+ uint256 totalSupply,
55
+ uint256 effectiveSurplusValue,
56
+ JBCashOutHookSpecification[] memory hookSpecifications
57
+ )
58
+ {
59
+ cashOutTaxRate = context.cashOutTaxRate;
60
+ cashOutCount = context.cashOutCount;
61
+ totalSupply = context.totalSupply;
62
+ effectiveSurplusValue = context.surplus.value;
63
+ hookSpecifications = new JBCashOutHookSpecification[](0);
64
+ }
65
+
66
+ function beforePayRecordedWith(JBBeforePayRecordedContext calldata context)
67
+ external
68
+ pure
69
+ returns (uint256 weight, JBPayHookSpecification[] memory hookSpecifications)
70
+ {
71
+ weight = context.weight;
72
+ hookSpecifications = new JBPayHookSpecification[](0);
73
+ }
74
+
75
+ function hasMintPermissionFor(uint256, JBRuleset calldata, address) external pure returns (bool) {
76
+ return false;
77
+ }
78
+
79
+ function setPoolFor(uint256, PoolKey calldata, uint256, address) external pure {}
80
+ function setPoolFor(uint256, uint24, int24, uint256, address) external pure {}
81
+ function initializePoolFor(uint256, uint24, int24, uint256, address, uint160) external pure {}
82
+
83
+ function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
84
+ return interfaceId == type(IJBRulesetDataHook).interfaceId || interfaceId == type(IERC165).interfaceId;
85
+ }
86
+ }
87
+
88
+ /// @notice REVOwner.beforeCashOutRecordedWith should pass the surplus currency (not the token address) to
89
+ /// remoteSurplusOf. @dev `currency: uint256(context.surplus.currency)` passes the correct currency value,
90
+ /// not `uint256(uint160(context.surplus.token))` which would pass the token address (e.g. 61166 for NATIVE_TOKEN).
91
+ contract REVOwnerCurrencyMismatchTest is TestBaseWorkflow {
92
+ REVOwner internal ownerHook;
93
+ MockSuckerRegistry internal suckerRegistry;
94
+ EchoBuybackRegistry internal buybackRegistry;
95
+
96
+ function setUp() public override {
97
+ super.setUp();
98
+
99
+ suckerRegistry = new MockSuckerRegistry();
100
+ buybackRegistry = new EchoBuybackRegistry();
101
+
102
+ ownerHook = new REVOwner(
103
+ IJBBuybackHookRegistry(address(buybackRegistry)),
104
+ jbDirectory(),
105
+ 999_999, // fee revnet ID (won't be used in this test path)
106
+ IJBSuckerRegistry(address(suckerRegistry)),
107
+ address(0), // loans
108
+ address(0) // hidden tokens
109
+ );
110
+ }
111
+
112
+ /// @notice Verify that remoteSurplusOf is called with the context's currency, not the token address.
113
+ /// @dev NATIVE_TOKEN = 0x000000000000000000000000000000000000EEEe
114
+ /// uint160(NATIVE_TOKEN) = 61166
115
+ /// The correct currency for ETH is 1 (baseCurrency).
116
+ /// Before the fix, 61166 was passed. After the fix, 1 is passed.
117
+ function test_remoteSurplusOf_receives_currency_not_token_address() public {
118
+ // Set up remote values so the registry returns something.
119
+ suckerRegistry.setRemoteValues(500 ether, 900 ether);
120
+
121
+ uint32 ethCurrency = 1; // ETH baseCurrency identifier
122
+
123
+ // Build a context where surplus.token = NATIVE_TOKEN and surplus.currency = 1 (ETH).
124
+ // These are intentionally different values to detect the bug.
125
+ JBBeforeCashOutRecordedContext memory context = JBBeforeCashOutRecordedContext({
126
+ terminal: address(jbMultiTerminal()),
127
+ holder: address(0xCAFE),
128
+ projectId: 1,
129
+ rulesetId: 0,
130
+ cashOutCount: 100 ether,
131
+ totalSupply: 1000 ether,
132
+ surplus: JBTokenAmount({
133
+ token: JBConstants.NATIVE_TOKEN, // 0xEEEe
134
+ value: 100 ether,
135
+ decimals: 18,
136
+ currency: ethCurrency // 1
137
+ }),
138
+ useTotalSurplus: true,
139
+ cashOutTaxRate: 0, // zero tax = feeless path (simpler, avoids needing fee terminal)
140
+ beneficiaryIsFeeless: false,
141
+ metadata: ""
142
+ });
143
+
144
+ // Use vm.expectCall to verify the exact parameters passed to remoteSurplusOf.
145
+ // After fix: currency should be 1 (ethCurrency), NOT 61166 (uint160(NATIVE_TOKEN)).
146
+ // This assertion will fail if the buggy code passes uint256(uint160(NATIVE_TOKEN)) = 61166.
147
+ vm.expectCall(
148
+ address(suckerRegistry), abi.encodeCall(suckerRegistry.remoteSurplusOf, (1, 18, uint256(ethCurrency)))
149
+ );
150
+
151
+ ownerHook.beforeCashOutRecordedWith(context);
152
+ }
153
+
154
+ /// @notice Verify that the remote surplus is actually included in the returned effectiveSurplusValue.
155
+ /// @dev This is a regression test: if the wrong currency is passed, the registry might return 0
156
+ /// and the remote surplus would be silently dropped.
157
+ function test_remoteSurplus_included_in_effectiveSurplus() public {
158
+ suckerRegistry.setRemoteValues(500 ether, 900 ether);
159
+
160
+ uint32 ethCurrency = 1;
161
+
162
+ JBBeforeCashOutRecordedContext memory context = JBBeforeCashOutRecordedContext({
163
+ terminal: address(jbMultiTerminal()),
164
+ holder: address(0xCAFE),
165
+ projectId: 1,
166
+ rulesetId: 0,
167
+ cashOutCount: 100 ether,
168
+ totalSupply: 1000 ether,
169
+ surplus: JBTokenAmount({
170
+ token: JBConstants.NATIVE_TOKEN, value: 100 ether, decimals: 18, currency: ethCurrency
171
+ }),
172
+ useTotalSurplus: true,
173
+ cashOutTaxRate: 0,
174
+ beneficiaryIsFeeless: false,
175
+ metadata: ""
176
+ });
177
+
178
+ (,, uint256 returnedSupply, uint256 returnedSurplus,) = ownerHook.beforeCashOutRecordedWith(context);
179
+
180
+ // Remote supply should be added.
181
+ assertEq(returnedSupply, 1500 ether, "totalSupply should include remote supply");
182
+
183
+ // Remote surplus should be added (100 local + 900 remote = 1000).
184
+ assertEq(
185
+ returnedSurplus, 1000 ether, "effectiveSurplusValue should include remote surplus (100 local + 900 remote)"
186
+ );
187
+ }
188
+ }
@@ -83,7 +83,7 @@ contract EchoBuybackRegistry is IJBRulesetDataHook {
83
83
  }
84
84
  }
85
85
 
86
- contract CodexREVOwnerRemoteSurplusCurrencyMismatchTest is TestBaseWorkflow {
86
+ contract REVOwnerRemoteSurplusCurrencyMismatchTest is TestBaseWorkflow {
87
87
  REVOwner internal ownerHook;
88
88
  CurrencyAwareSuckerRegistry internal suckerRegistry;
89
89
  EchoBuybackRegistry internal buybackRegistry;
@@ -128,11 +128,9 @@ contract CodexREVOwnerRemoteSurplusCurrencyMismatchTest is TestBaseWorkflow {
128
128
  (,, uint256 returnedSupply, uint256 returnedSurplus,) = ownerHook.beforeCashOutRecordedWith(context);
129
129
 
130
130
  assertEq(returnedSupply, 1500 ether, "remote supply should still be included");
131
- assertEq(
132
- returnedSurplus,
133
- 100 ether,
134
- "remote surplus is incorrectly dropped because REVOwner keys by token address instead of currency"
135
- );
131
+ // Remote surplus is correctly included (100 local + 900 remote = 1000) because the currency is passed to
132
+ // remoteSurplusOf.
133
+ assertEq(returnedSurplus, 1000 ether, "remote surplus should be included now that currency is passed correctly");
136
134
  assertEq(
137
135
  suckerRegistry.remoteSurplusOf(1, 18, ETH_CURRENCY),
138
136
  900 ether,
@@ -0,0 +1,363 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity 0.8.28;
3
+
4
+ // forge-lint: disable-next-line(unaliased-plain-import)
5
+ import "forge-std/Test.sol";
6
+ // forge-lint: disable-next-line(unaliased-plain-import)
7
+ import /* {*} from */ "@bananapus/core-v6/test/helpers/TestBaseWorkflow.sol";
8
+ // forge-lint: disable-next-line(unaliased-plain-import)
9
+ import /* {*} from */ "../../src/REVDeployer.sol";
10
+ // forge-lint: disable-next-line(unaliased-plain-import)
11
+ import "@croptop/core-v6/src/CTPublisher.sol";
12
+ import {MockBuybackDataHook} from "../mock/MockBuybackDataHook.sol";
13
+ import {REVEmpty721Config} from "../helpers/REVEmpty721Config.sol";
14
+ // forge-lint: disable-next-line(unaliased-plain-import)
15
+ import "@bananapus/core-v6/script/helpers/CoreDeploymentLib.sol";
16
+ // forge-lint: disable-next-line(unaliased-plain-import)
17
+ import "@bananapus/721-hook-v6/script/helpers/Hook721DeploymentLib.sol";
18
+ // forge-lint: disable-next-line(unaliased-plain-import)
19
+ import "@bananapus/suckers-v6/script/helpers/SuckerDeploymentLib.sol";
20
+ // forge-lint: disable-next-line(unaliased-plain-import)
21
+ import "@croptop/core-v6/script/helpers/CroptopDeploymentLib.sol";
22
+ // forge-lint: disable-next-line(unaliased-plain-import)
23
+ import "@bananapus/router-terminal-v6/script/helpers/RouterTerminalDeploymentLib.sol";
24
+ import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
25
+ import {JBAccountingContext} from "@bananapus/core-v6/src/structs/JBAccountingContext.sol";
26
+ import {JBPermissioned} from "@bananapus/core-v6/src/abstract/JBPermissioned.sol";
27
+ import {JBPermissionIds} from "@bananapus/permission-ids-v6/src/JBPermissionIds.sol";
28
+ import {JBPermissionsData} from "@bananapus/core-v6/src/structs/JBPermissionsData.sol";
29
+ import {REVLoans} from "../../src/REVLoans.sol";
30
+ import {REVLoan} from "../../src/structs/REVLoan.sol";
31
+ import {REVStageConfig, REVAutoIssuance} from "../../src/structs/REVStageConfig.sol";
32
+ import {REVLoanSource} from "../../src/structs/REVLoanSource.sol";
33
+ import {REVDescription} from "../../src/structs/REVDescription.sol";
34
+ import {IREVLoans} from "../../src/interfaces/IREVLoans.sol";
35
+ import {JBSuckerDeployerConfig} from "@bananapus/suckers-v6/src/structs/JBSuckerDeployerConfig.sol";
36
+ import {JBSuckerRegistry} from "@bananapus/suckers-v6/src/JBSuckerRegistry.sol";
37
+ import {JB721TiersHookDeployer} from "@bananapus/721-hook-v6/src/JB721TiersHookDeployer.sol";
38
+ import {JB721TiersHook} from "@bananapus/721-hook-v6/src/JB721TiersHook.sol";
39
+ import {JB721TiersHookStore} from "@bananapus/721-hook-v6/src/JB721TiersHookStore.sol";
40
+ import {JB721CheckpointsDeployer} from "@bananapus/721-hook-v6/src/JB721CheckpointsDeployer.sol";
41
+ import {IJB721CheckpointsDeployer} from "@bananapus/721-hook-v6/src/interfaces/IJB721CheckpointsDeployer.sol";
42
+ import {JBAddressRegistry} from "@bananapus/address-registry-v6/src/JBAddressRegistry.sol";
43
+ import {IJBAddressRegistry} from "@bananapus/address-registry-v6/src/interfaces/IJBAddressRegistry.sol";
44
+ import {REVOwner} from "../../src/REVOwner.sol";
45
+ import {IREVDeployer} from "../../src/interfaces/IREVDeployer.sol";
46
+ import {MockSuckerRegistry} from "../mock/MockSuckerRegistry.sol";
47
+
48
+ /// @notice Verify that reallocateCollateralFromLoan works with only REALLOCATE_LOAN permission,
49
+ /// without requiring OPEN_LOAN. Also verify that borrowFrom still requires OPEN_LOAN (regression).
50
+ contract ReallocatePermissionTest is TestBaseWorkflow {
51
+ // forge-lint: disable-next-line(mixed-case-variable)
52
+ bytes32 REV_DEPLOYER_SALT = "REVDeployer";
53
+
54
+ // forge-lint: disable-next-line(mixed-case-variable)
55
+ REVDeployer REV_DEPLOYER;
56
+ // forge-lint: disable-next-line(mixed-case-variable)
57
+ REVOwner REV_OWNER;
58
+ // forge-lint: disable-next-line(mixed-case-variable)
59
+ JB721TiersHook EXAMPLE_HOOK;
60
+ // forge-lint: disable-next-line(mixed-case-variable)
61
+ IJB721TiersHookDeployer HOOK_DEPLOYER;
62
+ // forge-lint: disable-next-line(mixed-case-variable)
63
+ IJB721TiersHookStore HOOK_STORE;
64
+ // forge-lint: disable-next-line(mixed-case-variable)
65
+ IJBAddressRegistry ADDRESS_REGISTRY;
66
+ // forge-lint: disable-next-line(mixed-case-variable)
67
+ IREVLoans LOANS_CONTRACT;
68
+ // forge-lint: disable-next-line(mixed-case-variable)
69
+ IJBSuckerRegistry SUCKER_REGISTRY;
70
+ // forge-lint: disable-next-line(mixed-case-variable)
71
+ CTPublisher PUBLISHER;
72
+ // forge-lint: disable-next-line(mixed-case-variable)
73
+ MockBuybackDataHook MOCK_BUYBACK;
74
+
75
+ // forge-lint: disable-next-line(mixed-case-variable)
76
+ uint256 FEE_PROJECT_ID;
77
+ // forge-lint: disable-next-line(mixed-case-variable)
78
+ uint256 REVNET_ID;
79
+
80
+ // forge-lint: disable-next-line(mixed-case-variable)
81
+ address HOLDER = makeAddr("holder");
82
+ // forge-lint: disable-next-line(mixed-case-variable)
83
+ address OPERATOR = makeAddr("operator");
84
+
85
+ address private constant TRUSTED_FORWARDER = 0xB2b5841DBeF766d4b521221732F9B618fCf34A87;
86
+
87
+ function setUp() public override {
88
+ super.setUp();
89
+
90
+ FEE_PROJECT_ID = jbProjects().createFor(multisig());
91
+ SUCKER_REGISTRY = new JBSuckerRegistry(jbDirectory(), jbPermissions(), multisig(), address(0));
92
+ HOOK_STORE = new JB721TiersHookStore();
93
+ EXAMPLE_HOOK = new JB721TiersHook(
94
+ jbDirectory(),
95
+ jbPermissions(),
96
+ jbPrices(),
97
+ jbRulesets(),
98
+ HOOK_STORE,
99
+ jbSplits(),
100
+ IJB721CheckpointsDeployer(address(new JB721CheckpointsDeployer())),
101
+ multisig()
102
+ );
103
+ ADDRESS_REGISTRY = new JBAddressRegistry();
104
+ HOOK_DEPLOYER = new JB721TiersHookDeployer(EXAMPLE_HOOK, HOOK_STORE, ADDRESS_REGISTRY, multisig());
105
+ PUBLISHER = new CTPublisher(jbDirectory(), jbPermissions(), FEE_PROJECT_ID, multisig());
106
+ MOCK_BUYBACK = new MockBuybackDataHook();
107
+
108
+ LOANS_CONTRACT = new REVLoans({
109
+ controller: jbController(),
110
+ suckerRegistry: IJBSuckerRegistry(address(new MockSuckerRegistry())),
111
+ revId: FEE_PROJECT_ID,
112
+ owner: address(this),
113
+ permit2: permit2(),
114
+ trustedForwarder: TRUSTED_FORWARDER
115
+ });
116
+
117
+ REV_OWNER = new REVOwner(
118
+ IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
119
+ jbDirectory(),
120
+ FEE_PROJECT_ID,
121
+ SUCKER_REGISTRY,
122
+ address(LOANS_CONTRACT),
123
+ address(0)
124
+ );
125
+
126
+ REV_DEPLOYER = new REVDeployer{salt: REV_DEPLOYER_SALT}(
127
+ jbController(),
128
+ SUCKER_REGISTRY,
129
+ FEE_PROJECT_ID,
130
+ HOOK_DEPLOYER,
131
+ PUBLISHER,
132
+ IJBBuybackHookRegistry(address(MOCK_BUYBACK)),
133
+ address(LOANS_CONTRACT),
134
+ TRUSTED_FORWARDER,
135
+ address(REV_OWNER)
136
+ );
137
+
138
+ REV_OWNER.setDeployer(REV_DEPLOYER);
139
+
140
+ vm.prank(multisig());
141
+ jbProjects().approve(address(REV_DEPLOYER), FEE_PROJECT_ID);
142
+
143
+ _deployFeeProject();
144
+ _deployRevnet();
145
+
146
+ vm.deal(HOLDER, 1000 ether);
147
+ vm.deal(OPERATOR, 100 ether);
148
+ }
149
+
150
+ function _deployFeeProject() internal {
151
+ JBAccountingContext[] memory acc = new JBAccountingContext[](1);
152
+ acc[0] = JBAccountingContext({
153
+ token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
154
+ });
155
+ JBTerminalConfig[] memory tc = new JBTerminalConfig[](1);
156
+ tc[0] = JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: acc});
157
+
158
+ JBSplit[] memory splits = new JBSplit[](1);
159
+ splits[0].beneficiary = payable(multisig());
160
+ splits[0].percent = 10_000;
161
+
162
+ REVAutoIssuance[] memory ai = new REVAutoIssuance[](1);
163
+ ai[0] = REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(70_000e18), beneficiary: multisig()});
164
+
165
+ REVStageConfig[] memory stages = new REVStageConfig[](1);
166
+ stages[0] = REVStageConfig({
167
+ startsAtOrAfter: uint40(block.timestamp),
168
+ autoIssuances: ai,
169
+ splitPercent: 2000,
170
+ splits: splits,
171
+ initialIssuance: uint112(1000e18),
172
+ issuanceCutFrequency: 90 days,
173
+ issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
174
+ cashOutTaxRate: 6000,
175
+ extraMetadata: 0
176
+ });
177
+
178
+ REVConfig memory cfg = REVConfig({
179
+ description: REVDescription("Revnet", "$REV", "ipfs://test", "REV_TOKEN"),
180
+ baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
181
+ splitOperator: multisig(),
182
+ stageConfigurations: stages
183
+ });
184
+
185
+ vm.prank(multisig());
186
+ REV_DEPLOYER.deployFor({
187
+ revnetId: FEE_PROJECT_ID,
188
+ configuration: cfg,
189
+ terminalConfigurations: tc,
190
+ suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
191
+ deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256("FEE")
192
+ }),
193
+ tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
194
+ allowedPosts: REVEmpty721Config.emptyAllowedPosts()
195
+ });
196
+ }
197
+
198
+ function _deployRevnet() internal {
199
+ JBAccountingContext[] memory acc = new JBAccountingContext[](1);
200
+ acc[0] = JBAccountingContext({
201
+ token: JBConstants.NATIVE_TOKEN, decimals: 18, currency: uint32(uint160(JBConstants.NATIVE_TOKEN))
202
+ });
203
+ JBTerminalConfig[] memory tc = new JBTerminalConfig[](1);
204
+ tc[0] = JBTerminalConfig({terminal: jbMultiTerminal(), accountingContextsToAccept: acc});
205
+
206
+ JBSplit[] memory splits = new JBSplit[](1);
207
+ splits[0].beneficiary = payable(multisig());
208
+ splits[0].percent = 10_000;
209
+
210
+ REVAutoIssuance[] memory ai = new REVAutoIssuance[](1);
211
+ ai[0] = REVAutoIssuance({chainId: uint32(block.chainid), count: uint104(70_000e18), beneficiary: multisig()});
212
+
213
+ REVStageConfig[] memory stages = new REVStageConfig[](1);
214
+ stages[0] = REVStageConfig({
215
+ startsAtOrAfter: uint40(block.timestamp),
216
+ autoIssuances: ai,
217
+ splitPercent: 2000,
218
+ splits: splits,
219
+ initialIssuance: uint112(1000e18),
220
+ issuanceCutFrequency: 90 days,
221
+ issuanceCutPercent: JBConstants.MAX_WEIGHT_CUT_PERCENT / 2,
222
+ cashOutTaxRate: 6000,
223
+ extraMetadata: 0
224
+ });
225
+
226
+ REVConfig memory cfg = REVConfig({
227
+ description: REVDescription("NANA", "$NANA", "ipfs://test2", "NANA_TOKEN"),
228
+ baseCurrency: uint32(uint160(JBConstants.NATIVE_TOKEN)),
229
+ splitOperator: multisig(),
230
+ stageConfigurations: stages
231
+ });
232
+
233
+ (REVNET_ID,) = REV_DEPLOYER.deployFor({
234
+ revnetId: 0,
235
+ configuration: cfg,
236
+ terminalConfigurations: tc,
237
+ suckerDeploymentConfiguration: REVSuckerDeploymentConfig({
238
+ deployerConfigurations: new JBSuckerDeployerConfig[](0), salt: keccak256("NANA")
239
+ }),
240
+ tiered721HookConfiguration: REVEmpty721Config.empty721Config(uint32(uint160(JBConstants.NATIVE_TOKEN))),
241
+ allowedPosts: REVEmpty721Config.emptyAllowedPosts()
242
+ });
243
+ }
244
+
245
+ /// @notice Helper: Grant a specific permission to an operator for HOLDER on REVNET_ID using real JBPermissions.
246
+ function _grantPermission(address operator, uint256 permissionId) internal {
247
+ uint8[] memory permissionIds = new uint8[](1);
248
+ permissionIds[0] = uint8(permissionId);
249
+ vm.prank(HOLDER);
250
+ jbPermissions()
251
+ .setPermissionsFor({
252
+ account: HOLDER,
253
+ permissionsData: JBPermissionsData({
254
+ operator: operator, projectId: uint64(REVNET_ID), permissionIds: permissionIds
255
+ })
256
+ });
257
+ }
258
+
259
+ /// @notice Helper: create an initial loan for the HOLDER.
260
+ function _createInitialLoan() internal returns (uint256 loanId, uint256 tokenCount) {
261
+ // HOLDER pays into the revnet to get tokens.
262
+ vm.prank(HOLDER);
263
+ tokenCount =
264
+ jbMultiTerminal().pay{value: 10 ether}(REVNET_ID, JBConstants.NATIVE_TOKEN, 10 ether, HOLDER, 0, "", "");
265
+
266
+ // Grant LOANS_CONTRACT the BURN_TOKENS permission so it can burn HOLDER's tokens as collateral.
267
+ _grantPermission(address(LOANS_CONTRACT), JBPermissionIds.BURN_TOKENS);
268
+
269
+ // HOLDER calls borrowFrom directly (sender == holder, so OPEN_LOAN check is short-circuited).
270
+ REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
271
+
272
+ vm.prank(HOLDER);
273
+ (loanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, source, 0, tokenCount, payable(HOLDER), 25, HOLDER);
274
+ }
275
+
276
+ /// @notice After fix: an operator with only REALLOCATE_LOAN permission can reallocate.
277
+ /// @dev Before the fix, this would revert because the inner borrowFrom call required OPEN_LOAN.
278
+ function test_reallocate_succeeds_with_only_REALLOCATE_LOAN_permission() public {
279
+ (uint256 loanId,) = _createInitialLoan();
280
+ require(loanId != 0, "Loan setup failed");
281
+
282
+ // Donate to inflate surplus so collateral reallocation is meaningful.
283
+ address donor = makeAddr("donor");
284
+ vm.deal(donor, 500 ether);
285
+ vm.prank(donor);
286
+ jbMultiTerminal().addToBalanceOf{value: 500 ether}(
287
+ REVNET_ID, JBConstants.NATIVE_TOKEN, 500 ether, false, "", ""
288
+ );
289
+
290
+ // HOLDER pays more to get extra tokens for the new loan's additional collateral.
291
+ vm.prank(HOLDER);
292
+ uint256 extraTokens =
293
+ jbMultiTerminal().pay{value: 50 ether}(REVNET_ID, JBConstants.NATIVE_TOKEN, 50 ether, HOLDER, 0, "", "");
294
+
295
+ // Get the loan's collateral count.
296
+ REVLoan memory loan = LOANS_CONTRACT.loanOf(loanId);
297
+ uint256 collateralToTransfer = loan.collateral / 10;
298
+
299
+ REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
300
+
301
+ // Grant OPERATOR only REALLOCATE_LOAN permission (NOT OPEN_LOAN).
302
+ _grantPermission(OPERATOR, JBPermissionIds.REALLOCATE_LOAN);
303
+
304
+ // This should succeed: OPERATOR has REALLOCATE_LOAN, and _borrowFrom skips OPEN_LOAN check.
305
+ vm.prank(OPERATOR);
306
+ (uint256 reallocatedLoanId, uint256 newLoanId,,) = LOANS_CONTRACT.reallocateCollateralFromLoan(
307
+ loanId,
308
+ collateralToTransfer,
309
+ source,
310
+ 0, // minBorrowAmount
311
+ extraTokens,
312
+ payable(HOLDER),
313
+ 25 // prepaidFeePercent
314
+ );
315
+
316
+ // Verify both loans were created.
317
+ assertTrue(reallocatedLoanId != 0, "Reallocated loan should exist");
318
+ assertTrue(newLoanId != 0, "New loan should exist");
319
+ }
320
+
321
+ /// @notice Regression: borrowFrom still requires OPEN_LOAN permission.
322
+ /// @dev An operator with only REALLOCATE_LOAN should NOT be able to call borrowFrom directly.
323
+ function test_borrowFrom_still_requires_OPEN_LOAN() public {
324
+ // HOLDER pays into the revnet.
325
+ vm.prank(HOLDER);
326
+ uint256 tokenCount =
327
+ jbMultiTerminal().pay{value: 10 ether}(REVNET_ID, JBConstants.NATIVE_TOKEN, 10 ether, HOLDER, 0, "", "");
328
+
329
+ REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
330
+
331
+ // OPERATOR does NOT have OPEN_LOAN permission (no permission granted at all).
332
+ vm.prank(OPERATOR);
333
+ vm.expectRevert(
334
+ abi.encodeWithSelector(
335
+ JBPermissioned.JBPermissioned_Unauthorized.selector,
336
+ HOLDER, // account
337
+ OPERATOR, // sender
338
+ REVNET_ID, // projectId
339
+ JBPermissionIds.OPEN_LOAN // permissionId
340
+ )
341
+ );
342
+ LOANS_CONTRACT.borrowFrom(REVNET_ID, source, 0, tokenCount, payable(HOLDER), 25, HOLDER);
343
+ }
344
+
345
+ /// @notice Verify that borrowFrom succeeds when the caller has OPEN_LOAN permission.
346
+ function test_borrowFrom_succeeds_with_OPEN_LOAN() public {
347
+ // HOLDER pays into the revnet.
348
+ vm.prank(HOLDER);
349
+ uint256 tokenCount =
350
+ jbMultiTerminal().pay{value: 10 ether}(REVNET_ID, JBConstants.NATIVE_TOKEN, 10 ether, HOLDER, 0, "", "");
351
+
352
+ REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
353
+
354
+ // Grant OPERATOR the OPEN_LOAN permission.
355
+ _grantPermission(OPERATOR, JBPermissionIds.OPEN_LOAN);
356
+ // Grant LOANS_CONTRACT the BURN_TOKENS permission so it can burn tokens for collateral.
357
+ _grantPermission(address(LOANS_CONTRACT), JBPermissionIds.BURN_TOKENS);
358
+
359
+ vm.prank(OPERATOR);
360
+ (uint256 loanId,) = LOANS_CONTRACT.borrowFrom(REVNET_ID, source, 0, tokenCount, payable(HOLDER), 25, HOLDER);
361
+ assertTrue(loanId != 0, "Loan should be created successfully");
362
+ }
363
+ }
@@ -0,0 +1,74 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity 0.8.28;
3
+
4
+ import {TestAuditFixVerification} from "../TestAuditFixVerification.t.sol";
5
+ import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
6
+ import {JBCashOuts} from "@bananapus/core-v6/src/libraries/JBCashOuts.sol";
7
+ import {JBPermissionIds} from "@bananapus/permission-ids-v6/src/JBPermissionIds.sol";
8
+ import {JBPermissionsData} from "@bananapus/core-v6/src/structs/JBPermissionsData.sol";
9
+ import {REVLoanSource} from "../../src/structs/REVLoanSource.sol";
10
+ import {REVLoan} from "../../src/structs/REVLoan.sol";
11
+
12
+ contract CodexRemoteLoanAccountingGap is TestAuditFixVerification {
13
+ function test_remoteLoanStateInflatesLocalBorrowability() public {
14
+ uint256 payAmount = 100 ether;
15
+
16
+ vm.prank(USER);
17
+ uint256 tokens =
18
+ jbMultiTerminal().pay{value: payAmount}(REVNET_ID, JBConstants.NATIVE_TOKEN, payAmount, USER, 0, "", "");
19
+
20
+ // Simulate a peer chain that started from 100 ETH / 100k tokens, then originated a loan against
21
+ // 50k burned-collateral tokens. The registry only exports the raw post-loan values, not the
22
+ // remote loan's economic adjustments.
23
+ uint256 remoteRawSupply = 50_000e18;
24
+ uint256 remoteRawSurplus = 62.5e18;
25
+ uint256 remoteLoanCollateral = 50_000e18;
26
+ uint256 remoteLoanDebt = 37.5e18;
27
+ MOCK_SUCKER_REGISTRY.setRemoteValues(remoteRawSupply, remoteRawSurplus);
28
+
29
+ uint256 collateral = tokens / 10;
30
+ uint256 actualBorrowable =
31
+ LOANS_CONTRACT.borrowableAmountFrom(REVNET_ID, collateral, 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
32
+
33
+ uint256 localSupply = jbController().totalTokenSupplyWithReservedTokensOf(REVNET_ID);
34
+ uint256 localSurplus = jbMultiTerminal()
35
+ .currentSurplusOf(REVNET_ID, new address[](0), 18, uint32(uint160(JBConstants.NATIVE_TOKEN)));
36
+
37
+ uint256 correctedBorrowable = JBCashOuts.cashOutFrom({
38
+ surplus: localSurplus + remoteRawSurplus + remoteLoanDebt,
39
+ cashOutCount: collateral,
40
+ totalSupply: localSupply + remoteRawSupply + remoteLoanCollateral,
41
+ cashOutTaxRate: 5000
42
+ });
43
+
44
+ if (correctedBorrowable > localSurplus) correctedBorrowable = localSurplus;
45
+
46
+ assertGt(actualBorrowable, correctedBorrowable, "raw remote values should overstate borrowability");
47
+
48
+ _grantLoansBurnPermission(USER, REVNET_ID);
49
+
50
+ REVLoanSource memory source = REVLoanSource({token: JBConstants.NATIVE_TOKEN, terminal: jbMultiTerminal()});
51
+
52
+ vm.prank(USER);
53
+ (, REVLoan memory loan) =
54
+ LOANS_CONTRACT.borrowFrom(REVNET_ID, source, actualBorrowable, collateral, payable(USER), 25, USER);
55
+
56
+ assertEq(loan.amount, actualBorrowable, "loan should be opened at the inflated amount");
57
+ assertGt(loan.amount, correctedBorrowable, "loan exceeds the corrected omnichain value");
58
+ }
59
+
60
+ function _grantLoansBurnPermission(address account, uint256 revnetId) internal {
61
+ uint8[] memory permissionIds = new uint8[](1);
62
+ permissionIds[0] = JBPermissionIds.BURN_TOKENS;
63
+
64
+ JBPermissionsData memory permissionsData = JBPermissionsData({
65
+ operator: address(LOANS_CONTRACT),
66
+ // forge-lint: disable-next-line(unsafe-typecast)
67
+ projectId: uint56(revnetId),
68
+ permissionIds: permissionIds
69
+ });
70
+
71
+ vm.prank(account);
72
+ jbPermissions().setPermissionsFor(account, permissionsData);
73
+ }
74
+ }