8000 Fix: default flags field for transaction frozen class should be None · Pull Request #821 · XRPLF/xrpl-py · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix: default flags field for transaction frozen class should be None #821

New issue

Have a question about this project? Sign up for a free GitHub accoun 8000 t 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

Merged
merged 1 commit into from
May 20, 2025

Conversation

ghost
Copy link
@ghost ghost commented Mar 24, 2025

High Level Overview of Change

By default flags field in transaction frozen class should be None rather than 0

Context of Change

When creating transactions using the frozen classes, the flags should not be

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Did you update CHANGELOG.md?

  • Yes
  • No, this change does not impact library users

Test Plan

Current tests

Future Tasks

No future tasks

Copy link
Contributor
coderabbitai bot commented Mar 24, 2025

Walkthrough

The changes update the handling of the flags field in transaction-related classes and tests. The flags attribute now defaults to None instead of 0, and is omitted from serialized output unless explicitly set. Tests and documentation wer 8000 e updated to reflect this behavior, including new test cases for Payment transactions.

Changes

File(s) Change Summary
xrpl/models/transactions/transaction.py Updated flags attribute in Transaction to be optional (None by default), modified serialization logic to exclude flags unless set, improved flag handling methods, and removed a redundant blank line.
xrpl/models/transactions/pseudo_transactions/enable_amendment.py Changed flags attribute in EnableAmendment to be optional, defaulting to None instead of 0.
xrpl/models/transactions/pseudo_transactions/unl_modify.py Updated flags attribute in UNLModify to accept None and other types, defaulting to None instead of 0; updated imports accordingly.
tests/unit/models/test_base_model.py Updated tests to accept None as a valid type for flags, removed "flags": 0 from test data and expected outputs.
tests/unit/models/transactions/test_pseudo_transactions.py Removed "Flags": 0 from expected output dictionaries in pseudo transaction tests.
tests/unit/models/transactions/test_payment.py Added four new tests verifying the presence or absence of the Flags field in Payment transactions depending on how flags is set.
CHANGELOG.md Added an entry describing the fix for default flags handling in transactions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Transaction
    participant Serializer

    User->>Transaction: Create Transaction (flags=None or flags set)
    Transaction->>Serializer: to_dict()
    alt flags is not None
        Serializer->>User: Serialized dict includes Flags
    else flags is None
        Serializer->>User: Serialized dict omits Flags
    end
Loading

Poem

In the fields of code, a change has grown,
Where flags once marched, now some have flown.
If you don’t set a flag, it won’t appear—
The output is tidy, the logic is clear!
With tests updated and bugs all gone,
The rabbit hops forward, code marching on.
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6152f46 and 95d8486.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • tests/unit/models/test_base_model.py (1 hunks)
  • tests/unit/models/transactions/test_payment.py (1 hunks)
  • tests/unit/models/transactions/test_pseudo_transactions.py (4 hunks)
  • xrpl/models/transactions/pseudo_transactions/enable_amendment.py (1 hunks)
  • xrpl/models/transactions/pseudo_transactions/unl_modify.py (2 hunks)
  • xrpl/models/transactions/transaction.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • CHANGELOG.md
  • xrpl/models/transactions/pseudo_transactions/unl_modify.py
  • tests/unit/models/transactions/test_pseudo_transactions.py
  • tests/unit/models/test_base_model.py
  • xrpl/models/transactions/pseudo_transactions/enable_amendment.py
  • xrpl/models/transactions/transaction.py
  • tests/unit/models/transactions/test_payment.py
✨ 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.

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

🔭 Outside diff range comments (2)
xrpl/models/transactions/transaction.py (2)

294-306: ⚠️ Potential issue

Add explicit handling for None in _flags_to_int method

The _flags_to_int method doesn't explicitly handle the case where flags is None. With the default value changing from 0 to None, this could lead to errors when this method is called.

Apply this fix to explicitly handle None:

def _flags_to_int(self: Self) -> int:
+   if self.flags is None:
+       return 0
    if isinstance(self.flags, int):
        return self.flags
    check_false_flag_definition(tx_type=self.transaction_type, tx_flags=self.flags)
    if isinstance(self.flags, dict):
        return self._iter_to_int(
            lst=interface_to_flag_list(
                tx_type=self.transaction_type,
                tx_flags=self.flags,
            )
        )

    return self._iter_to_int(lst=self.flags)

