Skip to content

include FetchFees for deposit/withdraw by calling FetchFees grpc with…#29

Merged
rsoury merged 2 commits intomasterfrom
develop
Feb 26, 2026
Merged

include FetchFees for deposit/withdraw by calling FetchFees grpc with…#29
rsoury merged 2 commits intomasterfrom
develop

Conversation

@rsoury
Copy link
Copy Markdown
Member

@rsoury rsoury commented Feb 20, 2026

… token symbol

Summary by CodeRabbit

  • New Features

    • Enhanced fee retrieval with support for funding fees, deposit fees, and withdrawal fees from multiple data sources
    • Improved fee responses now include detailed source information and per-currency fee breakdowns
    • Added flexibility to query fees for both trading markets and individual tokens
  • Chores

    • Version updated to 0.2.5

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 20, 2026

Walkthrough

This PR updates the broker package version from 0.2.4 to 0.2.5 across build and package configuration. It adds FetchFees schema validation with boolean flag coercion and significantly refactors server-side FetchFees handling to support multiple fee sources and context-aware response structures.

Changes

Cohort / File(s) Summary
Version Bump
.sandbox/Dockerfile, package.json
Updated @usherlabs/cex-broker package version from 0.2.4 to 0.2.5 in build and runtime configurations.
Fee Payload Schema
src/schemas/action-payloads.ts
Introduced booleanLikeSchema for coercing string representations of booleans and added FetchFeesPayloadSchema with optional includeAllFees and includeFundingFees flags.
FetchFees Server Logic
src/server.ts
Refactored FetchFees action handler to support multiple fee source types. Added conditional branching for market vs. token symbols, multi-source fee fetching (deposit/withdraw fees via broker, fallback to currency metadata), and context-aware response structures.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Server
    participant BrokerAPI as Broker API
    participant MarketData as Market Data
    
    Client->>Server: FetchFees Request<br/>(symbol, includeAllFees, includeFundingFees)
    Server->>Server: Validate payload<br/>against FetchFeesPayloadSchema
    
    alt Market Symbol
        Server->>MarketData: Fetch market data
        MarketData-->>Server: Market info (base, quote)
        
        alt includeAllFees OR includeFundingFees
            Server->>BrokerAPI: fetchDepositWithdrawFees<br/>(currency codes)
            alt Fees Available
                BrokerAPI-->>Server: fundingFeesByCurrency
                Server->>Server: Set source: fetchDepositWithdrawFees
            else Fallback
                Server->>BrokerAPI: fetchCurrencies()
                BrokerAPI-->>Server: Currency metadata
                Server->>Server: Extract fees, set source: currencies
            end
            Server-->>Client: Market + Funding Fees<br/>(generalFee, feeStatus, fundingFees)
        else Summary Only
            Server-->>Client: Market Summary<br/>(generalFee, feeStatus)
        end
    else Token Symbol
        Server->>BrokerAPI: fetchDepositWithdrawFees<br/>(token code)
        alt Fees Available
            BrokerAPI-->>Server: fundingFeesByCurrency
            Server->>Server: Set source: fetchDepositWithdrawFees
        else Fallback
            Server->>BrokerAPI: fetchCurrencies()
            BrokerAPI-->>Server: Currency metadata
            Server->>Server: Extract fees, set source: currencies
        end
        Server-->>Client: Token Fees<br/>(feeScope: token, fundingFees)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Fiet 370 #23: Directly implements FetchFees action handling in server with overlapping logic for payload parsing and multi-source fee retrieval.
  • Add devcontainer config #22: Updates .sandbox/Dockerfile with the same @usherlabs/cex-broker package version bump dependency.

Suggested reviewers

  • victorshevtsov

Poem

🐰 A fee-fetching hop down the broker's dear path,
With booleans coerced and sources in bath,
From markets to tokens, the logic does weave,
Multiple sources that server shall retrieve!
Version bumped high, now the warren rejoice!
🥕✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is incomplete and truncated, ending with 'with…' which makes it difficult to understand the full scope. However, it does relate to the main changes: implementing FetchFees functionality for deposit/withdraw operations. Complete the title to clearly describe what is being called or included, e.g., 'Add FetchFees endpoint support for deposit/withdraw operations' or similar.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

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

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (2)
src/server.ts (2)

360-443: Response structure differs between fee sources.

The fundingFeesByCurrency object has different shapes depending on the source:

  • From fetchDepositWithdrawFees (lines 394-398): deposit and withdraw contain the raw fee structures or a { fee, percentage } fallback.
  • From currencies fallback (lines 419-428): deposit contains { enabled } and withdraw contains { enabled, fee, limits }.

Consumers may need to handle both shapes. Consider normalizing to a consistent structure, or ensure downstream code and documentation account for this variation.

