Skip to content

feat: Expand Test Coverage for execute_token_transaction#150

Merged
codebestia merged 2 commits intoSpherre-Labs:mainfrom
anihdev:feature/Expand_Test_Coverage_for_execute_token_transaction_142
Jul 28, 2025
Merged

feat: Expand Test Coverage for execute_token_transaction#150
codebestia merged 2 commits intoSpherre-Labs:mainfrom
anihdev:feature/Expand_Test_Coverage_for_execute_token_transaction_142

Conversation

@anihdev
Copy link
Contributor

@anihdev anihdev commented Jul 26, 2025

Description 📝

This PR expands test coverage for execute_token_transaction functionality, adding edge cases and event validation as specified in #142.

Key improvements include:

  • Updated error message for clarity: ERR_INVALID_TOKEN_TRANSACTION to ERR_INVALID_TOKEN_TRANSACTION_TYPE, adjusted all contract references to use new error name.
  • Ensured consistent error handling across components
  • Added comprehensive event validation using assert_emitted
  • Covered all specified edge cases with focused tests

Tests Added

  • test_propose_token_transaction_fail_zero_recipient - Verifies zero recipient address rejection
  • test_execute_token_transaction_fail_non_existent - Tests invalid transaction ID handling
  • test_execute_token_transaction_fail_invalid_type - Ensures only token transactions execute
  • test_execute_token_transaction_fail_insufficient_approvals - Validates threshold enforcement
  • test_execute_token_transaction_fail_unauthorized_executor - Checks executor permissions
  • test_execute_token_transaction_fail_insufficient_balance_at_execution - Tests balance checks
  • test_execute_token_transaction_fail_already_executed - Prevents double execution
  • test_propose_token_transaction_fail_zero_amount - Rejects zero amount transfers
  • test_pause_contract_prevents_execution - Validates pause functionality
  • test_full_token_transaction_lifecycle_with_events - overall flow with event validation
  • test_approve_transaction_event_emission - Verifies approval events
  • test_multiple_approvals_before_execution - Tests multi-sign scenarios

Related Issues 🔗

Fixes #142.

Changes Made 🚀

  • [ ✅] ✨ Feature Implementation
  • [ ✅] 🐛 Bug Fix
  • [ ✅] 📚 Documentation Update
  • [✅ ] 🔨 Refactoring

Checklist ✅

  • [ ✅] 🛠 I have tested these changes.
  • [ ✅] 📖 I have updated the documentation.
  • [ ✅] 🎨 This PR follows the project's coding style.
  • [✅ ] 🧪 I have added necessary tests.

Summary by CodeRabbit

  • Bug Fixes

    • Updated error message for invalid token transactions to provide clearer feedback.
  • Tests

    • Significantly expanded token transaction test coverage, including new scenarios for failure cases, event emissions, permission checks, and contract pause behavior.
    • Added helper functions to streamline test setup and simulate different user roles.
  • Style

    • Added a comment for clarification in an existing test case.
  • Documentation

    • Improved visibility of event fields in transaction-related events for better transparency.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 26, 2025

Walkthrough

The updates make several event structs and their fields explicitly public in core and action modules, update an error message string, and add comprehensive tests for token transaction edge cases and event emissions. Minor documentation changes are also included in a test file, with no impact on logic or control flow outside the expanded test coverage.

Changes

File(s) Change Summary
src/account_data.cairo Made transaction_id and date_approved fields of TransactionApproved event struct explicitly public.
src/actions/token_transaction.cairo Made TokenTransactionProposed and TokenTransactionExecuted event structs and all their fields explicitly public.
src/errors.cairo Updated error message constant value from "Invalid Token Transaction" to "Invalid Token Transaction Type".
src/tests/actions/test_token_transaction.cairo Added extensive new tests and helpers for token transaction edge cases, event emission, and permission scenarios.
src/tests/test_spherre.cairo Added a non-functional comment marker after a test function.

Sequence Diagram(s)

sequenceDiagram
    participant Proposer
    participant Contract
    participant Approver
    participant Executor
    participant Token

    Proposer->>Contract: Propose Token Transaction
    Contract-->>Proposer: Emit TokenTransactionProposed Event

    Approver->>Contract: Approve Transaction
    Contract-->>Approver: Emit TransactionApproved Event

    Executor->>Contract: Execute Transaction
    alt Sufficient approvals & valid conditions
        Contract->>Token: Transfer tokens to recipient
        Token-->>Contract: Transfer confirmation
        Contract-->>Executor: Emit TokenTransactionExecuted & TransactionExecuted Events
    else Failure (e.g. insufficient approvals, invalid type, etc.)
        Contract-->>Executor: Revert with error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • codebestia

Poem

In fields of code, the rabbits leap,
With public structs no longer asleep.
Errors refined, events now sing,
And tests abound for everything!
Approvals, execution, all in view—
This patch brings coverage bright and new.
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 generate unit tests to generate unit tests 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.

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

