Skip to content

Conversation

adith-dinesh
Copy link
Contributor

@adith-dinesh adith-dinesh commented Jul 22, 2025

Summary by CodeRabbit

  • New Features
    • Added the ability to download contract files directly from SpotDraft using a new tool that accepts a contract identifier and returns the file as a base64-encoded attachment, along with its filename and content type.
  • Improvements
    • Enhanced tool selection and request handling to support contract file downloads.

Copy link

coderabbitai bot commented Jul 22, 2025

Walkthrough

A new tool for downloading contract files from SpotDraft via API v2.1 is introduced. This includes a tool definition, request interface, and handler function. Supporting changes add a downloadFile method to the SpotDraft client, and integrate the new tool into the main tool dispatch and listing logic.

Changes

File(s) Change Summary
src/contract/get_contract_download.ts Added tool, request interface, and async function for contract file download via SpotDraft API.
src/index.ts Imported new tool, interface, and function; integrated tool into tool listing and dispatch logic.
src/spotdraft_client.ts Added downloadFile method to SpotDraftClient for POSTing and retrieving file data.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ToolHandler
    participant SpotDraftClient
    participant SpotDraftAPI

    User->>ToolHandler: Request contract download (composite_id)
    ToolHandler->>SpotDraftClient: downloadFile(endpoint)
    SpotDraftClient->>SpotDraftAPI: POST /v2.1/contracts/{composite_id}/download
    SpotDraftAPI-->>SpotDraftClient: File response (binary, headers)
    SpotDraftClient-->>ToolHandler: { data (base64), filename, contentType }
    ToolHandler-->>User: Return file info (base64, filename, contentType)
Loading

Estimated code review effort

2 (~18 minutes)

Poem

In the warren of code, a new tunnel appears,
For contracts to download, let’s give bunny cheers!
With base64 bundles and headers in tow,
SpotDraft files hop where you want them to go.
A nibble of logic, a byte of delight—
This rabbit delivers your contracts just right!
🐇📄✨

✨ 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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: 1

🧹 Nitpick comments (1)
src/spotdraft_client.ts (1)

66-69: Improve optional chaining for filename extraction.

The filename extraction can be simplified using optional chaining as suggested by the static analysis tool.

-    if (contentDisposition) {
-      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
-      if (filenameMatch && filenameMatch[1]) {
-        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
-      }
-    }
+    if (contentDisposition) {
+      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
+      if (filenameMatch?.[1]) {
+        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
+      }
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d0f266 and 753b376.

📒 Files selected for processing (3)
  • src/contract/get_contract_download.ts (1 hunks)
  • src/index.ts (3 hunks)
  • src/spotdraft_client.ts (1 hunks)
🧬 Code Graph Analysis (2)
src/index.ts (1)
src/contract/get_contract_download.ts (3)
  • getContractDownloadTool (54-54)
  • getContractDownload (54-54)
  • GetContractDownloadRequest (54-54)
src/contract/get_contract_download.ts (1)
src/spotdraft_client.ts (1)
  • SpotDraftClient (1-80)
🪛 Biome (1.9.4)
src/spotdraft_client.ts

[error] 67-67: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🧰 Additional context used
🧬 Code Graph Analysis (2)
src/index.ts (1)
src/contract/get_contract_download.ts (3)
  • getContractDownloadTool (54-54)
  • getContractDownload (54-54)
  • GetContractDownloadRequest (54-54)
src/contract/get_contract_download.ts (1)
src/spotdraft_client.ts (1)
  • SpotDraftClient (1-80)
🪛 Biome (1.9.4)
src/spotdraft_client.ts

[error] 67-67: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (8)
src/spotdraft_client.ts (1)

60-62: Good implementation for binary data handling.

The conversion from ArrayBuffer to base64 using Buffer is appropriate for handling binary file downloads.

src/index.ts (3)

20-24: LGTM - Clean import integration.

The import statements follow the established pattern and are properly structured.


77-77: LGTM - Tool properly added to the registry.

The new tool is correctly added to the tools array following the existing pattern.


128-130: LGTM - Handler case properly implemented.

The switch case follows the established pattern with appropriate type casting and async handling.

src/contract/get_contract_download.ts (4)

4-40: Excellent tool documentation and schema definition.

The tool description is comprehensive and provides clear guidance on:

  • Parameter requirements with examples
  • Response structure explanation
  • Detailed usage instructions for models
  • Security considerations (not attempting to decode binary data)

This level of documentation will help ensure proper usage of the tool.


42-44: Interface definition is clean and appropriate.

The interface correctly defines the required composite_id parameter with proper typing.


46-52: Implementation correctly delegates to the client method.

The function properly constructs the API v2.1 endpoint and delegates to the downloadFile method. The endpoint path follows the expected SpotDraft API pattern.


54-54: All necessary exports are properly defined.

The exports include the function, interface, and tool definition needed for integration.

Comment on lines +52 to +58
async downloadFile(endpoint: string): Promise<{ data: string; filename?: string; contentType?: string }> {
const response = await this.post(endpoint, {});

if (!response.ok) {
const errorBody = await response.text();
throw new Error(`SpotDraft API Error: ${response.status} ${response.statusText} - ${errorBody}`);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical logic error in downloadFile method.

The method calls this.post(endpoint, {}) which returns a parsed JSON response, but then tries to check response.ok on that result. The post() method already handles response validation and returns the parsed response body, not the raw Response object.

 async downloadFile(endpoint: string): Promise<{ data: string; filename?: string; contentType?: string }> {
-   const response = await this.post(endpoint, {});
-
-   if (!response.ok) {
-     const errorBody = await response.text();
-     throw new Error(`SpotDraft API Error: ${response.status} ${response.statusText} - ${errorBody}`);
-   }
+   const response = await fetch(`${this.baseUrl}${endpoint}`, {
+     method: 'POST',
+     headers: this.headers,
+     body: JSON.stringify({}),
+   });
+
+   if (!response.ok) {
+     const errorBody = await response.text();
+     throw new Error(`SpotDraft API Error: ${response.status} ${response.statusText} - ${errorBody}`);
+   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async downloadFile(endpoint: string): Promise<{ data: string; filename?: string; contentType?: string }> {
const response = await this.post(endpoint, {});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`SpotDraft API Error: ${response.status} ${response.statusText} - ${errorBody}`);
}
async downloadFile(endpoint: string): Promise<{ data: string; filename?: string; contentType?: string }> {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({}),
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`SpotDraft API Error: ${response.status} ${response.statusText} - ${errorBody}`);
}
🤖 Prompt for AI Agents
In src/spotdraft_client.ts around lines 52 to 58, the downloadFile method
incorrectly treats the result of this.post(endpoint, {}) as a raw Response
object and checks response.ok, but this.post returns parsed JSON and already
handles response validation. Remove the check for response.ok and the error
handling based on it, and directly use the returned parsed response data as
intended.

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