Skip to content
Business logic Audit finding Intermediate

Deleveragable Positions Cannot Be Fully Liquidated

The liquidation function fails when fully liquidating a deleveragable position because the post-liquidation total risk becomes zero, triggering a panic in the health check. This prevents liquidators from closing insolvent positions, forcing the protocol to rely on deleverage and risking bad debt.

handsomegiraffe Follow with Bauchibred, CODESPECT and 7 others

Originally disclosed on Code4rena

Submitted by handsomegiraffe, also found by Bauchibred, CODESPECT, crunter, eta, hakunamatata, Hueber, m4k2, montecristo, and zzykxx

https://github.com/starkware-libs/starknet-perpetual/blob/main/workspace/apps/perpetuals/contracts/src/core/value_risk_calculator.cairo#L92

Finding description

According to spec, a position is liquidatable when Total Value (TV) is less than Total Risk (TR) (TV < TR) and deleveragable when TV < 0.

Liquidation is the preferred mechanism (over Deleverage) to wind down a deleveragable position because it is matched with a limit order. This is unlike the Deleverage mechanism which matches the unhealthy position with another healthy position, which reduces the health of deleverager’s position.

However, full liquidation of a deleveragable position will always fail the assert_healthy_or_healthier check. This is because when a position is fully liquidated, it no longer has exposure to the synthetic asset and TR == 0. But yet the check panics when TR is zero.

pub fn assert_healthy_or_healthier(position_id: PositionId, tvtr: TVTRChange) {
    let position_state_after_change = get_position_state(position_tvtr: tvtr.after);

    //@audit a deleveragable position has TV < 0 (not healthy) and will skip the return here unlike liquidatable (but not deleveragable) positions
    if position_state_after_change == PositionState::Healthy {
        return;
    }

	//@audit total_risk is zero after liquidating a deleveragable postion -- causing panic here
    if tvtr.before.total_risk.is_zero() || tvtr.after.total_risk.is_zero() {
        panic_with_byte_array(@position_not_healthy_nor_healthier(:position_id));
    }

This issue could also occur with liquidatable-only positions. For example, Position A is liquidatable with TV = 5. During liquidation, a liquidation fee of 10 is charged. Position A after-TV is now -5. Position is now not healthy, and if fully liquidated (TR == 0) will also revert.

Impact

This bug breaks a core piece of the protocol’s risk engine: fully liquidating a deleveragable position. As a result:

  • Toxic positions remain open, even when insolvent.
  • Liquidators are blocked, reducing incentives and weakening protocol safety.
  • The protocol is forced to fall back on deleverage, a less fair and more disruptive mechanism.
  • In volatile conditions, this can lead to bad debt accumulation and threaten system stability.

Proof of Concept

Add this test to test*core.cairo, run snforge test test*unsuccessful_liquidate

#[test]
#[should_panic(expected: "POSITION_NOT_HEALTHY_NOR_HEALTHIER")]
fn test_unsuccessful_liquidate() {
    // Setup state, token and user:
    let cfg: PerpetualsInitConfig = Default::default();
    let token_state = cfg.collateral_cfg.token_cfg.deploy();
    let mut state = setup_state_with_active_asset(cfg: @cfg, token_state: @token_state);

    let liquidator = Default::default();
    init_position(cfg: @cfg, ref :state, user: liquidator);
    let liquidated = UserTrait::new(position_id: POSITION_ID_2, key_pair: KEY_PAIR_2());
    init_position(cfg: @cfg, ref :state, user: liquidated);
    add_synthetic_to_position(
        ref :state,
        synthetic_id: cfg.synthetic_cfg.synthetic_id,
        position_id: liquidated.position_id,
        balance: -SYNTHETIC_BALANCE_AMOUNT,
    );

    // Test params:
    let BASE = 20;
    let QUOTE = -2000; // oracle price is $100
    let INSURANCE_FEE = 1;
    let FEE = 2;

    // Setup parameters:
    let expiration = Time::now().add(delta: Time::days(1));
    let operator_nonce = state.get_operator_nonce();

    let collateral_id = cfg.collateral_cfg.collateral_id;
    let synthetic_id = cfg.synthetic_cfg.synthetic_id;

    let order_liquidator = Order {
        position_id: liquidator.position_id,
        salt: liquidator.salt_counter,
        base_asset_id: synthetic_id,
        base_amount: -BASE,
        quote_asset_id: collateral_id,
        quote_amount: -QUOTE,
        fee_asset_id: collateral_id,
        fee_amount: FEE,
        expiration,
    };

    let liquidator_hash = order_liquidator.get_message_hash(liquidator.get_public_key());
    let liquidator_signature = liquidator.sign_message(liquidator_hash);

    // Panics with "POSITION_NOT_HEALTHY_NOR_HEALTHIER" as total_risk after is 0
    cheat_caller_address_once(contract_address: test_address(), caller_address: cfg.operator);
    state
        .liquidate(
            :operator_nonce,
            :liquidator_signature,
            liquidated_position_id: liquidated.position_id,
            liquidator_order: order_liquidator,
            actual_amount_base_liquidated: BASE,
            actual_amount_quote_liquidated: QUOTE,
            actual_liquidator_fee: FEE,
            liquidated_fee_amount: INSURANCE_FEE,
        );
}
Logs:
asset price: Price { value: 26843545600 }
asset balance before: Balance { value: -20 }
asset balance after: Balance { value: 0 }
asset value before: -2000
asset value after: 0
risk factor before: RiskFactor { value: 50 }
risk factor after: RiskFactor { value: 50 }
collateral balance before: Balance { value: 2000 }
collateral balance after: Balance { value: -1 }
collateral value before: 2000
collateral value after: -1
total value before: 0
total value after: -1
position is liquidatable
position is deleveragable
tvtr.before.total_risk: 1000
tvtr.after.total_risk: 0
[PASS] perpetuals::tests::test_core::test_unsuccessful_liquidate (gas: ~8069)

Recommended mitigation steps

If a deleveragable position is fully liquidated (i.e. zero synthetic balance after), the assert_healthy_or_healthier check could be skipped.

oded (Starknet Perpetual) confirmed


The original report as published on Code4rena, by handsomegiraffe. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The health check function panics when total risk is zero, which occurs after fully liquidating a deleveragable position, instead of allowing the liquidation to succeed.

Impact

Toxic positions remain open, liquidators are blocked, and the protocol may accumulate bad debt, threatening system stability.

What the attacker needed

A deleveragable position exists; liquidator submits a full liquidation order

The fix

The assert_healthy_or_healthier check should be skipped when a deleveragable position is fully liquidated (i.e., zero synthetic balance after).

How it was found

  1. Set up a position with a negative synthetic balance, making it deleveragable.
  2. Call the liquidate function with an order that fully closes the position.
  3. The transaction reverts with POSITION_NOT_HEALTHY_NOR_HEALTHIER because total risk after liquidation is zero.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

In a perpetual trading protocol, positions can become risky when their value drops below a threshold. Liquidators are supposed to close these positions, but a bug in the code causes the liquidation to fail when the position is fully closed, because the code incorrectly treats a zero-risk state as an error. This means bad positions stay open, which can harm the protocol.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by handsomegiraffe

View all

2 more disclosed reports, best first.

More from Starknet Perpetual

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.