Skip to content

feat: adjust primitives for position adjustment (0.13.0)#57

Merged
lukemacauley merged 1 commit into
mainfrom
feat/adjust-primitives
Jul 8, 2026
Merged

feat: adjust primitives for position adjustment (0.13.0)#57
lukemacauley merged 1 commit into
mainfrom
feat/adjust-primitives

Conversation

@lukemacauley

@lukemacauley lukemacauley commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

Phase 4 of the position-adjustment plan (perpcity-client thoughts/shared/plans/2026-07-08-position-adjustment.md).

  • adjustTaker / adjustMaker (and adjustMargin via dispatch) now await waitForTransactionReceipt and throw on revert, matching openTakerPosition/closePosition. Return shape unchanged ({txHash}).
  • estimateTakerAdjust(context, perp, { perpDelta }): quotes an arbitrary signed adjust delta via the client-side constant-liquidity swap model (no eth_call) — the adjust companion to estimateTakerPosition.
  • buildAdjustTakerCalls / buildAdjustMakerCalls: ordered approve+adjust batches for the gasless userOp path. Taker approval covers marginDelta only (margin is the only USDC pulled); maker approval covers marginDelta + amt1Limit when adding liquidity (same reasoning as buildOpenMakerPositionCalls).
  • closePosition stays full-unwind by design; partial close is composed client-side.
  • Version bumped to 0.13.0. After merge, cut a v0.13.0 release to trigger the npm publish workflow — the client PR pins ^0.13.0.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a taker adjustment quote so users can preview expected USD impact, fill price, and whether the move may exceed available liquidity.
    • Improved transaction handling for taker and maker adjustments by waiting for completion and surfacing failures if a transaction reverts.
  • Bug Fixes

    • Adjustment flows now automatically include approval steps only when needed, reducing failed or unnecessary wallet prompts.
  • Chores

    • Updated the app version to 0.13.0.

adjustTaker/adjustMaker/adjustMargin now await receipts and throw on
revert (aligned with open/close); estimateTakerAdjust quotes an
arbitrary signed delta via the client-side swap model; buildAdjustTakerCalls/
buildAdjustMakerCalls bundle the conditional USDC approve for gasless
userOp batching.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds an estimateTakerAdjust quoting function and a new EstimateTakerAdjustResult type, introduces buildAdjustTakerCalls and buildAdjustMakerCalls calldata batch builders with conditional USDC approval, adds receipt-based reversion checks to adjustTaker/adjustMaker, adds corresponding unit tests, and bumps the package version to 0.13.0.

Changes

Perp Adjust Feature

Layer / File(s) Summary
Result type
src/types/entity-data.ts
Adds exported EstimateTakerAdjustResult type with usdDelta, fillPrice, exceedsLiquidity.
Adjustment estimation
src/functions/perp-actions.ts
Adds estimateTakerAdjust which validates non-zero perpDelta, reads pool state, simulates via simulateTakerSwap, and returns the estimate.
Calldata batch builders
src/functions/calldata.ts
Adds buildAdjustTakerCalls and buildAdjustMakerCalls, each conditionally prepending a USDC approve call based on margin/liquidity deltas before the core adjust call.
Receipt reversion checks
src/functions/perp-actions.ts
Updates adjustTaker and adjustMaker to wait for transaction receipts and throw if status is "reverted".
Tests and version bump
src/__tests__/unit/adjust-primitives.test.ts, package.json
Adds unit tests covering estimation and call-building behavior; bumps version to 0.13.0.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant estimateTakerAdjust
  participant PerpCityContext
  participant simulateTakerSwap
  Caller->>estimateTakerAdjust: estimateTakerAdjust(perpAddress, perpDelta)
  estimateTakerAdjust->>estimateTakerAdjust: validate perpDelta != 0
  estimateTakerAdjust->>PerpCityContext: getPerpData(perpAddress)
  PerpCityContext-->>estimateTakerAdjust: pool state
  estimateTakerAdjust->>simulateTakerSwap: simulate(perpDelta, state)
  simulateTakerSwap-->>estimateTakerAdjust: usdDelta, fillPrice, exceedsLiquidity
  estimateTakerAdjust-->>Caller: EstimateTakerAdjustResult
