Skip to content

feat: interact with TN order book#170

Merged
MicBun merged 2 commits intomainfrom
featOrderBook
Jan 21, 2026
Merged

feat: interact with TN order book#170
MicBun merged 2 commits intomainfrom
featOrderBook

Conversation

@MicBun
Copy link
Copy Markdown
Member

@MicBun MicBun commented Jan 21, 2026

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

Summary by CodeRabbit

  • New Features

    • Complete order-book subsystem: create/list/validate markets, place/manage orders, settle markets, and distribute rewards.
    • New query APIs: view order book entries, user positions, market depth, best prices, collateral and reward history.
    • Public typed API and input validations for all order-book operations.
    • Order-book accessible via the HTTP client interface.
  • Chores

    • Dependency/version updates.

✏️ Tip: You can customize this high-level summary in your review settings.

@MicBun MicBun self-assigned this Jan 21, 2026
@MicBun MicBun added the enhancement New feature or request label Jan 21, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 21, 2026

📝 Walkthrough

Walkthrough

Adds a complete OrderBook client and public types for interacting with a Kwil-based order book: infrastructure, market/order operations, queries, settlement/rewards, parsing helpers, client integration, and dependency updates.

Changes

Cohort / File(s) Summary
Core OrderBook Infrastructure
core/contractsapi/order_book.go
Implements OrderBook type, NewOrderBookOptions, LoadOrderBook, internal call/execute wrappers, and robust column extraction helpers (int/int64/bool/string/bytes). Adds compile-time interface assertion.
Market Operations
core/contractsapi/order_book_markets.go
Adds market APIs: CreateMarket, GetMarketInfo, GetMarketByHash, ListMarkets, MarketExists, ValidateMarketCollateral and parsing helpers (parseMarketInfoRow, parseMarketSummaryRow, parseMarketValidationRow).
Order Operations
core/contractsapi/order_book_orders.go
Adds order management methods: PlaceBuyOrder, PlaceSellOrder, PlaceSplitLimitOrder, CancelOrder, ChangeBid, ChangeAsk; each validates input and executes contract commands.
Query Operations
core/contractsapi/order_book_queries.go
Adds query methods: GetOrderBook, GetUserPositions, GetMarketDepth, GetBestPrices, GetUserCollateral and row-parsing helpers for each result shape.
Settlement & Rewards
core/contractsapi/order_book_settlement.go
Adds SettleMarket, SampleLPRewards, GetDistributionSummary, GetDistributionDetails, GetParticipantRewardHistory plus parsing helpers for distribution and reward rows.
Type Definitions
core/types/order_book_types.go
Introduces IOrderBook interface plus input types (with Validate() methods) and output types for markets, orders, positions, depth, prices, collateral, distributions, LP rewards, and reward history.
Client Integration
core/tnclient/client.go
Adds LoadOrderBook() on Client returning IOrderBook for HTTP transport; returns error for non-HTTP transports.
Dependencies
go.mod
Updates Kwil-related dependencies and promotes google.golang.org/protobuf v1.36.8 to a direct requirement.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant OrderBook
    participant GatewayClient
    participant KwilDB as Kwil Database

    rect rgba(200, 150, 100, 0.5)
    Note over Caller,OrderBook: CreateMarket flow
    Caller->>OrderBook: CreateMarket(CreateMarketInput)
    OrderBook->>OrderBook: Validate input
    OrderBook->>GatewayClient: Execute("create_market", args)
    GatewayClient->>KwilDB: execute create_market
    KwilDB-->>GatewayClient: txHash
    GatewayClient-->>OrderBook: txHash
    OrderBook-->>Caller: txHash
    end

    rect rgba(150, 200, 150, 0.5)
    Note over Caller,OrderBook: PlaceBuyOrder flow
    Caller->>OrderBook: PlaceBuyOrder(PlaceBuyOrderInput, opts)
    OrderBook->>OrderBook: Validate input
    OrderBook->>GatewayClient: Execute("place_buy_order", args)
    GatewayClient->>KwilDB: execute place_buy_order
    KwilDB-->>GatewayClient: txHash
    GatewayClient-->>OrderBook: txHash
    OrderBook-->>Caller: txHash
    end

    rect rgba(150, 150, 200, 0.5)
    Note over Caller,OrderBook: GetOrderBook query
    Caller->>OrderBook: GetOrderBook(GetOrderBookInput)
    OrderBook->>OrderBook: Validate input
    OrderBook->>GatewayClient: Call("get_order_book", args)
    GatewayClient->>KwilDB: query get_order_book
    KwilDB-->>GatewayClient: rows
    GatewayClient-->>OrderBook: rows
    OrderBook->>OrderBook: parse rows -> []OrderBookEntry
    OrderBook-->>Caller: []OrderBookEntry
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

