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

Autofill function in Client not validating DeliverMax and Amount correctly #2857

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

JordiParraCrespo
Copy link

Autofill function in Client not validating DeliverMax and Amount correctly

Fixes an issue where the autofill function throws an error when passing amounts as objects.

Context of Change

In JavaScript, objects are compared by reference, not by their property values. Here's an example to illustrate this behavior:

const a = {
  currency: 'USD',
  value: '31415',
  issuer: 'r9vbV3EHvXWjSkeQ6CAcYVPGeq7TuiXY2X',
};

const b = {
  currency: 'USD',
  value: '31415',
  issuer: 'r9vbV3EHvXWjSkeQ6CAcYVPGeq7TuiXY2X',
};

console.log(a === b); // Output: false

Because objects are compared by reference, even identical objects like a and b are considered different. This was causing incorrect validation in the autofill function when dealing with amounts represented as objects.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Refactor (non-breaking change that only restructures code)
  • 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

Test Plan

I have added tests to verify that the bug is resolved.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces several enhancements to the XRPL JavaScript library, focusing on improving transaction handling and validation. The changes include adding new utility functions like areAmountsEqual and parseTransactionFlags, updating the autofill method to perform more robust amount validation, and introducing support for MPT transaction definitions. The modifications aim to enhance the library's functionality by providing more precise amount comparison, better transaction flag parsing, and improved error handling.

Changes

File Change Summary
packages/xrpl/src/models/transactions/common.ts Added areAmountsEqual utility function to compare amounts with validation
packages/xrpl/src/client/index.ts Updated autofill method to use areAmountsEqual for comparing Amount and DeliverMax fields
packages/xrpl/test/client/autofill.test.ts Added new test cases for autofill method with object-based amount comparisons
packages/xrpl/HISTORY.md Documented new utility functions, MPT transaction support, and validation improvements

Possibly related PRs

Suggested reviewers

  • justinr1234
  • khancode
  • pdp2121

Poem

🐰 Hop, hop, through the code we go,
Amounts compared with precision's glow
Flags parsed, transactions refined
XRPL's magic, cleverly designed!
A rabbit's leap of coding delight 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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: 1

🧹 Nitpick comments (2)
packages/xrpl/test/client/autofill.test.ts (1)

Line range hint 102-143: Add test cases for additional amount comparison scenarios

While the current test coverage is good, consider adding these scenarios:

  1. Mixed type comparison (string vs object)
  2. MPT amount comparison

Here are the additional test cases to add:

it('Validate Payment transaction API v2: Payment Transaction: differing DeliverMax and Amount fields using mixed types', async function () {
  // @ts-expect-error -- DeliverMax is a non-protocol, RPC level field in Payment transactions
  paymentTx.DeliverMax = '1000'
  paymentTx.Amount = {
    currency: 'USD',
    value: '1000',
    issuer: 'r9vbV3EHvXWjSkeQ6CAcYVPGeq7TuiXY2X',
  }

  await assertRejects(testContext.client.autofill(paymentTx), ValidationError)
})

it('Validate Payment transaction API v2: Payment Transaction: identical DeliverMax and Amount fields using MPT amounts', async function () {
  // @ts-expect-error -- DeliverMax is a non-protocol, RPC level field in Payment transactions
  paymentTx.DeliverMax = {
    value: '1000',
    mpt_issuance_id: 'abc123'
  }
  paymentTx.Amount = {
    value: '1000',
    mpt_issuance_id: 'abc123'
  }

  const txResult = await testContext.client.autofill(paymentTx)
  assert.strictEqual('DeliverMax' in txResult, false)
})
packages/xrpl/HISTORY.md (1)

Line range hint 1-24: Improve consistency in changelog entry formatting

For better traceability and documentation, consider:

  1. Adding a link to the PR/commit that fixed the amount validation issue
  2. Maintaining consistent formatting with other entries that include links
  3. Following the established pattern of categorizing changes under "Fixed" or "Bug fixes" sections
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 303c2b9 and e7d6001.

📒 Files selected for processing (4)
  • packages/xrpl/HISTORY.md (1 hunks)
  • packages/xrpl/src/client/index.ts (2 hunks)
  • packages/xrpl/src/models/transactions/common.ts (2 hunks)
  • packages/xrpl/test/client/autofill.test.ts (3 hunks)
🔇 Additional comments (2)
packages/xrpl/src/client/index.ts (1)

703-703: LGTM! Improved validation logic

The change correctly replaces the direct comparison with the new areAmountsEqual function, improving the robustness of amount validation.

packages/xrpl/HISTORY.md (1)

17-17: Verify that the changelog entry matches the PR objectives

The changelog entry "autofill function in client not validating amounts correctly" aligns with the PR objectives which describe a bug fix for amount validation in the Client's autofill function. However, for better clarity and traceability, consider expanding the entry to explicitly mention:

  1. The specific fields affected (DeliverMax and Amount)
  2. The root cause (JavaScript object comparison behavior)

Comment on lines +172 to +201
/**
* Check if two amounts are equal.
*
* @param amount1 - The first amount to compare.
* @param amount2 - The second amount to compare.
* @returns Whether the two amounts are equal.
* @throws When the amounts are not valid.
*/
export function areAmountsEqual(amount1: unknown, amount2: unknown): boolean {
const isAmount1Invalid = !isAmount(amount1)
if (isAmount1Invalid || !isAmount(amount2)) {
throw new ValidationError(
`Amount: invalid field. Expected Amount but received ${JSON.stringify(
isAmount1Invalid ? amount1 : amount2,
)}`,
)
}

if (isString(amount1) && isString(amount2)) {
return new BigNumber(amount1).eq(amount2)
}

if (isRecord(amount1) && isRecord(amount2)) {
return Object.entries(amount1).every(
([key, value]) => amount2[key] === value,
)
}

return false
}
Copy link

