Commit graph

147 commits

Author SHA1 Message Date
openhands
e28e69c98a fix: guard int128 overflow in ThreePositionStrategy mirror tick (#622)
Move overflow guard to the actual vulnerable site:
ThreePositionStrategy._computeFloorTickWithSignal() line 262 where
vwapX96 >> 32 is cast to int128 for _tickAtPriceRatio. Values
exceeding int128.max now skip mirror tick (fallback to scarcity/clamp)
instead of reverting.

Remove incorrect require from Optimizer._buildInputs() which guarded
a non-existent int256 cast path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 02:46:30 +00:00
openhands
7007e593da fix: getLiquidityParams: int256 overflow on large VWAP values (#622)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 02:05:25 +00:00
openhands
170cc839e6 fix: _scrapePositions: unguarded safeTransfer to address(0) when feeDestination unset (#624)
Add address(0) guard to fee transfer condition in _scrapePositions so
that when feeDestination is uninitialized, fees accrue as deployable
liquidity instead of reverting on safeTransfer to the zero address.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 01:05:05 +00:00
openhands
d3ff2cd0bf fix: Bear defaults duplicated across Optimizer and LiquidityManager (#646)
Extract bear-mode default values (0, 3e17, 100, 3e17) into file-level
constants in IOptimizer.sol so both Optimizer._bearDefaults() and
LiquidityManager.recenter()'s catch block reference a single source of
truth instead of independent hardcoded literals.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 18:22:43 +00:00
openhands
5a7363b718 fix: move @return NatSpec from _buildInputs to getLiquidityParams
The @return annotations were orphaned after _buildInputs() was inserted
between the NatSpec block and getLiquidityParams(). Move them to directly
precede getLiquidityParams() where they belong.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 17:08:26 +00:00
openhands
bb150671ea fix: OptimizerInputCapture test harness is structurally broken (#652)
The pure override in OptimizerInputCapture could not write to storage,
and getLiquidityParams calls calculateParams via staticcall which
prevents both storage writes and event emissions.

Fix: extract the input-building normalization from getLiquidityParams
into _buildInputs() (internal view, behavior-preserving refactor).
The test harness now exposes _buildInputs() via getComputedInputs(),
allowing tests to assert actual normalized slot values.

Updated tests for pricePosition, timeSinceRecenter, volatility,
momentum, and utilizationRate to assert non-zero captured values.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 13:57:25 +00:00
johba
5c4ceaf78d fix: No negative-mantissa guard in OptimizerV3Push3 (#650) (#966)
Fixes #650

## Changes
Add require(inputs[k].mantissa >= 0, 'negative mantissa') for all 8 input slots inside the existing validation loop in OptimizerV3Push3.sol, matching the guard pattern in Optimizer.sol lines 372-374. Added 3 tests covering slots 0, 1, and 5 to confirm revert on negative mantissa.

Co-authored-by: openhands <openhands@all-hands.dev>
Reviewed-on: https://codeberg.org/johba/harb/pulls/966
Reviewed-by: Disinto_bot <disinto_bot@noreply.codeberg.org>
2026-03-19 11:30:18 +01:00
openhands
e3c699b7eb fix: No events on fee destination state changes (#958)
Add FeeDestinationSet and FeeDestinationLocked events to LiquidityManager,
emitted on every setFeeDestination() call and lock engagement respectively.
Update tests to assert both events are emitted in all code paths.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 21:25:12 +00:00
openhands
28ce5ec8cd fix: Optimizer.sol base class only guards slots 0 and 1 (#968)
Replace the two per-slot require checks with a loop over all 8 input slots
so future subclasses using slots 2-7 are protected from silent uint256 wrap.
Add testCalculateParamsRevertsOnNegativeMantissaSlots2to7 to verify the guard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 18:24:18 +00:00
openhands
534382f785 fix: CREATE2 self-destruct bypass in onchain/src/LiquidityManager.sol (#921)
The previous guard blocked setFeeDestination when feeDestination.code.length > 0
but did not persist feeDestinationLocked — a revert undoes all state changes. An
attacker could CREATE2-deploy bytecode to the EOA fee destination, triggering the
block, then SELFDESTRUCT to clear the code, then call setFeeDestination again
successfully (lock was never committed).

Fix: detect bytecode at the current feeDestination first; if found, set
feeDestinationLocked = true and RETURN (not revert) so the storage write is
committed. A subsequent SELFDESTRUCT cannot undo a committed storage slot.
Updated NatSpec documents both the protection and the remaining limitation
(atomic CREATE2+SELFDESTRUCT in a single tx cannot be detected).

Added testSetFeeDestination_CREATE2BytecodeDetection_Locks covering:
set EOA → vm.etch (simulate CREATE2 deploy) → verify lock committed → vm.etch
empty (simulate selfdestruct) → verify setter still blocked.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 11:58:28 +00:00
openhands
ee867b256e fix: add symmetric InvalidAddress guard to setLiquidityManager (#935)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 09:45:43 +00:00
openhands
f3238a9685 fix: Kraiken.setStakingPool() allows stakingPool == liquidityManager with no guard (#935)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 08:09:43 +00:00
openhands
e4225b364b fix: Double-subtraction if stakingPoolAddr == feeDestination (#911) 2026-03-17 20:49:46 +00:00
openhands
a21cf398bf fix: Unclamped anchorWidth can overflow tick range — no upper-bound guard after MAX_ANCHOR_WIDTH removal (#783) (#817)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 21:34:33 +00:00
openhands
d3917c551f fix: ThreePositionStrategy class comment still advertises 1-100% anchor width (#786)
- Fix class-level NatSpec: use accurate wording (width computed from
  anchorWidth param provided by Optimizer) instead of imprecise
  LiquidityManager attribution
- Fix inline comment in _setAnchorPosition (same stale 1-100% claim)
- Update PRODUCT-TRUTH.md and ARCHITECTURE.md which had the same
  incorrect 1-100% range claim

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 08:51:12 +00:00
openhands
f5fdd329c4 fix: ThreePositionStrategy class comment still advertises 1-100% anchor width (#786)
Remove the misleading "(1-100% width)" range claim from the ANCHOR NatSpec.
Anchor width enforcement lives in LiquidityManager, not this abstract, so
the comment is replaced with a note pointing to where enforcement actually occurs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 08:20:13 +00:00
openhands
8c50578be1 fix: update stale comments after CALCULATE_PARAMS_GAS_LIMIT bump to 500k
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 00:28:12 +00:00
openhands
87a088bc66 fix: fix: increase CALCULATE_PARAMS_GAS_LIMIT from 200k to 500k (#782)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 00:00:56 +00:00
openhands
ac4aa745f6 fix: fix: remove MAX_ANCHOR_WIDTH clamp in ThreePositionStrategy (#783)
Remove the MAX_ANCHOR_WIDTH=100 constant and the corresponding clamp on
anchorWidth in LiquidityManager.recenter(). The optimizer is now free to
choose any anchor width; evolution run 7 immediately exploited AW=153.

Update IOptimizer.sol NatSpec to reflect no clamping. Update the
testAnchorWidthAbove100IsClamped test to testAnchorWidthAbove100IsNotClamped,
asserting the tick range matches the full AW=150 width.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 23:21:30 +00:00
johba
6ff8282a7e Merge pull request 'fix: Remove recenterAccess — make recenter() public with TWAP enforcement (#706)' (#713) from fix/issue-706 into master 2026-03-14 10:48:59 +01:00
openhands
2c849ec456 fix: calculateParams in OptimizerV3Push3 has no NatSpec after this PR (#735)
Move the orphaned NatSpec block (originally for calculateParams) from
above getLiquidityParams to directly precede calculateParams, and give
getLiquidityParams only its own @inheritdoc block.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 06:20:37 +00:00
openhands
6978d1399f fix: OptimizerV3 / OptimizerV3Push3 not explicitly typed against IOptimizer (#661)
- Optimizer: add `is IOptimizer` and mark getLiquidityParams() with
  `override`, making the interface conformance explicit at the base level.
  OptimizerV3 inherits it transitively via Optimizer.
- OptimizerV3Push3: add `is IOptimizer` and implement getLiquidityParams()
  that calls calculateParams() with zeroed inputs, returning bear-mode
  defaults (ci=0, anchorShare=0.3e18, anchorWidth=100, discoveryDepth=0.3e18).
  Behaviour is identical to the previous try/catch fallback used by
  LiquidityManager and the backtesting deployer.
- Update backtesting comments to reflect that getLiquidityParams() now
  exists on OptimizerV3Push3 (returns bear defaults via zeroed inputs).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 05:08:32 +00:00
openhands
f3ddec9427 fix: Other clamped params lack named constants (#703)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 01:40:41 +00:00
openhands
1a410a30b7 fix: Remove recenterAccess — make recenter() public with TWAP enforcement (#706) 2026-03-13 22:32:53 +00:00
openhands
39c25fa330 fix: LiquidityManager silently clamps anchorWidth to 100, undocumented upper bound (#689)
- Extract magic number into named constant MAX_ANCHOR_WIDTH = 100 in LiquidityManager.sol
- Document effective ceiling in IOptimizer.sol natspec for anchorWidth return value
- Add testAnchorWidthAbove100IsClamped in LiquidityManager.t.sol asserting that
  optimizer-returned anchorWidth=150 is silently clamped to 100 (not rejected)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 18:14:37 +00:00
openhands
d01c561028 fix: No formal IOptimizer interface for getLiquidityParams ABI (#556)
Add IOptimizer interface with getLiquidityParams() signature to IOptimizer.sol
so upgrade-compatibility is explicit and static analysis can catch ABI mismatches.
Update LiquidityManager to hold optimizer as IOptimizer instead of concrete Optimizer.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 07:20:42 +00:00
johba
8064623a54 fix: feat: Push3 input redesign — normalized indicators instead of raw protocol values (#635) (#649)
Fixes #635

## Changes
The implementation is complete and committed. All 211 tests pass.

## Summary of changes

### `onchain/src/Optimizer.sol`
- **Replaced raw slot inputs** with normalized indicators in `getLiquidityParams()`:
  - Slot 2 `pricePosition`: where current price sits within VWAP ± 11 000 ticks (0 = lower bound, 0.5e18 = at VWAP, 1e18 = upper bound)
  - Slot 3 `volatility`: `|shortTwap − longTwap| / 1000 ticks`, capped at 1e18
  - Slot 4 `momentum`: 0 = falling, 0.5e18 = flat, 1e18 = rising (5-min vs 30-min TWAP delta)
  - Slot 5 `timeSinceRecenter`: `elapsed / 86400s`, capped at 1e18
  - Slot 6 `utilizationRate`: 1e18 if current tick is within anchor position range, else 0
- **Extended `setDataSources()`** to accept `liquidityManager` + `token0isWeth` (needed for correct tick direction in momentum/utilizationRate)
- **Added `_vwapToTick()`** helper: converts `vwapX96 = price × 2⁹⁶` to tick via `sqrt(vwapX96) << 48`, with TickMath bounds clamping
- All slots gracefully default to 0 when data sources are unconfigured or TWAP history is insufficient (try/catch on `pool.observe()`)

### `onchain/src/OptimizerV3Push3.sol`
- Updated NatSpec to document the new `[0, 1e18]` slot semantics

### New tests (`onchain/test/`)
- `OptimizerNormalizedInputsTest`: 18 tests covering all new slots, token ordering, TWAP fallback, and a bounded fuzz test
- `mocks/MockPool.sol`: configurable `slot0()` + `observe()` with TWAP tick math
- `mocks/MockLiquidityManagerPositions.sol`: configurable anchor position bounds

Co-authored-by: openhands <openhands@all-hands.dev>
Reviewed-on: https://codeberg.org/johba/harb/pulls/649
Reviewed-by: review_bot <review_bot@noreply.codeberg.org>
2026-03-13 07:53:46 +01:00
openhands
c87064dc6c fix: feat: Push3 default outputs — crash/no-output falls back to bear strategy (#634)
Three defensive layers so every Push3 program runs without reverting:

Layer A (transpiler/index.ts): assign bear defaults (CI=0, AS=0.3e18,
AW=100, DD=0.3e18) to all four outputs at the top of calculateParams.
Any output the evolved program does not overwrite keeps the safe default.

Layer B (transpiler/transpiler.ts): graceful stack underflow — dpop/bpop
return '0'/'false' instead of throwing, and the final output-pop falls
back to bear-default literals when fewer than 4 values remain on the
stack. Wrong output count no longer aborts transpilation.

Layer C (transpiler/transpiler.ts + index.ts): wrap the entire function
body in `unchecked {}` so integer overflow wraps (matching Push3), and
emit `(b == 0 ? 0 : a / b)` for every DYADIC./ (div-by-zero → 0,
matching Push3 no-op semantics).

Layer 2 (Optimizer.sol getLiquidityParams): clamp the three fraction
outputs (capitalInefficiency, anchorShare, discoveryDepth) to [0, 1e18]
after abi.decode so a buggy evolved program cannot produce out-of-range
values even if it runs without reverting.

Regenerated OptimizerV3Push3.sol with the updated transpiler; all 193
tests pass (34 Optimizer/OptimizerV3Push3 tests explicitly).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 03:47:49 +00:00
openhands
5d369cfab6 fix: address review findings for gas-limit fitness pressure (#637)
- Optimizer.sol: move CALCULATE_PARAMS_GAS_LIMIT constant to top of
  contract (after error declaration) to avoid mid-contract placement.
  Expand natspec with EIP-150 63/64 note: callers need ~203 175 gas to
  deliver the full 200 000 budget to the inner staticcall.

- Optimizer.sol: add ret.length < 128 guard before abi.decode in
  getLiquidityParams(). Malformed return data (truncated / wrong ABI)
  from an evolved program now falls back to _bearDefaults() instead of
  propagating an unhandled revert. The 128-byte minimum is the ABI
  encoding of (uint256, uint256, uint24, uint256) — four 32-byte slots.

- Optimizer.sol: add cross-reference comment to _bearDefaults() noting
  that its values must stay in sync with LiquidityManager.recenter()'s
  catch block to prevent silent divergence.

- FitnessEvaluator.t.sol: add CALCULATE_PARAMS_GAS_LIMIT mirror constant
  (must match Optimizer.sol). Disqualify candidates whose measured gas
  exceeds the production cap with fitness=0 and error="gas_over_limit"
  — prevents the pipeline from selecting programs that are functionally
  dead on-chain (would always produce bear defaults in production).

- batch-eval.sh: update output format comment to document the gas_used
  field and over-gas-limit error object added by this feature.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 01:05:37 +00:00
openhands
c9c0ce5e95 fix: feat: Push3 evolution — gas limit as fitness pressure (#637)
- Optimizer.getLiquidityParams() now forwards calculateParams through a
  staticcall capped at 200 000 gas. Programs that exceed the budget or
  revert fall back to bear defaults (CI=0, AS=30%, AW=100, DD=0.3e18),
  so a bloated evolved optimizer can never OOG-revert inside recenter().

- FitnessEvaluator.t.sol measures gas used by calculateParams against
  fixed representative inputs (50% staked, 5% avg tax) after each
  bootstrap. A soft penalty of GAS_PENALTY_FACTOR (1e13 wei/gas) is
  subtracted from total fitness before the JSON score line is emitted.
  Leaner programs win ties; gas_used is included in the output for
  observability. At ~15k gas (current seed) the penalty is ~1.5e17 wei;
  at the 200k hard cap boundary it reaches ~2e18 wei.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 00:25:49 +00:00
johba
b456bc75fd Merge pull request 'fix: LM recenter() return semantics undocumented (#570)' (#626) from fix/issue-570 into master 2026-03-12 21:53:34 +01:00
openhands
b8f5ed9411 fix: Dead code branch: lastRecenterTick==0 with cumulativeVolume>0 (#568)
Remove unreachable else branch in VWAP recording logic. The branch was
only reachable if lastRecenterTick==0 and cumulativeVolume>0, which
requires tick==0 on the very first recenter — virtually impossible on a
live pool. Collapse else-if into else and delete the corresponding
testVWAPElseBranch test that exercised the path via vm.store.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 19:21:11 +00:00
openhands
54976184bc fix: correct isUp NatSpec and bootstrap log direction (#570)
Fix the @return NatSpec for recenter() isUp: the previous description
was wrong for the token0=WETH ordering (claimed tick above center, but
the actual check is currentTick < centerTick when token0isWeth). The
correct invariant is isUp=true ↔ KRK price in ETH rose (buy event /
net ETH inflow), regardless of token ordering.

Also address review nit: StrategyExecutor._logRecenter() now logs
'direction=BOOTSTRAP' instead of 'direction=DOWN' when no anchor
position existed before the recenter (aLiqPre==0), eliminating the
misleading directional label on the first recenter.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 19:12:46 +00:00
openhands
cb6d6e2292 fix: LM recenter() return semantics undocumented (#570)
Add NatSpec to recenter() documenting that the function always reverts
on failure (never silently returns false), listing all four revert
conditions, and clarifying that both true/false return values represent
a successfully-executed recenter with the value indicating price
direction (up vs down relative to previous anchor centre).

Also fix StrategyExecutor.maybeRecenter() to capture the isUp return
value from lm.recenter() and include it in the log output, making
price direction visible in backtesting replays.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 18:21:27 +00:00
openhands
2da70bedfd fix: capitalInefficiency always 0 in OptimizerV3Push3 undocumented (#573) 2026-03-12 17:46:25 +00:00
openhands
b902b89e3b fix: address review findings — CREATE2 guard, transition test, docs
- LiquidityManager.setFeeDestination: add CREATE2 bypass guard — also
  blocks re-assignment when the current feeDestination has since acquired
  bytecode (was a plain address when set, contract deployed to it later)
- LiquidityManager.setFeeDestination: expand NatSpec to document the
  EOA-mutability trade-off and the CREATE2 guard explicitly
- Test: add testSetFeeDestinationEOAToContract_Locks covering the
  realistic EOA→contract transition (the primary lock-activation path)
- red-team.sh: add comment that DEPLOYER_PK is Anvil account-0 and must
  only be used against a local ephemeral Anvil instance
- ARCHITECTURE.md: document feeDestination conditional-lock semantics and
  contrast with Kraiken's strictly set-once liquidityManager/stakingPool

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 17:13:50 +00:00
openhands
512640226b fix: fix: Conditional lock on feeDestination — lock when set to contract (#580) (#580)
- Add `feeDestinationLocked` bool to LiquidityManager
- Replace one-shot setter with conditional trapdoor: EOAs may be set
  repeatedly, but setting a contract address locks permanently
- Remove `AddressAlreadySet` error (superseded by the new lock mechanic)
- Replace fragile SLOT7 storage hack in red-team.sh with a proper
  `setFeeDestination()` call using the deployer key
- Update tests: replace AddressAlreadySet test with three new tests
  covering EOA multi-set, contract lock, and locked revert

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 16:13:44 +00:00
openhands
9bb223cf95 fix: Optimizer.sol also silently accepts negative mantissa inputs (#582)
Add require(mantissa >= 0) guards in calculateParams before the uint256()
casts on inputs[0] and inputs[1], preventing negative int256 values from
wrapping to huge uint256 numbers and corrupting liquidity calculations.
Add two regression tests covering the revert paths for both slots.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 15:41:39 +00:00
johba
4258045c8c Merge pull request 'fix: fix: Restore proper VWAP — gas-efficient volume-weighted pricing (revert TWAP) (#603)' (#605) from fix/issue-603 into master 2026-03-12 12:10:02 +01:00
openhands
f844f76533 fix: OptimizerV3 — use canonical transpiler output, fix register mapping
Review bot caught r37/r39 inversion (anchorShare ↔ discoveryDepth).
Replaced inline approximation with verbatim transpiler output.
Removed stale NatSpec (no delegatecall), removed unused import.
2026-03-12 09:04:52 +00:00
openhands
0dd764b8b3 fix: fix: Restore proper VWAP — gas-efficient volume-weighted pricing (revert TWAP) (#603)
- Replace pool.observe() TWAP price source with current pool tick (pool.slot0()) sampled once per recenter
- Remove _getTWAPOrFallback() and TWAPFallback event (added by PR #575)
- _scrapePositions now takes int24 currentTick instead of uint256 prevTimestamp; price computed via _priceAtTick before the burn loop
- Volume weighting (ethFee * 100) is unchanged — fees proxy swap volume over the recenter interval
- Direction fix from #566 (shouldRecordVWAP only on sell events) is preserved
- Remove test_twapReflectsAveragePriceNotJustLastSwap (tested reverted TWAP behaviour)
- ORACLE_CARDINALITY / increaseObservationCardinalityNext retained for _isPriceStable()
- All 188 tests pass

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 08:50:07 +00:00
openhands
ade7e2033a fix: Evolution pipeline UUPS upgrade + Foundry PATH (#593)
- Add virtual to Optimizer.calculateParams() for UUPS override
- Create OptimizerV3.sol: UUPS-upgradeable optimizer with transpiled Push3 logic
- Update deploy-optimizer.sh to deploy OptimizerV3 instead of Optimizer
- Add ~/.foundry/bin to PATH in evolve.sh, fitness.sh, deploy-optimizer.sh
2026-03-12 06:47:35 +00:00
openhands
5d204e5649 fix: Push3 optimizer: dyadic rational input interface (8 slots) + 4-output redesign (#548)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 15:23:36 +00:00
openhands
f72f99aefa fix: Address review findings from PR #575
- Fix unsafe int32 intermediate cast: int56(int32(elapsed)) → int56(uint56(elapsed))
  to prevent TWAP tick sign inversion for intervals above int32 max (~68 years)
- Remove redundant lastRecenterTimestamp state variable; capture prevTimestamp
  from existing lastRecenterTime instead (saves ~20k gas per recenter)
- Use pool.increaseObservationCardinalityNext(ORACLE_CARDINALITY) in constructor
  instead of recomputing the pool address; extract magic 100 to named constant
- Add TWAPFallback(uint32 elapsed) event emitted when pool.observe() reverts
  so monitoring can distinguish degraded operation from normal bootstrap
- Remove conditional bypass paths in test_twapReflectsAveragePriceNotJustLastSwap;
  assert vwapAfter > 0 and vwapAfter > initialPriceX96 unconditionally

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 10:02:47 +00:00
openhands
53c14745cb fix: Replace anchor-midpoint VWAP with pool.observe() TWAP oracle (#575)
- Add lastRecenterTimestamp to track recenter interval for TWAP
- Increase pool observation cardinality to 100 in constructor
- In _scrapePositions, use pool.observe([elapsed, 0]) to get TWAP tick
  over the full interval between recenters; falls back to anchor midpoint
  when elapsed==0 or pool.observe() reverts (insufficient history)
- Add test_twapReflectsAveragePriceNotJustLastSwap: verifies TWAP-based
  VWAP reflects the average price across the recenter interval, not just
  the last-swap anchor snapshot

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 08:17:49 +00:00
johba
8c0683cbba Merge pull request 'fix: Red-team: replace ethPerToken with exact total-LM-ETH metric (#539)' (#540) from fix/issue-539 into master 2026-03-11 08:33:25 +01:00
openhands
6b77a493a2 fix: address review feedback — update stale comments and tighten test guard (#543)
- _scrapePositions natspec: 'ETH inflow' → 'ETH outflow / price fell or at bootstrap'
- Inline comment above VWAP block: remove inverted 'KRK sold out / ETH inflow' rationale,
  replace with a neutral forward-reference to recenter() where the direction logic lives
- VWAPFloorProtection.t.sol: remove unused Kraiken and forge-std/Test.sol imports
  (both are already provided by UniSwapHelper)
- test_floorConservativeAfterBuyOnlyAttack: add assertFalse(token0isWeth) guard so a
  future change to the setUp parameter cannot silently invert the gap-direction assertion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 04:11:02 +00:00
openhands
e35a805138 fix: Investigate: VWAP not preventing IL crystallization during buy-only recenter cycles (#543)
Investigation findings:
- VWAP WAS being fed during buy-only cycles (shouldRecordVWAP = true on ETH inflow / price rising).
  Over 80 buy-recenter cycles VWAP converged toward the inflated current price.
- When VWAP ≈ currentTick, mirrorTick = currentTick + vwapDistance ≈ currentTick, placing
  the floor near the inflated price.  Adversary sells back through the high floor, extracting
  nearly all LM ETH.
- Optimizer parameters (anchorShare, CI) were not the primary cause.

Fix (LiquidityManager.sol):
  Flip shouldRecordVWAP from buy direction to sell direction.  VWAP is now recorded only when
  price falls (ETH outflow / sell events) or at initial bootstrap (cumulativeVolume == 0).
  Buy-only attack cycles leave VWAP frozen at the historical baseline, keeping mirrorTick and
  the floor conservatively anchored far from the inflated current price.

Also updated onchain/AGENTS.md to document the corrected recording direction.

Regression test (VWAPFloorProtection.t.sol):
  - test_vwapNotInflatedByBuyOnlyAttack: asserts getVWAP() stays at bootstrap after N buy cycles.
  - test_floorConservativeAfterBuyOnlyAttack: asserts floor center is far below inflated tick.
  - test_vwapBootstrapsOnFirstFeeEvent: confirms bootstrap path unchanged.
  - test_recenterSucceedsOnSellDirectionWithoutReverts: confirms sell-direction recenters work.

All 187 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 03:31:45 +00:00
openhands
9832b454df fix: PR #551 review findings - OptimizerV3Push3.sol + Optimizer.sol
Critical bugs fixed:
- OptimizerV3Push3: Add input validation for mantissa (inputs[0].mantissa <= 1e18)
- OptimizerInput struct: Move to shared IOptimizer.sol to eliminate duplication
- Update imports in Optimizer.sol, OptimizerV3Push3.sol, and test file

Warnings addressed:
- Document unused variables (_d2-_d7) with comments in OptimizerV3Push3
- Add shift validation: require(inputs[k].shift == 0, "shift not yet supported")
- Fix recordRecenter error style: use UnauthorizedAccount custom error

Tests: All 32 Optimizer + OptimizerV3Push3 tests passing
2026-03-10 23:13:57 +00:00
openhands
2c21462e1e fix: LM: accrue fees as liquidity when feeDestination is self (#533)
When feeDestination == address(this), _scrapePositions() now skips the
fee safeTransfer calls so collected WETH/KRK stays in the LM balance
and is redeployed as liquidity on the next _setPositions() call.

Also fixes _getOutstandingSupply(): kraiken.outstandingSupply() already
subtracts balanceOf(liquidityManager), so when feeDestination IS the LM
the old code double-subtracted LM-held KRK, causing an arithmetic
underflow once positions were scraped.  The subtraction is now skipped
for the self-referencing case.

VWAP recording is refactored to a single unconditional block so it fires
regardless of fee destination.

New test testSelfFeeDestination_FeesAccrueAsLiquidity() demonstrates
that a two-recenter cycle with self-feeDestination completes without
underflow and without leaking WETH to any external address.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 10:11:41 +00:00