361-385: ⚠️ Potential issue

Add explicit handling for None in has_flag method

The has_flag method raises an exception if flags is not an int, dict, or list. With the default value changing from 0 to None, this would raise an exception when checking flags for transactions with default values.

Apply this fix to explicitly handle None:

def has_flag(self: Self, flag: int) -> bool:
+   if self.flags is None:
+       return False
    if isinstance(self.flags, int):
        return self.flags & flag != 0
    elif isinstance(self.flags, dict):
        return flag in interface_to_flag_list(
            tx_type=self.transaction_type,
            tx_flags=self.flags,
        )
    elif isinstance(self.flags, list):
        return flag in self.flags
    else:
        raise XRPLModelException("self.flags is not an int, dict, or list")
🧹 Nitpick comments (1)
xrpl/models/transactions/transaction.py (1)

1-458: Update documentation for flags behavior change

The change from default value of 0 to None for flags is significant enough to warrant documentation updates, especially since it affects how the absence of flags is represented.

Consider updating the docstring for the flags field to explicitly mention that None represents no flags:

"""
A List of flags, or a bitwise map of flags, modifying this transaction's
behavior. See `Flags Field
<https://xrpl.org/transaction-common-fields.html#flags-field>`_ for more details.
+When None, indicates no flags are set.
"""
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 109c413 and 6f50fe5.

📒 Files selected for processing (1)
  • xrpl/models/transactions/transaction.py (1 hunks)
🔇 Additional comments (1)
xrpl/models/transactions/transaction.py (1)

269-282:

❓ Verification inconclusive

Verify to_dict method behavior with None flags

The to_dict method calls _flags_to_int() which may not handle None properly. It's important to ensure this method works correctly with the new default value.

Let's verify this with a test:


🏁 Script executed:

#!/bin/bash
# Check if there are any tests for to_dict with None flags
rg -A 5 -B 5 "to_dict.*flags.*None" --glob "test_*.py"

# Check existing tests for to_dict method
rg -A 10 -B 10 "def test.*to_dict" --glob "test_*.py"

Length of output: 7923


Action: Verify _flags_to_int behavior when flags is None

It looks like our existing tests cover flag conversion when a list of flags is provided, but there isn’t any test verifying the case where flags might be None. Please confirm that _flags_to_int gracefully handles a None value (for example, by returning 0 or another intended default). If not, consider updating the implementation and adding a corresponding test in tests/unit/models/transactions/test_transaction.py to cover this scenario.

@mvadari
Copy link
Collaborator
mvadari commented Mar 24, 2025

Why do you want them to be None instead of 0? There isn't really any difference in the outcome.

@ghost
Copy link
Author
ghost commented Mar 31, 2025

The main problem happens when trying to "serialise" a transactions

a = Payment(
            account=some_account,
            amount=some_amount,
            destination=some_destination,
            fee=some_fee,
            sequence=some_sequence,
        )
b = a.to_dict()

c = "flags" in transaction_dict # expected: false, actually true

Alternatively to_dict serialisation can be changed. But I think the proposed change matches the docs and python typing better.

@mvadari mvadari requested review from Patel-Raj and Copilot March 31, 2025 16:33
Copy link
@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a bug by updating the default value of the flags field in the transaction frozen class from 0 to None to better reflect the intended behavior.

  • Changed the default value of flags to None
  • Updated the type hint to Optional[...] to accommodate the new default
Comments suppressed due to low confidence (1)

xrpl/models/transactions/transaction.py:203

  • Verify that all transaction logic properly handles a None value for the flags field to avoid potential runtime issues.
flags: Optional[Union[Dict[str, bool], int, List[int]]] = None

@Patel-Raj
Copy link
Patel-Raj commented Apr 7, 2025

@AvbrehtLuka I think using this declaration would be more accurate:
flags: Optional[Union[Dict[str, bool], int, List[int]]] = None

Currently the tests are failing, can you please address the Unit tests, integration tests, and snippet tests after making this change?

@mvadari
Copy link
Collaborator
mvadari commented Apr 7, 2025

Appears to be a problem with a helper function:

File "/home/runner/work/xrpl-py/xrpl-py/xrpl/models/flags.py", line 106, in check_false_flag_definition
    assert all(isinstance(flag, int) for flag in list_flags)
