Hanji
Vault

Covered the vault's LP deposit and yield system, ERC-4626 integration, market-maker slashing protections, and dynamic fee structure.
report id
0580
category
DeFi & Yield
language
Solidity
final report
November 3, 2025
lines of code
2662
Content

Download audit report

1

Executive Summary

This document presents the results of the security review conducted by Nethermind Security for Hanji's derivatives engines contracts. The protocol provides a liquidity management system where LPs deposit assets into a central vault to earn yield, while market makers facilitate trading through integrated on-chain limit order books. The system supports integration with ERC-4626 compliant yield vaults, implements protective mechanisms including market maker slashing and LP token price validation to safeguard against unprofitable or malicious market making, and features a dynamic fee structure that adjusts based on token weight imbalances to maintain portfolio balance.

The audit comprises of 2662 lines of Solidity code. The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, and (c) creation of test cases.

Audit assessment
Audit TypeSecurity Review
Initial ReportAugust 28, 2025
Final ReportNovember 3, 2025
Initial commit276b77ccd4
Final commite803ad3bc7
Documentation AssessmentMedium
Test Suite AssessmentHigh
Total findings
10
Fixed
8
Acknowledged
0
Mitigated
2
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium0
  • Low1
  • Informational4
  • Best Practices5

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/LPManagerFactory.sol6123.3%1982
2src/ProxyPyth.sol1814122.7%45267
3src/ProxyLOBBatch.sol5723.5%1675
4src/ErrorReporter.sol575698.2%55168
5src/LPManager.sol124835228.2%2741874
6src/Proxy.sol5240.0%411
7src/LPToken.sol4824.2%1767
8src/LPManagerHelper.sol1182117.8%29168
9src/AggreVaultOracle.sol5423.7%2480
10src/ProxyLOB.sol214167.5%49279
11src/RfqProxyLOB.sol194105.2%35239
12src/utils/Ecdsa.sol532750.9%787
13src/utils/PythPriceHelper.sol2627.7%836
14src/utils/TokenValueCalculator.sol391641.0%863
15src/utils/RfqOrderLib.sol4648.7%1060
16src/interfaces/ILPManager.sol1503120.7%20201
17src/interfaces/IProxyLOB.sol16212.5%220
18src/interfaces/IOnchainTrie.sol4250.0%28
19src/interfaces/IWGAS.sol5240.0%29
20src/interfaces/IOnchainCLOB.sol8622.3%1199
Total266259422.3%6373893

4

System Overview

The derivatives engine protocol is comprised of several core contracts that facilitate a managed liquidity and trading environment: the LPManager as the core of the protocol, various Proxy contracts for external interactions, and various helper contracts.

LPManager: The central hub contract managing liquidity provision and asset allocation across multiple tokens. Users interact with this contract to add or remove liquidity, receiving LPToken shares proportional to their contribution. The contract implements sophisticated fee structures including dynamic fees based on token weight imbalances, performance fees tied to high-water marks, and cooldown periods for liquidity operations. Additionally, it supports flash loan functionality and integrations with ERC-4626 compliant vaults. The contract enforces strict weight bounds for each token to maintain portfolio balance and includes emergency mechanisms such as market maker share slashing and partial pausing capabilities.

ProxyLOB: An abstract contract that bridges the LPManager with external CLOB (Central Limit Order Book) contracts. This proxy enables the liquidity pool to act as a market maker by placing limit orders across multiple trading pairs. It maintains internal accounting of token reserves locked in limit orders, validates order prices against oracle feeds within configurable tolerance bands, and automatically synchronizes token balances after order operations.

ProxyPyth: A specialized oracle management contract that interfaces with Pyth Network price feeds. It implements epoch-based price tracking with minimum and maximum price storage within time windows, and validates LP token price movements to detect excessive deviations.

Supporting Contracts: The protocol includes several auxiliary contracts: LPToken implements ERC-20 functionality with integrated cooldown validation and market maker share enforcement. AggreVaultOracle provides external price feeds for LP tokens for integration with external protocols. RfqProxyLOB enables request-for-quote functionality with EIP-712 signature validation for authenticated off-chain order matching and LPManagerFactory deploys new liquidity pool instances with proper initialization.

Centralization Risks: The protocol's design includes significant points of centralization. The LPManager is controlled by a single owner with powerful administrative privileges, including the ability to pause the system, change critical parameters, and manage the allowlist for key roles like market makers and depositors. A compromised or malicious owner could therefore exert considerable control over the protocol's operations and assets.

4.1 Contract Interaction Diagram

Diagram from the audit report

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 The minUsdValue check in removeLiquidity is misleading as it does not account for fees