🧹 Nitpick comments (3)
src/actions/token_transaction.cairo (1)

49-55: Visibility change LGTM – but consider adding additional indexed keys

All struct fields are now declared pub, which solves the test/assert emission requirements. Only id is indexed with #[key]; if consumers routinely filter on token you may want to mark it as a second key to aid event querying, e.g.:

-        pub token: ContractAddress,
+        #[key]
+        pub token: ContractAddress,

Not mandatory, but a cheap win for analytics tooling.

Also applies to: 58-64

src/tests/actions/test_token_transaction.cairo (2)

251-279: Excellent race condition test with a minor typo.

This test cleverly simulates a scenario where balance becomes insufficient between proposal and execution. Great use of the balance_consuming_transaction helper.

Fix the typo in the comment:

-    // Try to execute the original transaction, tiss should panic due to insufficient balance
+    // Try to execute the original transaction, this should panic due to insufficient balance

374-427: Thorough multi-approval scenario test with a typo.

Excellent test coverage for transactions requiring multiple approvals. Good use of the setup_multiple_members helper.

Fix the typo in the comment:

-    // Verify events hould have proposal, 2 approvals, and execution events
+    // Verify events should have proposal, 2 approvals, and execution events
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4e71ac and e1c821e.

📒 Files selected for processing (5)
  • src/account_data.cairo (1 hunks)
  • src/actions/token_transaction.cairo (1 hunks)
  • src/errors.cairo (1 hunks)
  • src/tests/actions/test_token_transaction.cairo (2 hunks)
  • src/tests/test_spherre.cairo (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: codebestia
PR: Spherre-Labs/spherre#0
File: :0-0
Timestamp: 2025-06-10T02:41:14.896Z
Learning: When users request detailed PR descriptions, analyze all modified files comprehensively including implementation files, interfaces, error definitions, tests, and configuration changes to provide complete documentation covering features, security considerations, technical details, and testing coverage.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Run Contract Tests
🔇 Additional comments (12)
src/account_data.cairo (1)

108-110: Event fields correctly made pub

Making transaction_id and date_approved public enables downstream tests and indexers to read them without reflection-style hacks. No functional impact – looks good.

src/tests/test_spherre.cairo (1)

742-742: Comment marker addition acknowledged.

The //@note comment marker has been added after the test function. This change has no functional impact.

src/tests/actions/test_token_transaction.cairo (10)

36-46: LGTM! Clean test helper functions.

The new address helper functions follow the established pattern and provide clear test actor addresses.


49-91: Excellent helper functions for test setup.

The setup_member_with_all_permissions and setup_multiple_members helpers effectively reduce code duplication and provide flexible permission configuration for test scenarios.


94-123: Well-designed test utilities.

The setup_token_and_permissions and balance_consuming_transaction helpers are particularly well-thought-out. The latter provides an elegant way to consume balance for testing insufficient funds scenarios.


127-143: Good edge case coverage for zero recipient validation.

This test properly validates that token transactions with zero recipient addresses are rejected.


148-183: Comprehensive transaction validation tests.

Both tests effectively cover important edge cases:

  • Non-existent transaction IDs are properly rejected
  • Transaction type validation ensures only TOKEN_SEND transactions can be executed via execute_token_transaction

The error message in line 166 correctly uses the updated "Invalid Token Transaction Type" message.


187-216: Proper multi-signature threshold validation.

This test correctly verifies that transactions cannot be executed without meeting the approval threshold requirements.


219-248: Good RBAC enforcement test.

Validates that executor permissions are properly checked, ensuring only authorized members can execute transactions.


283-335: Comprehensive lifecycle test with excellent event validation.

This test thoroughly validates the entire token transaction flow from proposal through execution, with detailed event field verification. Great coverage of the happy path with event emissions.


339-371: Focused approval event test.

Good isolation of approval functionality testing, verifying both event emission and state changes.


431-499: Excellent edge case coverage.

These tests effectively validate critical safety features:

  • Double execution prevention: Ensures executed transactions cannot be re-executed
  • Zero amount validation: Prevents meaningless zero-value transactions
  • Pause functionality: Confirms paused contracts properly block transaction execution

All align perfectly with the PR's objective of comprehensive edge case testing.

pub const ERR_RECIPIENT_CANNOT_BE_ACCOUNT: felt252 = 'Recipient cannot be account';
pub const ERR_INVALID_AMOUNT: felt252 = 'Amount is invalid';
pub const ERR_INVALID_TOKEN_TRANSACTION: felt252 = 'Invalid Token Transaction';
pub const ERR_INVALID_TOKEN_TRANSACTION: felt252 = 'Invalid Token Transaction Type';
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Constant name no longer matches the documented change

ERR_INVALID_TOKEN_TRANSACTION still exists, but its message string has been updated to “Invalid Token Transaction Type”.
According to the PR description the constant itself should have been renamed to ERR_INVALID_TOKEN_TRANSACTION_TYPE. At the moment we have:

  1. ERR_INVALID_TRANSACTION_TYPE (L30) – unrelated.
  2. ERR_INVALID_TOKEN_TRANSACTION (L47) – message now says “… Type”.

This creates two problems:
• Future contributors may confuse the two similarly-worded errors.
• If some call-sites were already migrated to the new identifier the code will fail to compile.

Please verify which identifier is the single source of truth and either:

-    pub const ERR_INVALID_TOKEN_TRANSACTION: felt252 = 'Invalid Token Transaction Type';
+    // Keep the old name as an alias for backwards-compatibility (optional)
+    pub const ERR_INVALID_TOKEN_TRANSACTION_TYPE: felt252 = 'Invalid Token Transaction Type';
+    // Or, if you prefer a clean break, rename the constant everywhere and delete the old one.

Then update all references (rg ERR_INVALID_TOKEN_TRANSACTION / rg ERR_INVALID_TOKEN_TRANSACTION_TYPE) accordingly.


🏁 Script executed:

#!/bin/bash
# Search for all references to the old and new constant names
rg "ERR_INVALID_TOKEN_TRANSACTION" -n .
rg "ERR_INVALID_TOKEN_TRANSACTION_TYPE" -n .

Length of output: 389


Rename ERR_INVALID_TOKEN_TRANSACTION to ERR_INVALID_TOKEN_TRANSACTION_TYPE and update all references

There are still three occurrences of the old constant name in your codebase:

  • src/errors.cairo:47 – declaration
  • src/actions/token_transaction.cairo:118 – call-site
  • src/actions/token_transaction.cairo:191 – call-site

Please apply one of the two strategies consistently:

  1. Clean break – rename everywhere:

    --- a/src/errors.cairo
    +++ b/src/errors.cairo
    @@ -47,1 +47,1 @@
  • pub const ERR_INVALID_TOKEN_TRANSACTION: felt252 = 'Invalid Token Transaction Type';
  • pub const ERR_INVALID_TOKEN_TRANSACTION_TYPE: felt252 = 'Invalid Token Transaction Type';
    
    ```diff
    --- a/src/actions/token_transaction.cairo
    +++ b/src/actions/token_transaction.cairo
    @@ -118,1 +118,1 @@
    
  •            Errors::ERR_INVALID_TOKEN_TRANSACTION,
    
  •            Errors::ERR_INVALID_TOKEN_TRANSACTION_TYPE,
    
    @@ -191,1 +191,1 @@
  •            Errors::ERR_INVALID_TOKEN_TRANSACTION,
    
  •            Errors::ERR_INVALID_TOKEN_TRANSACTION_TYPE,
    
    
    
  1. Backward-compatible alias – introduce the new name and keep the old one as an alias:

    --- a/src/errors.cairo
    +++ b/src/errors.cairo
    @@ -46,0 +46,2 @@
  • pub const ERR_INVALID_TOKEN_TRANSACTION_TYPE: felt252 = 'Invalid Token Transaction Type';
  • pub const ERR_INVALID_TOKEN_TRANSACTION: felt252 = ERR_INVALID_TOKEN_TRANSACTION_TYPE; // alias
    
    Then update call-sites to use `ERR_INVALID_TOKEN_TRANSACTION_TYPE` or keep them pointing at the alias.
    
    

Ensure you choose one approach and update all three references accordingly so the code compiles and future contributors aren’t confused.

📝 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
pub const ERR_INVALID_TOKEN_TRANSACTION: felt252 = 'Invalid Token Transaction Type';
pub const ERR_INVALID_TOKEN_TRANSACTION_TYPE: felt252 = 'Invalid Token Transaction Type';
🤖 Prompt for AI Agents
In src/errors.cairo at line 47, rename the constant
ERR_INVALID_TOKEN_TRANSACTION to ERR_INVALID_TOKEN_TRANSACTION_TYPE. Then,
update all references to this constant in src/actions/token_transaction.cairo at
lines 118 and 191 to use the new name. Choose either to rename all occurrences
directly or create an alias for backward compatibility, but ensure consistency
across all three locations to avoid compilation errors and confusion.

@codebestia codebestia changed the title feat: /Expanded_Test_Coverage_for_execute_token_transaction_142 feat: Expand_Test_Coverage_for_execute_token_transaction_142 Jul 28, 2025
@codebestia codebestia changed the title feat: Expand_Test_Coverage_for_execute_token_transaction_142 feat: Expand Test Coverage for execute_token_transaction Jul 28, 2025
Copy link
Member

@codebestia codebestia left a comment

Choose a reason for hiding this comment

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

LGTM!
Thank you for your contribution.

@codebestia codebestia merged commit 206da9b into Spherre-Labs:main Jul 28, 2025
3 checks passed
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.

[TEST] Expand Test Coverage for execute_token_transaction

2 participants