Skip to content

fix: align SDK with perpcity-contracts v0.0.1#41

Merged
koko1123 merged 2 commits intomainfrom
koko/v0.0.1-contract-compat
Mar 9, 2026
Merged

fix: align SDK with perpcity-contracts v0.0.1#41
koko1123 merged 2 commits intomainfrom
koko/v0.0.1-contract-compat

Conversation

@koko1123
Copy link
Contributor

@koko1123 koko1123 commented Mar 9, 2026

Summary

  • Align all ABIs, SDK source, mock contracts, and tests with perpcity-contracts v0.0.1
  • Fix quoteClosePosition return type (6 values, int256 netMargin, added notional)
  • Remove startingSqrtPriceX96 from CreatePerpParams (now auto-derived from beacon index)
  • Replace individual module registration functions with generic registerModule/isModuleRegistered
  • Update PositionClosed event to match v0.0.1 (new trailing fields, field renames)
  • Add quoteSwap to ABI
  • Bump version to 0.5.0

Test plan

  • pnpm lint passes (0 issues)
  • pnpm test passes (187/187 unit tests)
  • pnpm test:integration passes (38/38 integration tests)
  • CodeRabbit review: no findings

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced position closure reporting with additional financial metrics (net delta, funding, utilization and liquidation fees, margin details).
    • Added notional field to position quotes.
  • Changes

    • Simplified module registration to a unified API.
    • Removed starting price parameter from position creation.
  • Version

    • Bumped to v0.5.0

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 9, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 45a1d80b-c21b-41a1-8ba6-984ac0690526

📥 Commits

Reviewing files that changed from the base of the PR and between 0e026b1 and f81e79f.

📒 Files selected for processing (7)
  • .github/workflows/ci.yml
  • .gitignore
  • tests/contracts/cache/solidity-files-cache.json
  • tests/contracts/out/MockFees.sol/MockFees.json
  • tests/contracts/out/MockMarginRatios.sol/MockMarginRatios.json
  • tests/contracts/out/MockPerpManager.sol/MockPerpManager.json
  • tests/contracts/out/MockUSDC.sol/MockUSDC.json
💤 Files with no reviewable changes (4)
  • tests/contracts/out/MockUSDC.sol/MockUSDC.json
  • tests/contracts/cache/solidity-files-cache.json
  • tests/contracts/out/MockFees.sol/MockFees.json
  • tests/contracts/out/MockMarginRatios.sol/MockMarginRatios.json
✅ Files skipped from review due to trivial changes (1)
  • .gitignore

📝 Walkthrough

Walkthrough

Version bumped to 0.5.0. PerpManager ABI consolidated module registration functions into a single registerModule function. Notional field added to quote results across codebase. StartingSqrtPriceX96 removed from CreatePerpParams. PositionClosed event enriched with additional position data. MockPerpManager contract expanded with setup and configuration methods.

Changes

Cohort / File(s) Summary
Package & Version
package.json
Version bumped from 0.4.3 to 0.5.0.
ABI & Type Definitions
src/abis/perp-manager.ts, src/types/entity-data.ts
Module registration functions consolidated (registerFeesModule, registerLockupPeriodModule, etc. merged into registerModule). PositionClosed event expanded with netUsdDelta, funding, utilizationFee, adl, liquidationFee, netMargin fields and renamed delta fields (perpDelta → exitPerpDelta, usdDelta → exitUsdDelta). CreatePerpParams startingPrice field removed.
Context & Integration
src/context.ts, src/__tests__/integration/context.test.ts
QuoteClosePosition return type expanded from 5-tuple to 6-tuple adding notional field. Integration test updated to pass notional value to setupMockQuoteResult.
Function Implementations
src/functions/open-position.ts, src/functions/position.ts, src/functions/perp-manager.ts
Type annotations updated to reflect 6-element tuple from quoteClosePosition. StartingSqrtPriceX96 calculation and import (priceToSqrtPriceX96) removed from perp-manager.
Test Infrastructure
src/__tests__/helpers/anvil-setup.ts, tests/contracts/MockPerpManager.sol
setupMockQuoteResult helper extended with notional parameter. MockPerpManager contract expanded with setProtocolFee, setupPerp, setupPosition, setupQuoteResult, cfgs, timeWeightedAvgSqrtPriceX96, positions, quoteClosePosition, createPerp, openTakerPos, openMakerPos, closePosition methods. CreatePerpParams struct updated to remove startingSqrtPriceX96.
Build Configuration & Artifacts
.github/workflows/ci.yml, tests/contracts/foundry.toml, .gitignore
CI workflow adds "Compile mock contracts" step executing forge build. Foundry config adds via_ir, optimizer, and optimizer_runs settings. Gitignore adds tests/contracts/out/ and tests/contracts/cache/ paths.
Build Artifacts
tests/contracts/cache/solidity-files-cache.json, tests/contracts/out/MockFees.sol/MockFees.json, tests/contracts/out/MockMarginRatios.sol/MockMarginRatios.json, tests/contracts/out/MockUSDC.sol/MockUSDC.json
Cache and compiled artifact files removed as build outputs are now ignored.
Generated Artifacts
tests/contracts/out/MockPerpManager.sol/MockPerpManager.json
New MockPerpManager contract artifact added containing ABI for expanded contract methods and events.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • rdave8
  • NTablang