TypeError: 'NoneType' object is not iterable
8000

@ghost
Copy link
Author
ghost commented Apr 9, 2025

Agreed, another option would be to only update the to_dict method to not include flags when none are set, and keep the current typing. What would you prefer?

@mvadari
Copy link
Collaborator
mvadari commented Apr 9, 2025

I would prefer updating the helper function. Less confusing that way IMO.

@Patel-Raj
Copy link

@LukaAvbreht Thanks for proposing the fix. Can you please look into the failing test cases? Thanks!

@LukaAvbreht
Copy link
Contributor

Yes!

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

🧹 Nitpick comments (1)
xrpl/models/flags.py (1)

91-93: Added early return for None flags

This change is critical for the PR's goal - it skips validation when flags is None, allowing transactions to be serialized without the flags field. There's a small typo in the comment "flasgs" instead of "flags", but it doesn't affect functionality.

Fix the typo in the comment:

-            # No flasgs were set, so we can skip the check
+            # No flags were set, so we can skip the check
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4ac81ce and 5f44b98.

📒 Files selected for processing (8)
  • tests/integration/transactions/test_payment.py (0 hunks)
  • tests/unit/core/binarycodec/test_main.py (1 hunks)
  • tests/unit/models/test_base_model.py (1 hunks)
  • tests/unit/models/transactions/test_pseudo_transactions.py (4 hunks)
  • tests/unit/models/transactions/test_transaction.py (1 hunks)
  • tests/unit/models/x-codec-fixtures.json (0 hunks)
  • xrpl/models/flags.py (3 hunks)
  • xrpl/models/transactions/transaction.py (3 hunks)
💤 Files with no reviewable changes (2)
  • tests/unit/models/x-codec-fixtures.json
  • tests/integration/transactions/test_payment.py
✅ Files skipped from review due to trivial changes (1)
  • tests/unit/core/binarycodec/test_main.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • xrpl/models/transactions/transaction.py
🔇 Additional comments (8)
tests/unit/models/transactions/test_transaction.py (1)

76-76: Hash value updated to reflect transaction without Flags field

The hash value is updated due to the removal of the "Flags": 0 entry from the offer_create_dict. This change aligns with the PR's goal of modifying the default flags field from 0 to None, ensuring the serialized transaction doesn't include Flags when not explicitly set.

tests/unit/models/transactions/test_pseudo_transactions.py (4)

37-37: Removed "Flags": 0 from test dictionary

The test has been updated to reflect that pseudo transactions no longer include a default "Flags": 0 entry when serialized, which is consistent with the PR's goal of changing the default flags value from 0 to None.


64-64: Removed "Flags": 0 from SetFee test dictionary

The test for SetFee pseudo transactions has also been updated to remove the default flags field, ensuring consistency with the updated Transaction model behavior.


88-88: Removed "Flags": 0 from post-amendment SetFee test dictionary

The test for post-amendment SetFee pseudo transactions correctly removes the default flags field to align with the updated transaction serialization behavior.


111-111: Removed "Flags": 0 from UNLModify test dictionary

The test for UNLModify pseudo transactions consistently removes the default flags field, ensuring that all test cases reflect the updated Transaction model behavior where flags=None by default.

xrpl/models/flags.py (2)

4-4: Added Optional type for flags

Updated imports to include Optional from typing, which is necessary to support the None value for flags.


77-77: Updated tx_flags type annotation to include None

The type annotation for tx_flags now appropriately includes Optional and expanded the union type to cover int explicitly. This change allows the flags field to be None or a simple integer instead of only supporting dictionaries or lists.

tests/unit/models/test_base_model.py (1)

127-128: Updated error message to include NoneType as valid flags type

The expected error message now correctly includes NoneType in the list of allowed types for the flags field, ensuring that tests won't break due to the added support for None flags.

# if "flags" in prepared_dict:
# del prepared_dict["flags"]
flags = self._flags_to_int()
if self.flags is None or flags == 0:
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: it seems like if self.flags is None, then line 284 flags will evaluate to 0 anyways based on _iter_to_int, so you wouldn't need both of these checks

Copy link
Author

Choose a reason for hiding this comment

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

Agreed, removed the check

flags = self._flags_to_int()
if self.flags is None or flags == 0:
if "flags" in prepared_dict:
del prepared_dict["flags"]
8000 Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: can you add a comment for future reference on why we need to delete flags here and ensure it is None in the returned dict?

