Skip to content

fix(token-swap): correct ratio calculation and liquidity assertion in deposit_liquidity#567

Open
HkSolDev wants to merge 3 commits intosolana-developers:mainfrom
HkSolDev:fix/token-swap-deposit-liquidity
Open

fix(token-swap): correct ratio calculation and liquidity assertion in deposit_liquidity#567
HkSolDev wants to merge 3 commits intosolana-developers:mainfrom
HkSolDev:fix/token-swap-deposit-liquidity

Conversation

@HkSolDev
Copy link
Copy Markdown

@HkSolDev HkSolDev commented Apr 14, 2026

Summary

Fixes the deposit_liquidity instruction which had incorrect ratio
calculation logic and test assertions that didn't catch the bug.

Root Cause

The ratio was computed with checked_mul (pool_a × pool_b) instead of
checked_div (pool_a / pool_b), so deposit proportionality was wrong.
Tests were also passing the wrong token amount for the B slot, masking
the bug entirely.

Changes

programs/token-swap/src/instructions/deposit_liquidity.rs

  • Changed ratio from pool_a.checked_mul(pool_b)pool_a.checked_div(pool_b)
    so proportionality is calculated correctly
  • Replaced .unwrap() with .ok_or(DepositTooSmall)? on checked_div
    to avoid panic when pool_b is zero

tests/deposit-liquidity.ts

  • Pass depositAmountB (1M) instead of depositAmountA (4M) for token B slot
    so unequal deposits are actually tested
  • Fix liquidity assertion: use sqrt(A × B) - minLiquidity formula
    instead of A - minLiquidity which only worked when A == B
  • Fix token B balance assertion: subtract depositAmountB not depositAmountA

Testing

```bash
cargo build-sbf # ✅ passes (warnings only)
anchor test # ✅ 7/7 tests pass
```

Closes #512

Screenshot 2026-04-14 at 10 53 40 PM

@HkSolDev
Copy link
Copy Markdown
Author

@claude

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: token-swap Anchor program

1 participant