Loading
sequenceDiagram
  participant Caller
  participant buildAdjustTakerCalls
  participant PublicClient
  participant USDC
  Caller->>buildAdjustTakerCalls: params(marginDelta, perpDelta, amt1Limit)
  buildAdjustTakerCalls->>PublicClient: readContract(allowance)
  PublicClient-->>buildAdjustTakerCalls: allowance
  alt marginDelta > 0 and allowance insufficient
    buildAdjustTakerCalls->>USDC: build approve(PERP, marginDelta)
  end
  buildAdjustTakerCalls->>buildAdjustTakerCalls: build adjustTaker call
  buildAdjustTakerCalls-->>Caller: CallData[]
Loading

Possibly related PRs

  • StrobeLabs/perpcity-sdk#46: Both PRs modify the PERP adjustment path in src/functions/perp-actions.ts (taker/maker adjust logic and related allowance/call construction).
  • StrobeLabs/perpcity-sdk#52: Both PRs extend the calldata-building layer in src/functions/calldata.ts around Perp position adjust flows and USDC approval gating.
  • StrobeLabs/perpcity-sdk#49: Both PRs modify adjustTaker/adjustMaker write flow in src/functions/perp-actions.ts, one adding receipt-status handling and the other changing fee-cap headroom.

Suggested reviewers: koko1123

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: new adjust primitives for position adjustment, with the version bump as a minor detail.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/adjust-primitives

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/functions/perp-actions.ts (1)

400-401: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated revert-check snippet across adjustTaker/adjustMaker.

The receipt-wait-and-throw block is now repeated verbatim in adjustTaker and adjustMaker (and reportedly in openTakerPosition/closePosition per the PR description). Consider extracting a small helper, e.g. waitForReceiptOrThrow(context.publicClient, txHash), to keep this logic single-sourced.

♻️ Proposed helper extraction
+async function waitForReceiptOrThrow(
+  publicClient: PublicClient,
+  txHash: Hex
+): Promise<void> {
+  const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
+  if (receipt.status === "reverted") throw new Error(`Transaction reverted. Hash: ${txHash}`);
+}

Then in adjustTaker/adjustMaker:

-    const receipt = await context.publicClient.waitForTransactionReceipt({ hash: txHash });
-    if (receipt.status === "reverted") throw new Error(`Transaction reverted. Hash: ${txHash}`);
+    await waitForReceiptOrThrow(context.publicClient, txHash);

Also applies to: 431-432

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/functions/perp-actions.ts` around lines 400 - 401, The receipt wait and
reverted-transaction check is duplicated in `adjustTaker` and `adjustMaker` (and
likely the similar position functions), so extract it into a shared helper such
as `waitForReceiptOrThrow` that takes `context.publicClient` and `txHash`.
Update `adjustTaker`, `adjustMaker`, and any other callers like
`openTakerPosition`/`closePosition` to use the helper so the transaction receipt
logic is single-sourced and consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/functions/perp-actions.ts`:
- Around line 400-401: The receipt wait and reverted-transaction check is
duplicated in `adjustTaker` and `adjustMaker` (and likely the similar position
functions), so extract it into a shared helper such as `waitForReceiptOrThrow`
that takes `context.publicClient` and `txHash`. Update `adjustTaker`,
`adjustMaker`, and any other callers like `openTakerPosition`/`closePosition` to
use the helper so the transaction receipt logic is single-sourced and
consistent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: adcabfea-5257-4043-be51-32d463a0b631

📥 Commits

Reviewing files that changed from the base of the PR and between a96c15a and 7b8b3c7.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • package.json
  • src/__tests__/unit/adjust-primitives.test.ts
  • src/functions/calldata.ts
  • src/functions/perp-actions.ts
  • src/types/entity-data.ts

@lukemacauley
lukemacauley merged commit 59f892a into main Jul 8, 2026
7 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