Poem

🐰 The perps consolidate with grace,
Module registration finds its place,
Notional fields bloom anew,
Less starting price, more truth to pursue,
Version bumped—a cleaner race! 🎯

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main objective: aligning the SDK with perpcity-contracts v0.0.1, which is the primary purpose reflected throughout the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch koko/v0.0.1-contract-compat

Comment @coderabbitai help to get the list of available commands and usage tips.

- Update quoteClosePosition to return 6 values (added notional,
  netMargin changed from uint256 to int256)
- Remove startingSqrtPriceX96 from CreatePerpParams (now auto-derived
  from beacon index in contract)
- Rename AdjustNotionalParams fields (perpDelta->usdDelta,
  usdLimit->perpLimit)
- Replace individual module registration functions with generic
  registerModule/isModuleRegistered
- Update PositionClosed event with new trailing fields and renames
- Add quoteSwap function to ABI
- Update mock contracts and integration tests
- Bump version to 0.5.0
@koko1123 koko1123 force-pushed the koko/v0.0.1-contract-compat branch from 1a19ab5 to 0e026b1 Compare March 9, 2026 21:09
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/contracts/MockPerpManager.sol (1)

369-375: ⚠️ Potential issue | 🟠 Major

Emit real close-side values in PositionClosed.

_emitPositionClosed still reports wasMaker = false, hardcodes tick bounds, and reuses the entry deltas as exitPerpDelta/exitUsdDelta. After the v0.0.1 event rename, that means the mock can emit close events the real contract would never produce, so event-based integration coverage can pass against impossible data.

Suggested direction
         _positions[posId].perpId = perpId;
         _positions[posId].margin = uint256(params.margin);
         _positions[posId].marginRatios = MarginRatios(100000, 1000000, 50000);
+        _positions[posId].makerDetails.tickLower = params.tickLower;
+        _positions[posId].makerDetails.tickUpper = params.tickUpper;
+        _positions[posId].makerDetails.liquidity = params.liquidity;
         _positionExists[posId] = true;
@@
     function _emitPositionClosed(
         uint256 posId,
         Position memory pos,
         QuoteResult memory quote
     ) internal {
+        bool wasMaker = pos.makerDetails.liquidity != 0;
         emit PositionClosed(
             pos.perpId,
             _sqrtPrices[pos.perpId],
             1000, 1000,
             posId,
-            false,
+            wasMaker,
             quote.wasLiquidated,
             false,
-            pos.entryPerpDelta,
-            pos.entryUsdDelta,
-            -887220, 887220,
+            -pos.entryPerpDelta,
+            -pos.entryUsdDelta,
+            wasMaker ? pos.makerDetails.tickLower : int24(-887220),
+            wasMaker ? pos.makerDetails.tickUpper : int24(887220),
             0, 0, 0, 0, 0, quote.netMargin
         );
     }

Also applies to: 405-423

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/contracts/MockPerpManager.sol` around lines 369 - 375, The mock emits
impossible PositionClosed events: _emitPositionClosed is using hardcoded tick
bounds, sets wasMaker = false, and reuses entry deltas (from
_positions/_quoteResults) as exitPerpDelta/exitUsdDelta; update the mock to
compute realistic close-side fields before emitting PositionClosed by deriving
wasMaker from the stored _positions[posId].isMaker (or an equivalent flag),
compute exitTickLower/exitTickUpper from the actual closing tick range instead
of hardcoding, and set exitPerpDelta/exitUsdDelta using realistic exit deltas
(e.g., calculate differences between stored entry values in _positions[posId]
and actual close values or derive from _quoteResults[posId].exit values) so the
emitted PositionClosed event matches what the real contract would produce;
adjust the same logic in the other block (lines referenced around 405-423) to
keep behavior consistent.
🧹 Nitpick comments (2)
src/__tests__/integration/context.test.ts (1)

33-40: Add one signed netMargin fixture.

This setup only exercises a positive netMargin, but v0.0.1 changed that field to int256. A second case with netMargin < 0 would lock in the new decoding/formatting path as well.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/integration/context.test.ts` around lines 33 - 40, Add a second
test fixture that calls setupMockQuoteResult with the same parameters but a
negative netMargin value to exercise the int256 path; specifically duplicate the
existing call that uses TEST_POSITION_ID and change the netMargin argument (the
third/fourth numeric args ordering as in the call to setupMockQuoteResult) to a
negative BigInt (e.g., -545_000000n) and adjust any related comments to indicate
"netMargin: -545 USDC" so the test covers decoding/formatting for negative
netMargin values.
src/abis/perp-manager.ts (1)

