Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove index signature from base request #2923

Open
wants to merge 14 commits into
base: main
Choose a base branch
from

Conversation

interc0der
Copy link
Contributor

High Level Overview of Change

  • Removed the index signature (e.g., [key: string]: any) from the base request method's TypeScript interface in the XRPL.js library.
  • Updated all downstream instances where the index signature was previously used for accessing properties dynamically (e.g., replaced with explicit property definitions or more specific types).
  • This change improves type safety and enhances compatibility with TypeScript utility types like Omit<> and Partial<>, making it easier for third-party developers to extend or manipulate the request type in their own projects.

Context of Change

  • Previously, the request method likely used an index signature to allow arbitrary key-value pairs, which provided flexibility but sacrificed type safety and discoverability. For example, a definition like interface Request { [key: string]: any } would allow any string key with any value, making it harder for developers to catch errors at compile time and limiting the utility of TypeScript’s tooling (e.g., autocompletion, refactoring).
  • This change is a refactor with bug-fix-like benefits: it eliminates the overly permissive index signature, replacing it with a more explicit structure (e.g., specific fields like method: string, params?: object). This aligns with TypeScript best practices, as index signatures should only be used when the keys are truly dynamic and unknown ahead of time.
  • The motivation stems from enhancing portability and usability for third-party developers. With a precise interface, developers can now leverage utility types (e.g., Omit<Request, 'params'> or Partial<Request>) to customize the request type without running into issues caused by the loose index signature.
  • No specific bug is being fixed (i.e., no prior crash or runtime error), but this prevents potential type-related issues in downstream usage. The change likely emerged from feedback or observed friction in third-party integrations with the library.
  • Alternatives considered might have included keeping the index signature with a more constrained value type (e.g., [key: string]: string | number), but removing it entirely was chosen to enforce stricter typing and better align with the library’s intended usage patterns.
  • No design document is referenced, but this aligns with broader TypeScript ecosystem trends toward stricter, more explicit type definitions.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
    (Prevents potential type misuse, though not tied to a specific runtime bug.)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
    (Assumed non-breaking since existing valid usage should still work with explicit types.)
  • Refactor (non-breaking change that only restructures code)
    (Primary intent is to improve type structure, making this a refactor as well.)
  • Tests (You added tests for code that already exists, or your new feature included in this PR)
  • Documentation Updates
  • Release

Did you update HISTORY.md?

  • Yes
  • No, this change does not impact library users
    (The change is internal to the type system and transparent to end users interacting with the library’s runtime behavior. It mainly benefits developers working with the typings, so no user-facing HISTORY.md update is needed.)

Test Plan

  • No specific unit tests were added for this change, as it is a type-level refactor that does not alter runtime behavior. The TypeScript compiler itself enforces the correctness of the updated typings during the build process.
  • Validation was performed by publishing a modified build to npm and testing it in a production-like environment. The updated package is available here: https://www.npmjs.com/package/@interc0der/xrpl.
  • Existing tests (if any) should still pass, assuming they were written to align with the request method’s intended usage. If the library has a CI pipeline, it likely caught any downstream type errors introduced by this change.

Copy link

coderabbitai bot commented Mar 9, 2025

Walkthrough

This pull request enhances error handling in the Client class's request method by checking for the existence of the account property before verifying its type, reducing the risk of runtime errors. Additionally, the index signature in the BaseRequest interface was removed to enforce a stricter structure. No alterations were made to exported or public entities.

Changes

File(s) Change Summary
packages/xrpl/src/client/index.ts Updated the condition in the Client class's request method: now checks for "account" in req before type-checking to prevent runtime errors.
packages/xrpl/src/models/methods/baseMethod.ts Removed the [x: string]: unknown index signature from the BaseRequest interface, restricting objects to explicitly defined properties only.

Poem

I’m a rabbit hopping through the code night,
Skipping bugs with careful checks so bright.
In client files, I watch each property’s dance,
While strict types in BaseRequest enhance.
Hoppy changes bring a joyful byte,
🐇✨ coding under the moonlight!

✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

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: 0

🧹 Nitpick comments (1)
packages/xrpl/src/client/index.ts (1)

346-346: Good defensive programming improvement.

This change improves code safety by first checking if the account property exists in the request object before checking its type. This pattern prevents potential TypeErrors when the property doesn't exist, especially important after removing the index signature from the BaseRequest interface (as mentioned in the PR objectives).

The code now properly handles the case where a request doesn't include an account property, ensuring more robust error handling.

According to the ESLint configuration, you should use single quotes instead of double quotes:

-        "account" in req && typeof req.account === 'string'
+        'account' in req && typeof req.account === 'string'
🧰 Tools
🪛 ESLint

[error] 346-346: Replace "account" with 'account'

(prettier/prettier)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8995e3d and 1271c37.

📒 Files selected for processing (2)
  • packages/xrpl/src/client/index.ts (1 hunks)
  • packages/xrpl/src/models/methods/baseMethod.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/xrpl/src/models/methods/baseMethod.ts
🧰 Additional context used
🪛 ESLint
packages/xrpl/src/client/index.ts

[error] 346-346: Replace "account" with 'account'

(prettier/prettier)

@mvadari
Copy link
Collaborator

mvadari commented Mar 12, 2025

I'm a bit confused as to what problem this is solving... Can you provide an example?

@interc0der
Copy link
Contributor Author

Here is a quick and dirty example: https://github.com/interc0der/xrpl-example

import type * as xrpl from 'xrpl'

// Type is not restructured correctly on the AccountChannelsParams
// due to the signature indexing on the base request method
export type AccountChannelsParams = Omit<xrpl.AccountChannelsRequest, 'command'>;

@ckeshava
Copy link
Collaborator

@interc0der I'm able to run the below snippet without the typescript compiler throwing any warnings (or) errors. It looks like type manipulation is possible in the current version of the code. What exactly is missing?

import { AccountChannelsRequest } from '../../src/models/methods/accountChannels'

type AccountChannelsMinusCommand = Omit<AccountChannelsRequest, 'command'>
type AccountChannelsOnlyCommand = Pick<AccountChannelsRequest, 'command'>

const accountChannels: AccountChannelsMinusCommand = {
  account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
  limit: 10,
  ledger_index: 'validated',
}

const command: AccountChannelsOnlyCommand = {
  command: 'account_channels',
}

console.log(accountChannels)
console.log(typeof accountChannels)
console.log(command)
console.log(typeof command)

I get the below output:
image

@interc0der
Copy link
Contributor Author

interc0der commented Mar 12, 2025

Pick<> type utility is fine and will work despite the signature index.
Omit<> type utility is the one that is the problem. While this is not breaking the ts compiler, you are losing type safety.

Screenshot 2025-03-12 at 4 13 11 PM

@ckeshava
Copy link
Collaborator

Omit<> type utility is the one that is the problem. While this is not breaking the ts compiler, you are losing type safety.

Okay, I found this snippet which is problematic.

import { AccountChannelsRequest } from '../../src/models/methods/accountChannels'

type AccountChannelsMinusCommand = Omit<AccountChannelsRequest, 'command'>

const accountChannels: AccountChannelsMinusCommand = {
  account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
  limit: 10,
  ledger_index: 'validated',
  // compiler does not throw an error here
  command: 'account_channels',
}

console.log(accountChannels)

@ckeshava
Copy link
Collaborator

@interc0der can you add some unit tests which prove the correctness of the Omit<> types with your code changes?

@interc0der
Copy link
Contributor Author

interc0der commented Mar 14, 2025

@ckeshava Unit testing for type utilities has been added within the models test directory. We are checking a few models.

It should be noted that Chai / Jest unit testing is not designed to pick up non-runtime issues.

Copy link
Collaborator

@ckeshava ckeshava left a comment

Choose a reason for hiding this comment

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

Some of the tests use the subcommand key in the Request input. I suspect the original design wanted to accomodate these liberties. Here is an example: https://github.com/XRPLF/xrpl.js/actions/runs/13847785489/job/38914627395?pr=2923#step:9:72

Would you be willing to fix these discrepancies?

Thanks for bringing this to our attention. How did you come across this type-check requirement? What are you using xrpl.js for?

Comment on lines +56 to +57
assertType<true>({} as HasCommand)
assertType<true>({} as HasNoCommand)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't understand the intent of these two tests. Are you testing that the empty type {} is compatible with both HasCommand and HasNoCommand? How is this useful?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Well, without an additional dependency, its kind tough the check correct type assertions that are not caught during runtime. Index signature removes type-checking of foreign keys and is not caught during runtime. Trying to write unit tests that are runtime-based is quite difficult for this scenerio.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Hmm, I understand. I see the value of the rest of the tests. I didn't understand the need for these two lines only.

@interc0der
Copy link
Contributor Author

interc0der commented Mar 24, 2025

The integration testing leverages index signatures in a few cases to iterate through typed keys and assert types. This can be easily fixed by add the type signatures where required, locally.

Testing has been cleaned of type errors and the path finding request has been typed with a required subcommand. See here for ref: https://github.com/XRPLF/rippled/blob/67028d6ea609b7ed41666f8c4d96680e292f0865/src/xrpld/rpc/handlers/PathFind.cpp#L40https://github.com/XRPLF/rippled/blob/67028d6ea609b7ed41666f8c4d96680e292f0865/src/xrpld/rpc/handlers/PathFind.cpp#L40


For anyone that is facing a similar issue as documented in this issue (the rare few), here is a workaround type hack to extract the index signature from any type interface.

type RemoveIndexSignature<T, TPropKey = PropertyKey> = {
  [K in keyof T as TPropKey extends K ? never : K extends TPropKey ? K : never]: T[K];
};

You can then use the Omit<> and the type structure is as expected.

export type AccountChannelsParams = Omit<
  RemoveIndexSignature<methods.AccountChannelsRequest>,
  'command'
>;

@interc0der interc0der closed this Mar 24, 2025
@interc0der interc0der reopened this Mar 24, 2025
Copy link
Collaborator

@ckeshava ckeshava left a comment

Choose a reason for hiding this comment

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

Hello! thanks for your work. I have a few comments regarding the linter and one test case.

I have incorporated my suggestions into this commit: 193490b. Feel free to use it.

@@ -135,10 +135,12 @@ describe('server_state', function () {
key,
) {
assert.equal(
// @ts-expect-error -- non-iterative type
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why do we need all these declarations?

import type { BaseRequest } from '../../src/models'

// Helper type assertion function (only for TS, no runtime impact)
function assertType<T>(value: T): void {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Since value is unused, we could perhaps use _ ?

const validated_ledger = response.result.info.validated_ledger
assert.equal(typeof validated_ledger?.hash, 'string')
for (const key of Object.keys(omit(validated_ledger, 'hash'))) {
// @ts-expect-error -- non-iterative type
Copy link
Collaborator

Choose a reason for hiding this comment

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

This type of @ts-expect-error statements can be removed.

'string',
)
const state_accounting: StateAccountingFinal & {
[index: string]: unknown
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why do we need this catch-all type here? I have found that we can iterate over the keys without using this additional key-value pair.

@@ -55,6 +55,8 @@ describe('ledger', function () {
assert.typeOf(ledgerResponse.result.ledger_index, 'number')

const ledger = ledgerResponse.result.ledger as Ledger & {
// Add index signature to request to iterate through keys and asset types
[index: string]: unknown
Copy link
Collaborator

Choose a reason for hiding this comment

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

Similar to my comments in other test files, I don't see the need for this additional kv pair

@ckeshava
Copy link
Collaborator

@interc0der Clarification: Are you trying to remove the [x: string]: unknown key-value pair from the BaseRequest ? I'm looking at the work-around that you suggested here:

type RemoveIndexSignature<T, TPropKey = PropertyKey> = {
  [K in keyof T as TPropKey extends K ? never : K extends TPropKey ? K : never]: T[K];
};

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.

3 participants