Skip to content

feat: read any wallet's order-book portfolio by address#162

Merged
MicBun merged 1 commit into
mainfrom
feat/orderbook-by-wallet-getters
Jun 24, 2026
Merged

feat: read any wallet's order-book portfolio by address#162
MicBun merged 1 commit into
mainfrom
feat/orderbook-by-wallet-getters

Conversation

@MicBun

@MicBun MicBun commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

resolves: https://github.com/truflation/website/issues/4171

Problem

The JS SDK can only read an order-book portfolio for the signer itself — getUserPositions / getUserCollateral are @caller-scoped. There's no way for an owner, or a delegated market-maker bot, to read another wallet's positions/collateral by address, the way the Go and Python SDKs already can (migration 051). This is needed to monitor an agent wallet (MAA) without holding its key.

Change

Adds two address-parameterized order-book getters to OrderbookAction, at parity with sdk-go/sdk-py:

  • getPositionsByWallet(walletHex)WalletPosition[] (calls get_positions_by_wallet)
  • getCollateralByWallet(walletHex, bridge)UserCollateral (calls get_collateral_by_wallet)

Both read the wallet you pass in, not the signer. Supporting pieces:

  • New WalletPosition / RawWalletPosition types — they carry positionType (the node's position_type column), so they intentionally differ from the @caller UserPosition (which carries lastUpdated); UserCollateral is reused as-is.
  • validateWalletHex helper (20-byte hex, optional 0x), mirroring sdk-go's validation.
  • Empty wallet returns [] (positions) / { "0", "0", "0" } (collateral), matching sdk-go/sdk-py.

Verification

  • 10 new co-located unit tests (orderbookAction.test.ts) assert the exact action name, named params, row→object mapping, empty-result handling, wallet validation, and error paths.
  • npm run typecheck clean; full unit suite green (266 tests).
  • Exercised live against testnet via the agent-wallet lifecycle example: getPositionsByWallet[] and getCollateralByWallet → zeros for a data-provision MAA — a clean return proving migration 051 is live on the network.

Summary by CodeRabbit

  • New Features

    • Added wallet-based orderbook queries for positions and collateral.
    • Introduced a new wallet position result shape for returned market data.
    • Expanded exported orderbook types and utilities for broader API use.
  • Bug Fixes

    • Added wallet address validation to catch invalid or empty addresses early.
    • Improved collateral lookups to return zeroed values when no data is found.
    • Added clearer error handling for failed wallet query responses.

@holdex

holdex Bot commented Jun 24, 2026

Copy link
Copy Markdown

Time Submission Status

Member # Time Running Total Status Last Update
MicBun 2h ✅ Submitted Jun 24, 2026, 2:47 PM

Submit or update total time with:

@holdex pr submit-time 2h

Add time on top of previous submission with:

@holdex pr add-time 1h30m

See available commands to help comply with our Guidelines.

@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@MicBun, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 23 minutes and 25 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 33b98663-dc5c-4623-ac60-3e57ba0a77a6

📥 Commits

Reviewing files that changed from the base of the PR and between 7ad7dfb and af17f91.

📒 Files selected for processing (5)
  • src/contracts-api/orderbookAction.test.ts
  • src/contracts-api/orderbookAction.ts
  • src/internal.ts
  • src/types/orderbook.ts
  • src/util/orderbookHelpers.ts
📝 Walkthrough

Walkthrough

Two new public methods are added to OrderbookAction: getPositionsByWallet and getCollateralByWallet. These rely on a new validateWalletHex utility and two new types (WalletPosition, RawWalletPosition). WalletPosition is re-exported from src/internal.ts. Unit tests cover mapping, validation, empty results, and error paths.

Changes

Wallet-address portfolio getters on OrderbookAction

Layer / File(s) Summary
WalletPosition types and validateWalletHex utility
src/types/orderbook.ts, src/util/orderbookHelpers.ts
Adds WalletPosition (with positionType) and RawWalletPosition interfaces, plus a validateWalletHex helper that normalizes and validates a 40-hex-character wallet address.
getPositionsByWallet and getCollateralByWallet implementation
src/contracts-api/orderbookAction.ts, src/internal.ts
Imports new types and validator into OrderbookAction; implements getPositionsByWallet (maps rows to WalletPosition[]) and getCollateralByWallet (maps rows to UserCollateral with zero fallback); re-exports WalletPosition from src/internal.ts.
Unit tests
src/contracts-api/orderbookAction.test.ts
Vitest suite using a mocked NodeKwil call and signer; covers correct action name/params, row mapping, empty results, input validation failures (bad wallet, missing bridge), and non-200 status errors.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

enhancement

Suggested reviewers

  • pr-time-tracker

Poem

🐇 Hop, hop — a wallet hex to check,
Forty chars of hex in a row,
Positions and collateral, in a tidy deck,
0x prefix? Off it shall go.
The orderbook grows with each new call,
This bunny tests every edge — none shall fall! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: reading an order-book portfolio for any wallet by address.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/orderbook-by-wallet-getters

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/types/orderbook.ts (1)

157-158: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a string-literal union for positionType.

The JSDoc enumerates exactly 'holding' | 'buy_order' | 'sell_order', but the field is typed as string. A union would give callers compile-time safety and autocompletion.

♻️ Optional
-  /** Kind of position: 'holding' | 'buy_order' | 'sell_order' */
-  positionType: string;
+  /** Kind of position */
+  positionType: "holding" | "buy_order" | "sell_order";
🤖 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/types/orderbook.ts` around lines 157 - 158, The positionType field in the
orderbook type is too broad and should match the documented allowed values.
Update the type definition in the orderbook model to use a string-literal union
for holding, buy_order, and sell_order, keeping the JSDoc and the actual type
aligned so callers of positionType get compile-time safety and autocomplete.
🤖 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.

Inline comments:
In `@src/contracts-api/orderbookAction.ts`:
- Around line 747-754: getCollateralByWallet currently only checks for an empty
bridge string, so update it to use the existing validateBridge helper just like
createMarket does. Replace the ad hoc bridge guard inside getCollateralByWallet
with validateBridge(bridge) to keep the whitelist consistent for known
order-book bridges and fail fast on invalid values.

---

Nitpick comments:
In `@src/types/orderbook.ts`:
- Around line 157-158: The positionType field in the orderbook type is too broad
and should match the documented allowed values. Update the type definition in
the orderbook model to use a string-literal union for holding, buy_order, and
sell_order, keeping the JSDoc and the actual type aligned so callers of
positionType get compile-time safety and autocomplete.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3780df59-78cc-4e57-8f9f-4ba480e46d08

📥 Commits

Reviewing files that changed from the base of the PR and between 8c75d8b and 7ad7dfb.

📒 Files selected for processing (5)
  • src/contracts-api/orderbookAction.test.ts
  • src/contracts-api/orderbookAction.ts
  • src/internal.ts
  • src/types/orderbook.ts
  • src/util/orderbookHelpers.ts

Comment thread src/contracts-api/orderbookAction.ts Outdated
@MicBun MicBun self-assigned this Jun 24, 2026
@MicBun

MicBun commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

@holdex pr submit-time 2h

@MicBun
MicBun force-pushed the feat/orderbook-by-wallet-getters branch from 7ad7dfb to af17f91 Compare June 24, 2026 14:57
@MicBun
MicBun merged commit 74f0b78 into main Jun 24, 2026
4 checks passed
@MicBun
MicBun deleted the feat/orderbook-by-wallet-getters branch June 24, 2026 15:08
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