252-266: Consider sourcing PERP_MANAGER_ABI from generated contract artifacts.

This file had to hand-edit events, tuple members, and return shapes in several places again. Importing a generated ABI from perpcity-contracts (or a checked-in artifact derived from it) would remove a recurring drift point and keep viem’s named tuple types aligned on future contract bumps.

Also applies to: 464-523, 709-737, 1090-1111, 1436-1669

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/abis/perp-manager.ts` around lines 252 - 266, Replace the hand-edited
PERP_MANAGER_ABI by importing the generated contract artifact (e.g., from the
perpcity-contracts package or a checked-in JSON artifact) and use that exported
ABI where PERP_MANAGER_ABI is referenced (including places referencing
events/tuples like ModuleRegistered); remove the inline/hand-written ABI
constant and update any references to use the imported artifact name, ensuring
viem named-tuple types are derived from that artifact; if necessary adjust the
import/export (e.g., export const PERP_MANAGER_ABI = artifact.abi) so the same
single source-of-truth ABI is used across the file and the other regions noted
(around the other ranges) to prevent future drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@tests/contracts/MockPerpManager.sol`:
- Around line 369-375: The mock emits impossible PositionClosed events:
_emitPositionClosed is using hardcoded tick bounds, sets wasMaker = false, and
reuses entry deltas (from _positions/_quoteResults) as
exitPerpDelta/exitUsdDelta; update the mock to compute realistic close-side
fields before emitting PositionClosed by deriving wasMaker from the stored
_positions[posId].isMaker (or an equivalent flag), compute
exitTickLower/exitTickUpper from the actual closing tick range instead of
hardcoding, and set exitPerpDelta/exitUsdDelta using realistic exit deltas
(e.g., calculate differences between stored entry values in _positions[posId]
and actual close values or derive from _quoteResults[posId].exit values) so the
emitted PositionClosed event matches what the real contract would produce;
adjust the same logic in the other block (lines referenced around 405-423) to
keep behavior consistent.

---

Nitpick comments:
In `@src/__tests__/integration/context.test.ts`:
- Around line 33-40: Add a second test fixture that calls setupMockQuoteResult
with the same parameters but a negative netMargin value to exercise the int256
path; specifically duplicate the existing call that uses TEST_POSITION_ID and
change the netMargin argument (the third/fourth numeric args ordering as in the
call to setupMockQuoteResult) to a negative BigInt (e.g., -545_000000n) and
adjust any related comments to indicate "netMargin: -545 USDC" so the test
covers decoding/formatting for negative netMargin values.

In `@src/abis/perp-manager.ts`:
- Around line 252-266: Replace the hand-edited PERP_MANAGER_ABI by importing the
generated contract artifact (e.g., from the perpcity-contracts package or a
checked-in JSON artifact) and use that exported ABI where PERP_MANAGER_ABI is
referenced (including places referencing events/tuples like ModuleRegistered);
remove the inline/hand-written ABI constant and update any references to use the
imported artifact name, ensuring viem named-tuple types are derived from that
artifact; if necessary adjust the import/export (e.g., export const
PERP_MANAGER_ABI = artifact.abi) so the same single source-of-truth ABI is used
across the file and the other regions noted (around the other ranges) to prevent
future drift.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0e9c4c38-96aa-4711-be8c-39d95c1ad8c5

📥 Commits

Reviewing files that changed from the base of the PR and between 55ae73a and 0e026b1.

📒 Files selected for processing (17)
  • package.json
  • src/__tests__/helpers/anvil-setup.ts
  • src/__tests__/integration/context.test.ts
  • src/abis/perp-manager.ts
  • src/context.ts
  • src/functions/open-position.ts
  • src/functions/perp-manager.ts
  • src/functions/position.ts
  • src/types/entity-data.ts
  • tests/contracts/MockPerpManager.sol
  • tests/contracts/cache/solidity-files-cache.json
  • tests/contracts/foundry.toml
  • tests/contracts/out/MockFees.sol/MockFees.json
  • tests/contracts/out/MockMarginRatios.sol/MockMarginRatios.json
  • tests/contracts/out/MockPerpManager.sol/MockPerpManager.json
  • tests/contracts/out/MockUSDC.sol/MockUSDC.json
  • tests/contracts/out/build-info/c47e4dff3ecab415.json
💤 Files with no reviewable changes (1)
  • src/types/entity-data.ts

Add tests/contracts/out/ and tests/contracts/cache/ to .gitignore.
Add forge build step to CI before integration tests.
@koko1123 koko1123 merged commit 173b855 into main Mar 9, 2026
4 checks passed
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.

1 participant