Skip to content

fix(platform): paying for a document action with tokens where tokens would be transferred to yourself as contract owner was breaking #2633

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

Merged
merged 1 commit into from
May 23, 2025

Conversation

QuantumExplorer
Copy link
Member

@QuantumExplorer QuantumExplorer commented May 23, 2025

Issue being fixed or feature implemented

Paying for a document action with tokens where tokens would be transferred to yourself as contract owner was breaking.

What was done?

Updated document action transitions to check if the owner is the same as the sender before performing a token transfer. If they are the same, the transfer operation is skipped, but the document is still made.

How Has This Been Tested?

Added tests to ensure that token transfers are not executed when the sender and recipient are the same.

Breaking Changes

None

Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • New Features

    • Introduced a new test to verify correct handling when tokens are transferred to oneself during document creation, ensuring balances remain unchanged in this scenario.
  • Bug Fixes

    • Prevented unnecessary token transfer operations when the document owner and contract owner are the same, avoiding redundant balance changes across document creation, deletion, purchase, replacement, transfer, and price update actions.
    • Improved error reporting for unbalanced token states after block execution, providing clearer feedback related to token balance issues.
  • Tests

    • Enhanced test coverage for token balance validation in document creation scenarios, including cases involving token burns and self-transfers.

Copy link
Contributor

coderabbitai bot commented May 23, 2025

Walkthrough

The changes introduce a new CorruptedTokensNotBalanced error variant for token balance inconsistencies and update related error handling. Conditional logic is added to prevent redundant token transfer operations when the owner and contract owner are the same. Additional tests validate token balance consistency, including a new scenario for self-payment with tokens.

Changes

File(s) Change Summary
packages/rs-drive-abci/src/error/execution.rs Added CorruptedTokensNotBalanced(String) variant to ExecutionError enum for token balance errors.
packages/rs-drive-abci/src/execution/platform_events/tokens/validate_token_aggregated_balance/v0/mod.rs Updated error variant and message from credits to tokens for balance validation errors.
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/creation.rs Added calls to token balance validation in tests and introduced a new test for self-payment with tokens.
packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_create_transition.rs
document_delete_transition.rs
document_purchase_transition.rs
document_replace_transition.rs
document_transfer_transition.rs
document_update_price_transition.rs
Added conditional checks to only push token transfer operations if owner and contract owner differ, preventing redundant transfers.

Sequence Diagram(s)

sequenceDiagram
    participant Owner
    participant ContractOwner
    participant System

    Owner->>System: Initiate document transition (create, delete, etc.)
    alt Owner != ContractOwner
        System->>ContractOwner: Push TokenTransfer operation
    else Owner == ContractOwner
        System-->>System: Skip TokenTransfer operation
    end
    System->>System: Validate token aggregated balance
    System-->>Owner: Return result or error (CorruptedTokensNotBalanced)
Loading

Poem

In the ledger’s warren, tokens hop with glee,
No more self-gifting, as wise as can be!
Errors now named for tokens, not credits past,
And tests ensure the balances last.
With careful checks, the code’s more neat—
Every bunny’s balance stays complete!
🐇💰

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

@QuantumExplorer QuantumExplorer added this to the v2.0.0 milestone May 23, 2025
@QuantumExplorer QuantumExplorer changed the title fix(drive): prevent token transfer to self during document actions fix(platform): paying for a document action with tokens where tokens would be transferred to yourself as contract owner was breaking May 23, 2025
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)
packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_replace_transition.rs (1)

74-82: LGTM! Consistent pattern implementation across all document operations.

The conditional check correctly prevents self-transfers during document replacement operations. The implementation maintains the established pattern across all document transition types, which ensures consistent behavior and excellent code maintainability.

Optional suggestion for future consideration: Since this exact pattern is repeated across multiple document transition files, consider extracting it into a helper function to reduce code duplication and ensure consistency. This could be addressed in a future refactoring effort.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a86708f and cc481a2.

📒 Files selected for processing (9)
  • packages/rs-drive-abci/src/error/execution.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/platform_events/tokens/validate_token_aggregated_balance/v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/creation.rs (3 hunks)
  • packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_create_transition.rs (1 hunks)
  • packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_delete_transition.rs (1 hunks)
  • packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_purchase_transition.rs (1 hunks)
  • packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_replace_transition.rs (1 hunks)
  • packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_transfer_transition.rs (1 hunks)
  • packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_update_price_transition.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: QuantumExplorer