FileFix commitTypeStatus
src/LPManager.sol—LowMitigated

The removeLiquidity(...) function is intended to protect users from slippage by using the minUsdValue parameter. The NatSpec comment explicitly states this parameter is "The minimum USD value the user expects to receive". However, the implementation checks this condition *before* protocol and admin fees are deducted. This means a user can receive a net value in tokens that is less than the minUsdValue they specified.

The check is performed on the gross lpUSDValue, but the final tokenAmount sent to the user is reduced by both protocolFee and adminTokenAmount.

// ...
uint256 lpUSDValue = (totalUSDValue * burnLP) / lpTotalSupply;
// @audit This check is performed against the pre-fee value.
require(
lpUSDValue >= minUsdValue,
ErrorReporter.InsufficientUSDValue()
);

// ...
// Multiple fees are calculated based on the initial tokenAmount.
uint256 protocolFee = tokenAmount.mulDivUp(
protocolFeeBps,
BASIS_POINTS_DIVISOR
);
// ...
uint256 adminTokenAmount = tokenAmount.mulDivUp(
adminBurnLPFeeBps,
BASIS_POINTS_DIVISOR
);
// ...

// @audit The user receives an amount reduced by fees, potentially worth less than minUsdValue.
tokenAmount -= (adminTokenAmount + protocolFee);
token.safeTransfer(msg.sender, tokenAmount);
// ...

This behavior is counterintuitive and makes the slippage protection less effective than implied. A user might set a minimum acceptable value but still have their transaction processed for a lower net value due to fees, which contradicts the purpose of a minimum output parameter.

Recommendation

Consider performing the minUsdValue check on the final net amount of tokens the user will receive after all fees are accounted for. Alternatively, update the NatSpec to reflect the current code.

Resolution

We have updated the documentation for the removeLiquidity function to provide clearer guidance to end users regarding the purpose and behavior of the minUsdValue parameter.

The primary focus of minUsdValue is to protect users against significant price movements during liquidity removal operations. As such, this parameter validates the USD value of the tokens before any fees are applied, ensuring the gross value meets the user's expectations relative to market conditions.

For comprehensive protection that includes fee considerations, we direct users to the minTokenGet parameter, which specifically enforces the minimum net token amount the user will receive after all protocol and admin fees have been deducted.

This dual-parameter approach provides users with flexibility:

  • minUsdValue for price movement protection
  • minTokenGet for fee-inclusive amount protection

The updated documentation now accurately reflects this intended behavior and helps users make informed decisions when configuring their liquidity removal parameters.

6.2 Deactivating a LOB prevents claiming of outstanding orders

FileFix commitTypeStatus
src/LPManager.sol—InfoMitigated

The changeLob(...) function allows the owner to deactivate a Limit Order Book (LOB) by setting its isActive status to false. However, the claimOrder(...) function, which is used to claim or cancel orders, can only be called on active LOBs due to the check in _checkLOB(...).

If an owner deactivates a LOB that still has open orders placed by the LPManager, the assets backing those orders will become temporarily inaccessible. The claimOrder(...) function will revert for that lobId, preventing the recovery of the funds.

function changeLob(
address lobAddress,
bool isActive,
// ...
) external onlyOwner {
// ...
} else {
// @audit When a LOB is deactivated (!isActive), there is no process
// @audit to claim or cancel any existing open orders.
if (!isActive) {
// When deactivating the pair, reset LOB contract allowances to zero
_callApprove(
tokens[lobs[i].tokenIdX].tokenAddress,
lobAddress,
0
);
_callApprove(
tokens[lobs[i].tokenIdY].tokenAddress,
lobAddress,
0
);
}
}
// ...
}

function _checkLOB(uint8 lobId) internal view override {
require(lobId < lobs.length, ErrorReporter.UnknownLob());
// @audit This check prevents `claimOrder` from being called on a deactivated LOB.
require(lobs[lobId].isActive, ErrorReporter.LobDisabled());
}

While the owner can resolve this by reactivating the LOB, claiming the orders, and then deactivating it again, this process is cumbersome and introduces operational risk. An owner might forget to clear outstanding orders before deactivation, leading to temporarily locked funds.

Recommendation

Consider adding logic to the changeLob(...) function to automatically cancel all outstanding LPManager orders on a LOB when it is being deactivated. Alternatively, add a strong warning in the NatSpec documentation for the function, advising the owner to manually claim all orders before setting a LOB's status to inactive.

Resolution

The @param isActive description now clearly warns about the consequences of deactivation and the recovery procedure.

6.3 Missing input validation for priceConfig parameters in setConfig function

