Add Solidity linting with solhint, Foundry formatter, and pre-commit hooks (#51)

## Changes

### Configuration
- Added .solhint.json with recommended rules + custom config
  - 160 char line length (warn)
  - Double quotes enforcement (error)
  - Explicit visibility required (error)
  - Console statements allowed (scripts/tests need them)
  - Gas optimization warnings enabled
  - Ignores test/helpers/, lib/, out/, cache/, broadcast/

- Added foundry.toml [fmt] section
  - 160 char line length
  - 4-space tabs
  - Double quotes
  - Thousands separators for numbers
  - Sort imports enabled

- Added .lintstagedrc.json for pre-commit auto-fix
  - Runs solhint --fix on .sol files
  - Runs forge fmt on .sol files

- Added husky pre-commit hook via lint-staged

### NPM Scripts
- lint:sol - run solhint
- lint:sol:fix - auto-fix solhint issues
- format:sol - format with forge fmt
- format:sol:check - check formatting
- lint / lint:fix - combined commands

### Code Changes
- Added explicit visibility modifiers (internal) to constants in scripts and tests
- Fixed quote style in DeployLocal.sol
- All Solidity files formatted with forge fmt

## Verification
-  forge fmt --check passes
-  No solhint errors (warnings only)
-  forge build succeeds
-  forge test passes (107/107)

resolves #44

Co-authored-by: johba <johba@harb.eth>
Reviewed-on: https://codeberg.org/johba/harb/pulls/51
This commit is contained in:
johba 2025-10-04 15:17:09 +02:00
parent f8927b426e
commit d7c2184ccf
45 changed files with 2853 additions and 1225 deletions

View file

@ -1,10 +1,10 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {TickMath} from "@aperture/uni-v3-lib/TickMath.sol";
import {LiquidityAmounts} from "@aperture/uni-v3-lib/LiquidityAmounts.sol";
import {ThreePositionStrategy} from "../../src/abstracts/ThreePositionStrategy.sol";
import { ThreePositionStrategy } from "../../src/abstracts/ThreePositionStrategy.sol";
import { LiquidityAmounts } from "@aperture/uni-v3-lib/LiquidityAmounts.sol";
import { TickMath } from "@aperture/uni-v3-lib/TickMath.sol";
import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
/**
* @title LiquidityBoundaryHelper
@ -15,11 +15,7 @@ library LiquidityBoundaryHelper {
/**
* @notice Calculates the ETH required to push price to the outer discovery bound
*/
function calculateBuyLimit(
IUniswapV3Pool pool,
ThreePositionStrategy liquidityManager,
bool token0isWeth
) internal view returns (uint256) {
function calculateBuyLimit(IUniswapV3Pool pool, ThreePositionStrategy liquidityManager, bool token0isWeth) internal view returns (uint256) {
(, int24 currentTick,,,,,) = pool.slot0();
(uint128 anchorLiquidity, int24 anchorLower, int24 anchorUpper) = liquidityManager.positions(ThreePositionStrategy.Stage.ANCHOR);
@ -30,36 +26,16 @@ library LiquidityBoundaryHelper {
}
if (token0isWeth) {
return _calculateBuyLimitToken0IsWeth(
currentTick,
anchorLiquidity,
anchorLower,
anchorUpper,
discoveryLiquidity,
discoveryLower,
discoveryUpper
);
return _calculateBuyLimitToken0IsWeth(currentTick, anchorLiquidity, anchorLower, anchorUpper, discoveryLiquidity, discoveryLower, discoveryUpper);
}
return _calculateBuyLimitToken1IsWeth(
currentTick,
anchorLiquidity,
anchorLower,
anchorUpper,
discoveryLiquidity,
discoveryLower,
discoveryUpper
);
return _calculateBuyLimitToken1IsWeth(currentTick, anchorLiquidity, anchorLower, anchorUpper, discoveryLiquidity, discoveryLower, discoveryUpper);
}
/**
* @notice Calculates the HARB required to push price to the outer floor bound
*/
function calculateSellLimit(
IUniswapV3Pool pool,
ThreePositionStrategy liquidityManager,
bool token0isWeth
) internal view returns (uint256) {
function calculateSellLimit(IUniswapV3Pool pool, ThreePositionStrategy liquidityManager, bool token0isWeth) internal view returns (uint256) {
(, int24 currentTick,,,,,) = pool.slot0();
(uint128 anchorLiquidity, int24 anchorLower, int24 anchorUpper) = liquidityManager.positions(ThreePositionStrategy.Stage.ANCHOR);
@ -70,26 +46,10 @@ library LiquidityBoundaryHelper {
}
if (token0isWeth) {
return _calculateSellLimitToken0IsWeth(
currentTick,
anchorLiquidity,
anchorLower,
anchorUpper,
floorLiquidity,
floorLower,
floorUpper
);
return _calculateSellLimitToken0IsWeth(currentTick, anchorLiquidity, anchorLower, anchorUpper, floorLiquidity, floorLower, floorUpper);
}
return _calculateSellLimitToken1IsWeth(
currentTick,
anchorLiquidity,
anchorLower,
anchorUpper,
floorLiquidity,
floorLower,
floorUpper
);
return _calculateSellLimitToken1IsWeth(currentTick, anchorLiquidity, anchorLower, anchorUpper, floorLiquidity, floorLower, floorUpper);
}
function _calculateBuyLimitToken0IsWeth(
@ -100,7 +60,11 @@ library LiquidityBoundaryHelper {
uint128 discoveryLiquidity,
int24 discoveryLower,
int24 discoveryUpper
) private pure returns (uint256) {
)
private
pure
returns (uint256)
{
if (discoveryLiquidity == 0) {
return type(uint256).max;
}
@ -135,7 +99,11 @@ library LiquidityBoundaryHelper {
uint128 discoveryLiquidity,
int24 discoveryLower,
int24 discoveryUpper
) private pure returns (uint256) {
)
private
pure
returns (uint256)
{
if (discoveryLiquidity == 0) {
return type(uint256).max;
}
@ -170,7 +138,11 @@ library LiquidityBoundaryHelper {
uint128 floorLiquidity,
int24 floorLower,
int24 floorUpper
) private pure returns (uint256) {
)
private
pure
returns (uint256)
{
if (floorLiquidity == 0) {
return type(uint256).max;
}
@ -205,7 +177,11 @@ library LiquidityBoundaryHelper {
uint128 floorLiquidity,
int24 floorLower,
int24 floorUpper
) private pure returns (uint256) {
)
private
pure
returns (uint256)
{
if (floorLiquidity == 0) {
return type(uint256).max;
}

View file

@ -1,19 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import { Kraiken } from "../../src/Kraiken.sol";
import { LiquidityManager } from "../../src/LiquidityManager.sol";
import "../../src/Optimizer.sol";
import { Stake } from "../../src/Stake.sol";
import "../../src/abstracts/ThreePositionStrategy.sol";
import "../../src/helpers/UniswapHelpers.sol";
import "../../src/interfaces/IWETH9.sol";
import "../../test/mocks/MockOptimizer.sol";
import "@aperture/uni-v3-lib/TickMath.sol";
import {WETH} from "solmate/tokens/WETH.sol";
import "@uniswap-v3-core/interfaces/IUniswapV3Factory.sol";
import "@uniswap-v3-core/interfaces/IUniswapV3Pool.sol";
import "../../src/interfaces/IWETH9.sol";
import {Kraiken} from "../../src/Kraiken.sol";
import {Stake} from "../../src/Stake.sol";
import {LiquidityManager} from "../../src/LiquidityManager.sol";
import "../../src/helpers/UniswapHelpers.sol";
import "../../src/Optimizer.sol";
import "../../test/mocks/MockOptimizer.sol";
import "forge-std/Test.sol";
import { WETH } from "solmate/tokens/WETH.sol";
// Constants
uint24 constant FEE = uint24(10_000); // 1% fee
@ -33,11 +37,11 @@ abstract contract TestConstants is Test {
*/
function getDefaultParams() internal pure returns (ThreePositionStrategy.PositionParams memory) {
return ThreePositionStrategy.PositionParams({
capitalInefficiency: 5 * 10 ** 17, // 50%
anchorShare: 5 * 10 ** 17, // 50%
anchorWidth: 50, // 50%
discoveryDepth: 5 * 10 ** 17 // 50%
});
capitalInefficiency: 5 * 10 ** 17, // 50%
anchorShare: 5 * 10 ** 17, // 50%
anchorWidth: 50, // 50%
discoveryDepth: 5 * 10 ** 17 // 50%
});
}
/**
@ -66,7 +70,7 @@ abstract contract TestConstants is Test {
*/
contract TestEnvironment is TestConstants {
using UniswapHelpers for IUniswapV3Pool;
// Core contracts
IUniswapV3Factory public factory;
IUniswapV3Pool public pool;
@ -75,15 +79,15 @@ contract TestEnvironment is TestConstants {
Stake public stake;
LiquidityManager public lm;
Optimizer public optimizer;
// State variables
bool public token0isWeth;
address public feeDestination;
constructor(address _feeDestination) {
feeDestination = _feeDestination;
}
/**
* @notice Deploy all contracts and set up the environment
* @param token0shouldBeWeth Whether WETH should be token0
@ -97,38 +101,44 @@ contract TestEnvironment is TestConstants {
* @return _optimizer The optimizer contract
* @return _token0isWeth Whether token0 is WETH
*/
function setupEnvironment(bool token0shouldBeWeth, address recenterCaller) external returns (
IUniswapV3Factory _factory,
IUniswapV3Pool _pool,
IWETH9 _weth,
Kraiken _harberg,
Stake _stake,
LiquidityManager _lm,
Optimizer _optimizer,
bool _token0isWeth
) {
function setupEnvironment(
bool token0shouldBeWeth,
address recenterCaller
)
external
returns (
IUniswapV3Factory _factory,
IUniswapV3Pool _pool,
IWETH9 _weth,
Kraiken _harberg,
Stake _stake,
LiquidityManager _lm,
Optimizer _optimizer,
bool _token0isWeth
)
{
// Deploy factory
factory = UniswapHelpers.deployUniswapFactory();
// Deploy tokens in correct order
_deployTokensWithOrder(token0shouldBeWeth);
// Create and initialize pool
_createAndInitializePool();
// Deploy protocol contracts
_deployProtocolContracts();
// Configure permissions
_configurePermissions();
// Grant recenter access to specified caller
vm.prank(feeDestination);
lm.setRecenterAccess(recenterCaller);
return (factory, pool, weth, harberg, stake, lm, optimizer, token0isWeth);
}
/**
* @notice Deploy tokens ensuring the desired ordering
* @param token0shouldBeWeth Whether WETH should be token0
@ -159,7 +169,7 @@ contract TestEnvironment is TestConstants {
}
require(setupComplete, "Setup failed to meet the condition after several retries");
}
/**
* @notice Create and initialize the Uniswap pool
*/
@ -168,7 +178,7 @@ contract TestEnvironment is TestConstants {
token0isWeth = address(weth) < address(harberg);
pool.initializePoolFor1Cent(token0isWeth);
}
/**
* @notice Deploy protocol contracts (Stake, Optimizer, LiquidityManager)
*/
@ -179,7 +189,7 @@ contract TestEnvironment is TestConstants {
lm = new LiquidityManager(address(factory), address(weth), address(harberg), address(optimizer));
lm.setFeeDestination(feeDestination);
}
/**
* @notice Configure permissions and initial funding
*/
@ -189,7 +199,7 @@ contract TestEnvironment is TestConstants {
harberg.setLiquidityManager(address(lm));
vm.deal(address(lm), INITIAL_LM_ETH_BALANCE);
}
/**
* @notice Setup environment with specific optimizer
* @param token0shouldBeWeth Whether WETH should be token0
@ -205,44 +215,47 @@ contract TestEnvironment is TestConstants {
* @return _token0isWeth Whether token0 is WETH
*/
function setupEnvironmentWithOptimizer(
bool token0shouldBeWeth,
bool token0shouldBeWeth,
address recenterCaller,
address optimizerAddress
) external returns (
IUniswapV3Factory _factory,
IUniswapV3Pool _pool,
IWETH9 _weth,
Kraiken _harberg,
Stake _stake,
LiquidityManager _lm,
Optimizer _optimizer,
bool _token0isWeth
) {
)
external
returns (
IUniswapV3Factory _factory,
IUniswapV3Pool _pool,
IWETH9 _weth,
Kraiken _harberg,
Stake _stake,
LiquidityManager _lm,
Optimizer _optimizer,
bool _token0isWeth
)
{
// Deploy factory
factory = UniswapHelpers.deployUniswapFactory();
// Deploy tokens in correct order
_deployTokensWithOrder(token0shouldBeWeth);
// Create and initialize pool
_createAndInitializePool();
// Deploy protocol contracts with custom optimizer
stake = new Stake(address(harberg), feeDestination);
optimizer = Optimizer(optimizerAddress);
lm = new LiquidityManager(address(factory), address(weth), address(harberg), optimizerAddress);
lm.setFeeDestination(feeDestination);
// Configure permissions
_configurePermissions();
// Grant recenter access to specified caller
vm.prank(feeDestination);
lm.setRecenterAccess(recenterCaller);
return (factory, pool, weth, harberg, stake, lm, optimizer, token0isWeth);
}
/**
* @notice Setup environment with existing factory and specific optimizer
* @param existingFactory The existing Uniswap factory to use
@ -260,44 +273,47 @@ contract TestEnvironment is TestConstants {
*/
function setupEnvironmentWithExistingFactory(
IUniswapV3Factory existingFactory,
bool token0shouldBeWeth,
bool token0shouldBeWeth,
address recenterCaller,
address optimizerAddress
) external returns (
IUniswapV3Factory _factory,
IUniswapV3Pool _pool,
IWETH9 _weth,
Kraiken _harberg,
Stake _stake,
LiquidityManager _lm,
Optimizer _optimizer,
bool _token0isWeth
) {
)
external
returns (
IUniswapV3Factory _factory,
IUniswapV3Pool _pool,
IWETH9 _weth,
Kraiken _harberg,
Stake _stake,
LiquidityManager _lm,
Optimizer _optimizer,
bool _token0isWeth
)
{
// Use existing factory
factory = existingFactory;
// Deploy tokens in correct order
_deployTokensWithOrder(token0shouldBeWeth);
// Create and initialize pool
_createAndInitializePool();
// Deploy protocol contracts with custom optimizer
stake = new Stake(address(harberg), feeDestination);
optimizer = Optimizer(optimizerAddress);
lm = new LiquidityManager(address(factory), address(weth), address(harberg), optimizerAddress);
lm.setFeeDestination(feeDestination);
// Configure permissions
_configurePermissions();
// Grant recenter access to specified caller
vm.prank(feeDestination);
lm.setRecenterAccess(recenterCaller);
return (factory, pool, weth, harberg, stake, lm, optimizer, token0isWeth);
}
/**
* @notice Perform recenter with proper time warp and oracle updates
* @param liquidityManager The LiquidityManager instance to recenter
@ -306,9 +322,9 @@ contract TestEnvironment is TestConstants {
function performRecenter(LiquidityManager liquidityManager, address caller) external {
// Update oracle time
vm.warp(block.timestamp + ORACLE_UPDATE_INTERVAL);
// Perform recenter
vm.prank(caller);
liquidityManager.recenter();
}
}
}

View file

@ -1,15 +1,15 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "@uniswap-v3-core/interfaces/IUniswapV3Pool.sol";
import {TickMath} from "@aperture/uni-v3-lib/TickMath.sol";
import {LiquidityAmounts} from "@aperture/uni-v3-lib/LiquidityAmounts.sol";
import {SqrtPriceMath} from "@aperture/uni-v3-lib/SqrtPriceMath.sol";
import { Kraiken } from "../../src/Kraiken.sol";
import { ThreePositionStrategy } from "../../src/abstracts/ThreePositionStrategy.sol";
import "../../src/interfaces/IWETH9.sol";
import {Kraiken} from "../../src/Kraiken.sol";
import {ThreePositionStrategy} from "../../src/abstracts/ThreePositionStrategy.sol";
import {LiquidityBoundaryHelper} from "./LiquidityBoundaryHelper.sol";
import { LiquidityBoundaryHelper } from "./LiquidityBoundaryHelper.sol";
import { LiquidityAmounts } from "@aperture/uni-v3-lib/LiquidityAmounts.sol";
import { SqrtPriceMath } from "@aperture/uni-v3-lib/SqrtPriceMath.sol";
import { TickMath } from "@aperture/uni-v3-lib/TickMath.sol";
import "@uniswap-v3-core/interfaces/IUniswapV3Pool.sol";
import "forge-std/Test.sol";
/**
* @title UniSwapHelper
@ -99,7 +99,7 @@ abstract contract UniSwapHelper is Test {
// Use very aggressive limit close to MIN_SQRT_RATIO
limit = TickMath.MIN_SQRT_RATIO + 1;
} else {
// Swapping token1 for token0 - price goes up
// Swapping token1 for token0 - price goes up
// Use very aggressive limit close to MAX_SQRT_RATIO
limit = TickMath.MAX_SQRT_RATIO - 1;
}
@ -115,13 +115,12 @@ abstract contract UniSwapHelper is Test {
if (amount0Delta == 0 && amount1Delta == 0) {
return;
}
require(amount0Delta > 0 || amount1Delta > 0);
(address seller,, bool isBuy) = abi.decode(_data, (address, uint256, bool));
(, uint256 amountToPay) =
amount0Delta > 0 ? (!token0isWeth, uint256(amount0Delta)) : (token0isWeth, uint256(amount1Delta));
(, uint256 amountToPay) = amount0Delta > 0 ? (!token0isWeth, uint256(amount0Delta)) : (token0isWeth, uint256(amount1Delta));
if (isBuy) {
weth.transfer(msg.sender, amountToPay);
} else {
@ -145,7 +144,7 @@ abstract contract UniSwapHelper is Test {
// pack ETH
uint256 ethOwed = token0isWeth ? amount0Owed : amount1Owed;
if (weth.balanceOf(address(this)) < ethOwed) {
weth.deposit{value: address(this).balance}();
weth.deposit{ value: address(this).balance }();
}
if (ethOwed > 0) {
weth.transfer(msg.sender, amount1Owed);
@ -157,8 +156,8 @@ abstract contract UniSwapHelper is Test {
// ========================================
// Safety margin to prevent tick boundary violations (conservative approach)
int24 constant TICK_BOUNDARY_SAFETY_MARGIN = 15000;
int24 constant TICK_BOUNDARY_SAFETY_MARGIN = 15_000;
// Price normalization constants
uint256 constant NORMALIZATION_HARB_PERCENTAGE = 100; // 1% of HARB balance
uint256 constant NORMALIZATION_ETH_AMOUNT = 0.01 ether; // Fixed ETH amount for normalization
@ -172,10 +171,10 @@ abstract contract UniSwapHelper is Test {
*/
function handleExtremePrice() internal {
uint256 attempts = 0;
while (attempts < MAX_NORMALIZATION_ATTEMPTS) {
(, int24 currentTick,,,,,) = pool.slot0();
if (currentTick >= TickMath.MAX_TICK - TICK_BOUNDARY_SAFETY_MARGIN) {
_executeNormalizingTrade(true); // Move price down
attempts++;
@ -188,7 +187,6 @@ abstract contract UniSwapHelper is Test {
}
}
}
/**
* @notice Executes a small trade to move price away from tick boundaries
@ -203,24 +201,24 @@ abstract contract UniSwapHelper is Test {
// Use 1% of account's HARB balance (conservative approach like original)
uint256 harbToSell = harbBalance / NORMALIZATION_HARB_PERCENTAGE;
if (harbToSell == 0) harbToSell = 1;
vm.prank(account);
harberg.transfer(address(this), harbToSell);
harberg.approve(address(pool), harbToSell);
// Sell HARB for ETH with aggressive price limits for normalization
performSwapWithAggressiveLimits(harbToSell, false);
}
} else {
// Need to move price UP (increase HARB price)
// Need to move price UP (increase HARB price)
// This means: buy HARB with ETH (reduce HARB supply in pool)
uint256 ethBalance = weth.balanceOf(account);
if (ethBalance > 0) {
// Use small amount for normalization (like original)
uint256 ethToBuy = NORMALIZATION_ETH_AMOUNT;
if (ethToBuy > ethBalance) ethToBuy = ethBalance;
// Buy HARB with ETH with aggressive price limits for normalization
// Buy HARB with ETH with aggressive price limits for normalization
performSwapWithAggressiveLimits(ethToBuy, true);
}
}
@ -246,7 +244,7 @@ abstract contract UniSwapHelper is Test {
}
/**
* @notice Calculates the maximum HARB amount that can be traded (sell HARB) without exceeding position liquidity limits
* @notice Calculates the maximum HARB amount that can be traded (sell HARB) without exceeding position liquidity limits
* @dev When currentTick is in anchor range, calculates trade size to make anchor and floor positions "full" of HARB
* @return maxHarbAmount Maximum HARB that can be safely traded, 0 if no positions exist or already at limit
*/
@ -269,7 +267,7 @@ abstract contract UniSwapHelper is Test {
/**
* @notice Raw buy operation without liquidity limit checking
* @param amountEth Amount of ETH to spend buying HARB
* @param amountEth Amount of ETH to spend buying HARB
*/
function buyRaw(uint256 amountEth) internal {
performSwap(amountEth, true);