♻️ Example normalization for the currencies fallback
 fundingFeesByCurrency[code] = {
-  deposit: {
-    enabled: currency.deposit ?? null,
-  },
-  withdraw: {
-    enabled: currency.withdraw ?? null,
-    fee: currency.fee ?? null,
-    limits: currency.limits?.withdraw ?? null,
-  },
+  deposit: currency.deposit !== undefined
+    ? { fee: null, percentage: null, enabled: currency.deposit }
+    : null,
+  withdraw: currency.withdraw !== undefined
+    ? { fee: currency.fee ?? null, percentage: null, enabled: currency.withdraw, limits: currency.limits?.withdraw ?? null }
+    : null,
   networks: currency.networks ?? {},
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server.ts` around lines 360 - 443, fetchFundingFees produces inconsistent
fundingFeesByCurrency shapes between the fetchDepositWithdrawFees branch and the
fetchCurrencies fallback; normalize the structure so every currency entry has
the same keys (e.g., deposit: { enabled, fee, percentage, limits?, networks? },
withdraw: { enabled, fee, percentage, limits?, networks? }, networks: {...}) by
mapping/transforming the outputs in both places inside fetchFundingFees (the
loop that assigns fundingFeesByCurrency in the fetchDepositWithdrawFees handling
and the loop in the fetchCurrencies fallback) to populate the unified keys
consistently; alternatively, if you keep both shapes, update downstream
consumers to accept both by centralizing a normalizer function called from
fetchFundingFees.

355-357: Consider clarifying the flag relationship.

The logic includeAllFees || includeFundingFees === true effectively treats includeFundingFees=true as equivalent to includeAllFees=true. If this is intentional, consider adding a brief comment explaining why includeFundingFees triggers the full fee response, or consider if includeFundingFees should have distinct behavior (e.g., only fetching funding fees without market details).

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

In `@src/server.ts` around lines 355 - 357, The current line conflates two
flags—parsedPayload.data.includeAllFees and
parsedPayload.data.includeFundingFees—by treating includeFundingFees === true as
equivalent to includeAllFees; either add an inline comment explaining that
includeFundingFees intentionally implies full fee data, or split them so
includeAllFees = Boolean(parsedPayload.data.includeAllFees) and const
includeFundingFees = parsedPayload.data.includeFundingFees === true (and update
any downstream checks to consult includeFundingFees when only funding fees are
needed); update usages of includeAllFees in the request-handling logic to use
the new includeFundingFees variable where appropriate.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 53ed54f and 3d57170.

📒 Files selected for processing (4)
  • .sandbox/Dockerfile
  • package.json
  • src/schemas/action-payloads.ts
  • src/server.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-01-29T17:09:55.684Z
Learnt from: victorshevtsov
Repo: usherlabs/cex-broker PR: 23
File: src/client.dev.ts:72-76
Timestamp: 2026-01-29T17:09:55.684Z
Learning: In the cex-broker codebase, Action.FetchAccountId must remain implemented in src/server.ts to support external consumers like fiet-prover that depend on fetching account IDs from CEX endpoints; removing or replacing this handler breaks backward compatibility.

Applied to files:

  • src/server.ts
🧬 Code graph analysis (1)
src/server.ts (2)
src/schemas/action-payloads.ts (1)
  • FetchFeesPayloadSchema (82-85)
src/helpers/logger.ts (1)
  • log (40-40)
🔇 Additional comments (7)
package.json (1)

3-3: LGTM!

Version bump to 0.2.5 aligns with the new FetchFees feature additions.

.sandbox/Dockerfile (1)

9-9: LGTM!

Dockerfile version correctly aligned with package.json version 0.2.5.

src/schemas/action-payloads.ts (2)

68-85: LGTM!

The booleanLikeSchema preprocessing correctly handles common string boolean representations ("true"/"1"/"yes" and "false"/"0"/"no") with case-insensitive matching. Invalid inputs appropriately pass through to fail z.boolean() validation.

The FetchFeesPayloadSchema structure is well-defined with sensible defaults.


98-98: LGTM!

Type export correctly inferred from the schema.

src/server.ts (3)

30-30: LGTM!

Import correctly added for the new schema.


445-483: LGTM!

Market symbol handling is well-structured:

  • Properly distinguishes market symbols (containing "/") from token symbols
  • Includes early return optimization when includeAllFees is false
  • Correctly extracts base/quote currencies for funding fee lookup
  • Response structure clearly indicates scope via feeScope field

485-496: LGTM!

Token symbol handling correctly normalizes to uppercase and returns a consistent response structure with feeScope: "token".

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/server.ts`:
- Around line 360-443: fetchFundingFees produces inconsistent
fundingFeesByCurrency shapes between the fetchDepositWithdrawFees branch and the
fetchCurrencies fallback; normalize the structure so every currency entry has
the same keys (e.g., deposit: { enabled, fee, percentage, limits?, networks? },
withdraw: { enabled, fee, percentage, limits?, networks? }, networks: {...}) by
mapping/transforming the outputs in both places inside fetchFundingFees (the
loop that assigns fundingFeesByCurrency in the fetchDepositWithdrawFees handling
and the loop in the fetchCurrencies fallback) to populate the unified keys
consistently; alternatively, if you keep both shapes, update downstream
consumers to accept both by centralizing a normalizer function called from
fetchFundingFees.
- Around line 355-357: The current line conflates two
flags—parsedPayload.data.includeAllFees and
parsedPayload.data.includeFundingFees—by treating includeFundingFees === true as
equivalent to includeAllFees; either add an inline comment explaining that
includeFundingFees intentionally implies full fee data, or split them so
includeAllFees = Boolean(parsedPayload.data.includeAllFees) and const
includeFundingFees = parsedPayload.data.includeFundingFees === true (and update
any downstream checks to consult includeFundingFees when only funding fees are
needed); update usages of includeAllFees in the request-handling logic to use
the new includeFundingFees variable where appropriate.

@rsoury rsoury requested a review from outerlook February 20, 2026 10:48
@rsoury rsoury merged commit 4e2bd10 into master Feb 26, 2026
5 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