FileFix commitTypeStatus
src/LPManager.solPR #58InfoFixed

The setConfig(...) function in the LPManager contract allows the owner to set critical system parameters, including baseMultiplier and maxAllowedPriceDeviation from the PriceConfig struct. These parameters are used in the function ProxyPyth.validateAndResetPriceIfNeeded(...) to validate LP token price movements.

Currently, the setConfig(...) function does not perform any validation on these two values.

// ...
// slot 12
address _adminFeeRecipient = feeConfig.adminFeeRecipient;
_checkForZeroAddress(_adminFeeRecipient);

uint24 _priceValidityPeriod = priceConfig.priceValidityPeriod;
// @audit The baseMultiplier parameter is not validated.
uint64 _baseMultiplier = priceConfig.baseMultiplier;

// ...
adminFeeRecipient = _adminFeeRecipient;
priceValidityPeriod = _priceValidityPeriod;
baseMultiplier = _baseMultiplier;

// slot 13
// @audit The maxAllowedPriceDeviation parameter is not validated.
uint64 _maxAllowedPriceDeviation = priceConfig.maxAllowedPriceDeviation;
// ...

While this function is owner-restricted, a misconfiguration—such as setting baseMultiplier to a value greater than the WAD value of 1e18 or setting either parameter to zero—could compromise the price validation logic.

Recommendation

Consider adding input validation for the baseMultiplier and maxAllowedPriceDeviation parameters within the setConfig(...) function.

Resolution

Fixed in commit 651366ac. Added validation ensuring:

  • baseMultiplier is restricted between 50% and 100%
  • maxAllowedPriceDeviation cannot exceed maximum daily volatility (100% / √86400)

6.4 Missing validation for liquidity thresholds in setConfig

FileFix commitTypeStatus
src/LPManager.solPR #58InfoFixed

The setConfig(...) function in the LPManager contract is responsible for setting various configuration parameters, including minLiquidityValueUsd and maxLiquidityValueUsd. These variables define the lower and upper bounds for the total USD value of liquidity in the pool.

The function currently lacks a validation check to ensure that minLiquidityValueUsd is less than or equal to maxLiquidityValueUsd.

// ...
// @audit The minimum liquidity threshold is set here.
minLiquidityValueUsd = _minLiquidityValueUsd;

// slot 11
// @audit The maximum liquidity threshold is set here.
uint128 _maxLiquidityValueUsd = liquidityConfig.maxLiquidityValueUsd;
// @audit A check is missing to ensure _minLiquidityValueUsd <= _maxLiquidityValueUsd.

maxLiquidityValueUsd = _maxLiquidityValueUsd;
// ...

Recommendation

Consider adding a require statement in the setConfig(...) function to validate that minLiquidityValueUsd is less than or equal to maxLiquidityValueUsd.

6.5 cooldownDuration can be cached to save an SLOAD

FileFix commitTypeStatus
src/LPManager.solPR #58InfoFixed

The checkCooldown(...) function in the LPManager contract reads the cooldownDuration state variable from storage twice if its value is not zero. Each read from storage consumes gas for an SLOAD operation.

function checkCooldown(address account) public view {
// @audit First SLOAD of `cooldownDuration`.
if (cooldownDuration == 0) {
return;
}
// @audit Second SLOAD of `cooldownDuration` occurs here.
require(
block.timestamp - lastAddedAt[account] >= cooldownDuration,
ErrorReporter.CooldownDurationNotYetPassed()
);
}

This double read is inefficient. The value of cooldownDuration can be read from storage once and stored in a local memory variable.

Recommendation

Consider caching the cooldownDuration state variable in a local memory variable at the beginning of the checkCooldown(...) function.

6.6 Functions mint and burn can be declared external

FileFix commitTypeStatus
src/LPToken.solPR #58Best PracticesFixed

The mint(...) and burn(...) functions in the LPToken contract are declared with public visibility. However, they are only designed to be called externally by the owner of the contract (the LPManager). These functions are never called internally from within the LPToken contract itself.

// ...

function mint(address account, uint256 value) onlyOwner public {
_mint(account, value);
emit TokensMinted(account, value);
}

function burn(address account, uint256 value) onlyOwner public {
_burn(account, value);
emit TokensBurned(account, value);
}
// ...

For functions that are only ever called from outside the contract, using external visibility is a best practice.

Recommendation

Consider changing the visibility of the mint(...) and burn(...) functions from public to external.

6.7 Inconsistent early return pattern in state-setting functions

FileFix commitTypeStatus
src/LPManager.solPR #58Best PracticesFixed

There is an inconsistent pattern in how permissioned, state-setting functions handle redundant calls. Some functions, like changePendingPrimaryMarketMaker(...) and acceptPrimaryMarketMaker(...), check if the new state is the same as the current state and return early to avoid unnecessary operations. However, other functions, namely changeMarketMaker(...) and changeDepositor(...), do not have this check.

These functions will perform a state write and emit an event even if the new value is identical to the one already in storage.

// @audit This function writes to storage even if marketMakers[marketMaker] already equals isActive.
function changeMarketMaker(address marketMaker, bool isActive) external onlyOwner {
marketMakers[marketMaker] = isActive;

emit MarketMakerChanged(marketMaker, isActive);
}

// @audit This function writes to storage even if depositors[depositor] already equals isActive.
function changeDepositor(address depositor, bool isActive) external onlyOwner {
depositors[depositor] = isActive;

emit DepositorChanged(depositor, isActive);
}

In contrast, other functions in the same contract do implement this check:

function changePendingPrimaryMarketMaker(
address _primaryMarketMaker
) external onlyOwner {
address currentPendingPrimaryMarketMaker = pendingPrimaryMarketMaker;
// @audit This function correctly returns early if there is no state change.
if (currentPendingPrimaryMarketMaker == _primaryMarketMaker) {
return;
}
// ...
}

This inconsistency makes the codebase harder to maintain and can lead to unnecessary gas costs from redundant SSTORE operations and event emissions.

Recommendation

Consider applying a consistent pattern across all state-setting functions.

6.8 Inconsistent type casting for LPManager contract

FileFix commitTypeStatus
src/LPManager.solPR #58Best PracticesFixed

In various parts of the codebase, instances of the LPManager contract are inconsistently cast. Sometimes they are treated as the LPManager type, while other times they are cast to the parent ProxyLOB type. While this pattern does not introduce a direct security vulnerability, it leads to an inconsistent and confusing coding style.

Recommendation

Consider consistently using the LPManager type for all variables and interactions involving instances of the LPManager contract. Since LPManager inherits from ProxyLOB, it already provides access to all of its parent's public and external functions.

Resolution

Fixed in commit 045ea2f3. We've resolved the inheritance by making ILPManager inherit from IProxyLOB. This eliminates the redundant interface and removes all IProxyLOB casts across integrations, ensuring consistent typing with ILPManager throughout the codebase.

6.9 Misleading NatSpec for withdrawFromYieldVault function

FileFix commitTypeStatus
src/LPManager.solPR #58Best PracticesFixed

The NatSpec documentation for the withdrawFromYieldVault(...) function in the LPManager contract is inaccurate. Specifically, the comment for the assets parameter states that it is an "Amount of assets to withdraw directly," which does not reflect the function's actual implementation.

The function's logic takes the assets amount, converts it into a corresponding number of vault shares using yieldVault.previewWithdraw(assets), and then adds these shares to the shares parameter. The final withdrawal from the vault is based on this combined total of shares.

/// @notice Withdraws assets from a yield vault.
/// @param yieldVaultId Identifier of the target vault.
/// @param assets Amount of assets to withdraw directly.
/// @param shares Amount of shares to redeem.
/// @param expires Timestamp when operation expires.
function withdrawFromYieldVault(
uint8 yieldVaultId,
uint256 assets,
uint256 shares,
uint256 expires
) external /* ... */ {
// ...
IERC4626 yieldVault = IERC4626(yieldVaultAddress);

uint256 totalShares = shares;
if (assets > 0) {
// @audit The 'assets' amount is converted to shares before withdrawal.
totalShares += yieldVault.previewWithdraw(assets);
}

uint256 redeemedAssets = _callRedeem(yieldVault, totalShares);
// ...
}

Recommendation

Consider updating the NatSpec comment for the assets parameter in the withdrawFromYieldVault(...) function.

6.10 Missing NatSpec documentation for updateAndGetEpochPrice function

FileFix commitTypeStatus
src/ProxyPyth.solPR #58Best PracticesFixed

The updateAndGetEpochPrice(...) function has @notice, @dev, and @return comments but it is missing descriptions for its input parameters.

Recommendation

Consider adding comprehensive NatSpec @param documentation.

Resolution

Fixed in commit ff06e0ee. Added documentation for maxOracleAge and oracleConfRel input parameters.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

Although the Hanji team did not provide any written documentations, the team provided an overview of the core system components during our meetings, presenting a clear explanation of the intended functionalities and addressing questions raised by the Nethermind Security team. These sessions offered valuable insights and ensured a comprehensive understanding of the project’s technical foundations.

Test suite
128Tests passed0Failed

The complete test output is in the full report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.