@coderabbitai coderabbitai bot Dec 19, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance amount comparison logic for better type safety and edge cases

The areAmountsEqual function has a few areas that could be improved:

  1. The object comparison is shallow and may miss nested differences
  2. Type narrowing is not leveraged after isRecord check
  3. Mixed type comparisons (string vs object) are not explicitly handled

Consider this improved implementation:

 export function areAmountsEqual(amount1: unknown, amount2: unknown): boolean {
   const isAmount1Invalid = !isAmount(amount1)
   if (isAmount1Invalid || !isAmount(amount2)) {
     throw new ValidationError(
       `Amount: invalid field. Expected Amount but received ${JSON.stringify(
         isAmount1Invalid ? amount1 : amount2,
       )}`,
     )
   }

   if (isString(amount1) && isString(amount2)) {
     return new BigNumber(amount1).eq(amount2)
   }

-  if (isRecord(amount1) && isRecord(amount2)) {
-    return Object.entries(amount1).every(
-      ([key, value]) => amount2[key] === value,
-    )
+  if (isIssuedCurrency(amount1) && isIssuedCurrency(amount2)) {
+    return (
+      amount1.currency === amount2.currency &&
+      amount1.issuer === amount2.issuer &&
+      new BigNumber(amount1.value).eq(amount2.value)
+    )
+  }
+
+  if (isMPTAmount(amount1) && isMPTAmount(amount2)) {
+    return (
+      amount1.mpt_issuance_id === amount2.mpt_issuance_id &&
+      new BigNumber(amount1.value).eq(amount2.value)
+    )
   }

   return false
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Collaborator

Choose a reason for hiding this comment

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

This appears to be a reasonable suggestion. Can it be incorporated into the PR?

Copy link

Choose a reason for hiding this comment

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

@ckeshava Sure! Below is an example of how you could update the areAmountsEqual function to incorporate the improved checks:

export function areAmountsEqual(amount1: unknown, amount2: unknown): boolean {
  const isAmount1Invalid = !isAmount(amount1)
  if (isAmount1Invalid || !isAmount(amount2)) {
    throw new ValidationError(
      `Amount: invalid field. Expected Amount but received ${JSON.stringify(
        isAmount1Invalid ? amount1 : amount2,
      )}`,
    )
  }

  if (isString(amount1) && isString(amount2)) {
    return new BigNumber(amount1).eq(amount2)
  }

  if (isIssuedCurrency(amount1) && isIssuedCurrency(amount2)) {
    return (
      amount1.currency === amount2.currency &&
      amount1.issuer === amount2.issuer &&
      new BigNumber(amount1.value).eq(amount2.value)
    )
  }

  if (isMPTAmount(amount1) && isMPTAmount(amount2)) {
    return (
      amount1.mpt_issuance_id === amount2.mpt_issuance_id &&
      new BigNumber(amount1.value).eq(amount2.value)
    )
  }

  return false
}

This approach adds clearer checks for each amount variant and leverages BigNumber for numeric comparisons. Let me know if you need anything else!

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.

I don't understand what is the bug in the existing codebase.

I have incorporated the identical Amount and DeliverMax field test case into the main branch of the code base. However, I did not get any errors.

The test where Amount and DeliverMax differ will throw a ValidationError. What is the need for your changes?

Comment on lines +172 to +201
/**
* Check if two amounts are equal.
*
* @param amount1 - The first amount to compare.
* @param amount2 - The second amount to compare.
* @returns Whether the two amounts are equal.
* @throws When the amounts are not valid.
*/
export function areAmountsEqual(amount1: unknown, amount2: unknown): boolean {
const isAmount1Invalid = !isAmount(amount1)
if (isAmount1Invalid || !isAmount(amount2)) {
throw new ValidationError(
`Amount: invalid field. Expected Amount but received ${JSON.stringify(
isAmount1Invalid ? amount1 : amount2,
)}`,
)
}

if (isString(amount1) && isString(amount2)) {
return new BigNumber(amount1).eq(amount2)
}

if (isRecord(amount1) && isRecord(amount2)) {
return Object.entries(amount1).every(
([key, value]) => amount2[key] === value,
)
}

return false
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This appears to be a reasonable suggestion. Can it be incorporated into the PR?

@@ -98,6 +99,25 @@ describe('client.autofill', function () {
assert.strictEqual('DeliverMax' in txResult, false)
})

it('Validate Payment transaction API v2: Payment Transaction: differing DeliverMax and Amount fields using amount objects', async function () {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
it('Validate Payment transaction API v2: Payment Transaction: differing DeliverMax and Amount fields using amount objects', async function () {
it('Validate Payment transaction API v2: Payment Transaction: identical DeliverMax and Amount fields using amount objects', async function () {

@ckeshava
Copy link
Collaborator

ckeshava commented Jan 2, 2025

@JordiParraCrespo Here is my branch with the concerned test case: https://github.com/XRPLF/xrpl.js/compare/main...ckeshava:xrpl.js:IssuedAmountPaymentTest?expand=1

Let me know what I'm missing

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.

2 participants