Copy link
Author

Choose a reason for hiding this comment

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

Added a comment and a test

@achowdhry-ripple
Copy link
Collaborator

@LukaAvbreht thanks for tackling this issue. Overall LGTM with some minor nits. Pipeline is currently failing due to a typing issue, should be good to go after fixing that

payment_txn = Payment.from_xrpl(payment_tx_json)
payment = payment_txn.to_xrpl()

self.assertTrue("Flags" in payment)
Copy link
Collaborator

Choose a reason for hiding this comment

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

newline at the end of files

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

♻️ Duplicate comments (1)
tests/unit/models/transactions/test_payment.py (1)

248-248: Add newline at end of file.

The file should end with a newline character.

 self.assertTrue("Flags" in payment)

+
🧹 Nitpick comments (1)
CHANGELOG.md (1)

14-14: Fix spelling errors in the changelog entry.

The entry contains several typos:

  • "dafault" should be "default"
  • "bahaviour" should be "behavior"
  • "thransactions" should be "transactions"

Also, you should add a comma after "By default" for better readability.

-Fixed the dafault bahaviour of flags field when preparing thransactions. By default flags are not part of the transaction if not explicitly provided.
+Fixed the default behavior of flags field when preparing transactions. By default, flags are not part of the transaction if not explicitly provided.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~14-~14: You might be missing the article “the” here.
Context: ...client - Fixed the dafault bahaviour of flags field when preparing thransactions. By ...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~14-~14: Did you mean: “By default,”?
Context: ...ags field when preparing thransactions. By default flags are not part of the transaction i...

(BY_DEFAULT_COMMA)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 310717b and 198dc2d.

📒 Files selected for processing (8)
  • CHANGELOG.md (1 hunks)
  • tests/unit/models/test_base_model.py (1 hunks)
  • tests/unit/models/transactions/test_payment.py (1 hunks)
  • tests/unit/models/transactions/test_pseudo_transactions.py (4 hunks)
  • xrpl/models/flags.py (3 hunks)
  • xrpl/models/transactions/pseudo_transactions/enable_amendment.py (1 hunks)
  • xrpl/models/transactions/pseudo_transactions/unl_modify.py (2 hunks)
  • xrpl/models/transactions/transaction.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • xrpl/models/transactions/pseudo_transactions/unl_modify.py
  • tests/unit/models/transactions/test_pseudo_transactions.py
  • xrpl/models/transactions/pseudo_transactions/enable_amendment.py
  • xrpl/models/flags.py
  • tests/unit/models/test_base_model.py
  • xrpl/models/transactions/transaction.py
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[uncategorized] ~14-~14: You might be missing the article “the” here.
Context: ...client - Fixed the dafault bahaviour of flags field when preparing thransactions. By ...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)


[uncategorized] ~14-~14: Did you mean: “By default,”?
Context: ...ags field when preparing thransactions. By default flags are not part of the transaction i...

(BY_DEFAULT_COMMA)

🔇 Additional comments (1)
tests/unit/models/transactions/test_payment.py (1)

193-248: Test coverage looks good!

The added tests thoroughly verify the new behavior of the flags field in Payment transactions:

  1. Test with explicitly set zero flags
  2. Test with direct creation and zero flags
  3. Test with no flags (ensuring they're omitted)
  4. Test with non-zero flags

These tests align perfectly with the PR objective of changing the default flags field from 0 to None.

@ghost ghost force-pushed the main branch 3 times, most recently from ee04e37 to b00b032 Compare May 12, 2025 13:06
@LukaAvbreht
Copy link
Contributor

fixed typos and squashed commits. Please take a look

Copy link
Collaborator
@Patel-Raj11 Patel-Raj11 left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Collaborator
@achowdhry-ripple achowdhry-ripple left a comment

Choose a reason for hiding this comment

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

lgtm

@Patel-Raj11 Patel-Raj11 merged commit ba3cbe5 into XRPLF:main May 20, 2025
22 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jun 5, 2025
9 tasks
LimpidCrypto pushed a commit to LimpidCrypto/xrpl-py that referenced this pull request Jun 7, 2025
…RPLF#821)

fix: default flags field for transaction frozen class should be None

Co-authored-by: Luka Avbreht <l.avbreht@gmail.com>
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.

5 participants
0