PR: dashpay/platform#2257
File: packages/rs-drive-abci/src/mimic/test_quorum.rs:159-164
Timestamp: 2024-11-20T16:16:01.830Z
Learning: QuantumExplorer prefers not to receive auto-generated messages asking to post on social media.
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Rust packages (dash-sdk) / Check each feature
  • GitHub Check: Rust packages (dash-sdk) / Tests
  • GitHub Check: Rust packages (dash-sdk) / Unused dependencies
  • GitHub Check: Rust packages (dash-sdk) / Linting
  • GitHub Check: Rust packages (drive-abci) / Tests
  • GitHub Check: Rust packages (drive-abci) / Check each feature
  • GitHub Check: Rust packages (drive) / Linting
  • GitHub Check: Rust packages (drive) / Tests
  • GitHub Check: Rust packages (drive-abci) / Linting
  • GitHub Check: Rust packages (drive-abci) / Formatting
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
🔇 Additional comments (10)
packages/rs-drive-abci/src/error/execution.rs (1)

103-105: Well-implemented error variant addition.

The new CorruptedTokensNotBalanced variant follows the established patterns and naming conventions. It properly separates token balance errors from credit balance errors, improving error specificity.

packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_delete_transition.rs (1)

64-72: Effective prevention of redundant self-transfers.

The conditional check correctly prevents token transfer operations when the owner and contract owner are identical. This optimization avoids unnecessary operations while maintaining the existing behavior for legitimate transfers.

packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_purchase_transition.rs (1)

87-95: Consistent implementation of self-transfer prevention.

The conditional logic matches the pattern established in other document action files, ensuring consistent behavior across all document transitions. The implementation correctly prevents redundant token transfers while preserving legitimate transfer operations.

packages/rs-drive-abci/src/execution/platform_events/tokens/validate_token_aggregated_balance/v0/mod.rs (1)

24-25: Proper alignment with new token error variant.

The error type change from CorruptedCreditsNotBalanced to CorruptedTokensNotBalanced correctly utilizes the new error variant and provides more accurate error context by referencing "tokens" instead of "credits" in the message.

packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_update_price_transition.rs (1)

69-77: LGTM! Excellent optimization to prevent redundant self-transfers.

The conditional check correctly prevents unnecessary token transfer operations when the document owner and contract owner are the same entity. This optimization improves performance while maintaining logical correctness, as transferring tokens to oneself would be a no-op operation.

packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_transfer_transition.rs (1)

76-84: LGTM! Consistent implementation of self-transfer prevention.

The implementation follows the same pattern established in other document transition files, correctly preventing redundant token transfers when the owner and contract owner are identical. The consistency across all document operation types is excellent for maintainability.

packages/rs-drive/src/state_transition_action/action_convert_to_operations/batch/document/document_create_transition.rs (1)

73-81: LGTM! Correct implementation with minor style variation.

The conditional check correctly prevents self-transfers during document creation. Note that the contract owner is accessed inline (contract_fetch_info.contract.owner_id()) rather than being stored in a variable like in other files, but this is functionally equivalent and doesn't impact correctness.

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/creation.rs (3)

678-680: LGTM! Token balance validation enhances test robustness.

The addition of token balance validation after state transition processing is a good practice that ensures token consistency before committing the transaction.


823-825: LGTM! Consistent validation pattern applied.

The token balance validation is consistently applied across different token operation scenarios, which is good for comprehensive testing.


861-2989: LGTM! Essential test coverage for self-payment scenario.

This new test effectively validates the core PR objective - preventing redundant token transfers when the sender and recipient are the same entity. The test correctly verifies that the contract owner's token balance remains unchanged (15 tokens) when paying themselves for document creation, demonstrating that no actual transfer occurs in this scenario.

Key strengths:

  • Comprehensive test setup following established patterns
  • Proper assertion that token balance remains unchanged (assert_eq!(token_balance, Some(15)))
  • Includes token balance validation for consistency checks
  • Covers the edge case mentioned in the PR objectives

Copy link
Member Author

@QuantumExplorer QuantumExplorer left a comment

Choose a reason for hiding this comment

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

Self Reviewed

@QuantumExplorer QuantumExplorer merged commit eacc5f8 into v2.0-dev May 23, 2025
72 of 73 checks passed
@QuantumExplorer QuantumExplorer deleted the fixdrive-token-transfer-to-self branch May 23, 2025 17:33
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