"I hopped through code with care and cheer,
Markets, orders, and rewards appear,
Types aligned and helpers bright,
Queries, settles, transactions light—
A rabbit's dance for trading right." 🐇✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: interact with TN order book' is clear, concise, and directly describes the main change—adding order book interaction functionality to the SDK.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

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 and usage tips.

@holdex
Copy link
Copy Markdown

holdex bot commented Jan 21, 2026

Time Submission Status

Member Status Time Action Last Update
MicBun ✅ Submitted 8h Update time Jan 21, 2026, 9:45 PM

@MicBun MicBun marked this pull request as ready for review January 21, 2026 20:54
Copy link
Copy Markdown
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.

Actionable comments posted: 7

🤖 Fix all issues with AI agents
In `@core/contractsapi/order_book_markets.go`:
- Around line 79-91: The code accesses row[0] and row[1:] without validating the
number of columns; add a bounds check on len(row) (e.g., require len(row) >= 10
or at least >= 1+expectedMarketInfoCols) before extracting the ID and calling
parseMarketInfoRow, and return a descriptive error (wrapped with
errors.WithStack) if the row is too short; update the block around
result.Values[0], extractIntColumn, and parseMarketInfoRow to perform this
validation so you never slice out-of-bounds.

In `@core/contractsapi/order_book_queries.go`:
- Around line 105-118: In GetBestPrices (method on OrderBook) replace the error
return when len(result.Values) == 0 with returning a zero-value BestPrices (e.g.
&types.BestPrices{} or equivalent) and nil error so empty order books are
treated as non-exceptional; keep the input.Validate and call to o.call as-is and
only change the branch that currently does fmt.Errorf("no price data...") to
return the empty BestPrices result and nil error.

In `@core/contractsapi/order_book_settlement.go`:
- Around line 84-97: The handler in OrderBook.GetDistributionSummary currently
treats an empty result.Values as an error; update it to align with the docs by
returning (nil, nil) when no distribution exists (e.g., market not settled)
instead of fmt.Errorf; locate the check in GetDistributionSummary and replace
the error return branch so it returns nil, nil with a brief comment indicating
"no distribution yet" to preserve intent.

In `@core/contractsapi/order_book.go`:
- Around line 42-55: The call method in OrderBook returns callResult.QueryResult
without checking if QueryResult is nil, which can cause panics; modify the
call(ctx, action, args) function to check if callResult.QueryResult == nil and
return a clear error (e.g., fmt.Errorf("action %s returned nil QueryResult",
action)) before returning, keeping the existing checks for callResult and
callResult.Error intact so callers never receive a nil *kwiltypes.QueryResult.
- Around line 130-137: The extractBytesColumn function currently asserts val as
[]byte but the gateway returns BYTEA as base64-encoded strings; update
extractBytesColumn to accept string (and nil/empty) values, detect if val is
nil, if val is a string decode it from base64 into the target *[]byte, and
return a descriptive error on decode failures; mirror the implementation pattern
used in attestation_actions.go (or move the decoding logic into a shared helper
used by both places) and keep the error messages consistent with other extract*
helpers.

In `@core/types/order_book_types.go`:
- Around line 531-538: The Validate method on GetParticipantRewardHistoryInput
currently only checks WalletHex length and "0x" prefix but not that the
remaining characters are valid hex; update
GetParticipantRewardHistoryInput.Validate to decode/validate the substring after
the "0x" (e.g., using hex decoding) and return a descriptive error if decoding
fails so callers get immediate feedback rather than failing later in the
contract call.
- Around line 169-176: The current CreateMarketInput.Validate only checks
c.SettleTime <= 0; update it to enforce the "must be future" requirement by
comparing c.SettleTime to the current unix time (e.g., time.Now().Unix()) and
returning an error if c.SettleTime is not strictly greater than now; update the
error text from "must be positive" to something like "settle_time must be a
future unix timestamp" and keep the QueryHash length check and other logic in
CreateMarketInput.Validate unchanged.

@MicBun
Copy link
Copy Markdown
Member Author

MicBun commented Jan 21, 2026

Log: the PR is too large, will complete the rest in a new pr

@MicBun MicBun merged commit bf99422 into main Jan 21, 2026
5 checks passed
@MicBun MicBun deleted the featOrderBook branch January 21, 2026 21:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant