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

Added Discarded state to cf contract #715

Merged
merged 10 commits into from
Dec 11, 2024
Merged

Added Discarded state to cf contract #715

merged 10 commits into from
Dec 11, 2024

Conversation

DimitrijeDragasevic
Copy link
Contributor

@DimitrijeDragasevic DimitrijeDragasevic commented Dec 10, 2024

Motivation

Wanted to have an DISCARDED state in the contract, makes is more beautiful :)

Implementation

Just added one more state

Testing

Tests are added as well

Version Changes

idk how to do this

Notes

So as my learning process for the contract side in Andromeda, i was experimenting and wanted to tryout this change.
Please feedback is much appreciated :)

Summary by CodeRabbit

  • New Features

    • Introduced a new function to discard campaigns by the owner.
    • Added a new campaign stage for discarded campaigns.
  • Bug Fixes

    • Enhanced error handling for campaign operations to ensure proper validation.
  • Tests

    • Added new test cases for the discard campaign functionality.
    • Refactored existing tests for ending campaigns to improve clarity and separation of logic.
    • Updated integration tests to reflect changes in campaign lifecycle behavior.
  • Chores

    • Updated package version to 2.1.5-beta.
    • Updated CHANGELOG.md to reflect new features and fixes.

Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Warning

Rate limit exceeded

@DimitrijeDragasevic has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 51 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8c659c5 and 42402e9.

📒 Files selected for processing (1)
  • CHANGELOG.md (2 hunks)

Walkthrough

The changes in this pull request enhance the Andromeda Crowdfund contract by introducing a new function, execute_discard_campaign, which allows the owner to discard a campaign in specific states. The execute_end_campaign function has been refactored to simplify its parameters and logic, focusing solely on ending campaigns. Additionally, new error variants have been added to improve error handling, and the test suite has been updated to reflect these changes, ensuring robust validation of campaign management functionalities.

Changes

File Change Summary
contracts/non-fungible-tokens/andromeda-crowdfund/src/contract.rs - Added function: execute_discard_campaign for discarding campaigns.
- Refactored execute_end_campaign to remove is_discard parameter and simplify logic.
contracts/non-fungible-tokens/andromeda-crowdfund/src/testing/tests.rs - Added tests for DiscardCampaign functionality.
- Refactored tests for ending campaigns to remove is_discard logic.
packages/andromeda-non-fungible-tokens/src/crowdfund.rs - Added enum variant: DISCARDED to CampaignStage.
- Updated to_string method to handle DISCARDED state.
packages/std/src/error.rs - Added error variants: InvalidCampaignOperation and InvalidClaim to ContractError.
tests-integration/tests/crowdfund_app.rs - Added test function: test_crowdfund_app_native_discard for testing discard behavior with invalid withdrawal recipients.
- Modified existing discard test logic.
contracts/non-fungible-tokens/andromeda-crowdfund/Cargo.toml - Updated package version from 2.1.4-beta to 2.1.5-beta.
CHANGELOG.md - Updated to reflect notable changes, including new features and fixes across various components.

Possibly related PRs

Suggested labels

backport/v1.1.x, ci: skip-changelog

Suggested reviewers

  • joemonem
  • crnbarr93

🐇 In the land of code where campaigns thrive,
A new way to discard helps them survive.
With functions refined and errors in line,
The contract now dances, oh how it shines!
So let’s hop with joy, for changes are here,
In the world of Andromeda, let’s give a cheer! 🎉


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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: 0

🧹 Outside diff range and nitpick comments (1)
contracts/non-fungible-tokens/andromeda-crowdfund/src/testing/tests.rs (1)

1208-1216: Updated test case name for clarity

Renaming the test case to "Cannot end non-expired campaign" improves readability and accurately reflects the behavior being tested.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e2348ec and f580c0a.

📒 Files selected for processing (4)
  • contracts/non-fungible-tokens/andromeda-crowdfund/src/contract.rs (3 hunks)
  • contracts/non-fungible-tokens/andromeda-crowdfund/src/testing/tests.rs (4 hunks)
  • packages/andromeda-non-fungible-tokens/src/crowdfund.rs (2 hunks)
  • packages/std/src/error.rs (1 hunks)
🔇 Additional comments (8)
contracts/non-fungible-tokens/andromeda-crowdfund/src/contract.rs (3)

144-145: New ExecuteMsg variants handled appropriately

The inclusion of ExecuteMsg::EndCampaign and ExecuteMsg::DiscardCampaign in the match statement ensures that these new actions are correctly routed to their respective execution functions.


373-405: Correct implementation of execute_discard_campaign function

The execute_discard_campaign function appropriately checks for ownership, ensures the campaign is in the correct stage (READY or ONGOING), and updates the campaign state to DISCARDED. This aligns with the intended functionality.


Line range hint 408-473: Refactored execute_end_campaign simplifies logic

Removing the is_discard parameter from execute_end_campaign simplifies the function signature. The decision logic for determining the final campaign stage based on capital and expiration is correctly implemented.

contracts/non-fungible-tokens/andromeda-crowdfund/src/testing/tests.rs (2)

1290-1300: Addition of DiscardCampaign struct for testing

The DiscardCampaign struct is well-defined to parameterize test cases for the execute_discard_campaign function, improving test scalability and readability.


1302-1405: Comprehensive tests for execute_discard_campaign

The test_execute_discard_campaign function adds valuable test coverage for the discard campaign operation, including scenarios for successful discards, unauthorized attempts, and invalid campaign states.

packages/andromeda-non-fungible-tokens/src/crowdfund.rs (2)

121-122: Addition of DISCARDED variant to CampaignStage enum

The new DISCARDED variant extends the CampaignStage enum to represent discarded campaigns, enhancing the state management of campaigns.


133-133: Updated to_string method for CampaignStage

Including the DISCARDED variant in the to_string method ensures accurate string representation of the new campaign state.

packages/std/src/error.rs (1)

75-78: Enhanced error handling with new ContractError variants

The addition of InvalidCampaignOperation and InvalidClaim to the ContractError enum improves error specificity for campaign and staking operations, facilitating better error reporting and handling.

@joemonem
Copy link
Contributor

Crowdfund integration test needs to be updated.
You can update version in the Cargo.toml file in the andromeda-crowdfund folder under contracts

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

🧹 Outside diff range and nitpick comments (1)
tests-integration/tests/crowdfund_app.rs (1)

410-410: Consider adding more assertions for edge cases.

While the basic flow is well tested, consider adding assertions for:

  • Attempting to discard an already discarded campaign
  • Attempting to discard a campaign in SUCCESS/FAILED states
  • Attempting to discard by non-owner

Also applies to: 412-421

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f580c0a and 03f213d.

📒 Files selected for processing (2)
  • contracts/non-fungible-tokens/andromeda-crowdfund/src/contract.rs (4 hunks)
  • tests-integration/tests/crowdfund_app.rs (2 hunks)
🔇 Additional comments (5)
tests-integration/tests/crowdfund_app.rs (1)

Line range hint 337-405: LGTM! The test case thoroughly validates the discard functionality.

The test case effectively covers:

  • Campaign state transitions
  • Balance changes during purchase and refund
  • Proper refund handling after discard
contracts/non-fungible-tokens/andromeda-crowdfund/src/contract.rs (4)

373-405: LGTM! The discard campaign implementation is well-structured.

The function correctly:

  • Validates permissions
  • Checks valid states
  • Updates campaign state

Line range hint 408-473: LGTM! The end campaign refactor improves clarity.

The refactored function:

  • Simplifies state transition logic
  • Properly handles campaign completion conditions
  • Maintains withdrawal functionality for successful campaigns

635-635: LGTM! Claim handling properly includes discarded state.

The change correctly handles refunds for discarded campaigns similar to failed campaigns.


373-405: Verify fund handling security in discard flow.

While the implementation looks secure, let's verify:

  1. No funds can be locked in the contract
  2. All purchases are refundable after discard
  3. State transitions are atomic

Also applies to: 635-635

✅ Verification successful

From analyzing the code and execution results, I can now provide a definitive response about the security of the discard flow:

Fund handling in discard flow is secure

The implementation ensures:

  1. Proper state transition validation - only ONGOING or READY states can be discarded
  2. Owner-only access control through is_contract_owner check
  3. Funds are refundable after discard - verified through handle_failed_claim being called for DISCARDED state
  4. State transitions are atomic through single storage operation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify fund handling in discard flow

# Check for potential fund locking conditions
rg -A 5 "fn execute_claim.*CampaignStage::DISCARDED"

# Check for proper error handling in state transitions
rg -A 5 "fn execute_discard_campaign.*ContractError"

# Check for proper permission validation
rg -A 5 "is_contract_owner.*execute_discard_campaign"

Length of output: 749


Script:

#!/bin/bash
# Let's verify the fund handling and state transitions more thoroughly

# Check how claims are handled in different states
rg -A 10 "fn execute_claim"

# Check if there's a refund mechanism
rg -A 10 "fn execute_refund"

# Check state transition validations
rg -A 5 "CampaignStage::"

# Check purchase handling
rg -A 10 "fn execute_purchase"

# Look for fund transfer implementations
rg -A 10 "fn transfer_funds"

Length of output: 71300

@DimitrijeDragasevic
Copy link
Contributor Author

Crowdfund integration test needs to be updated. You can update version in the Cargo.toml file in the andromeda-crowdfund folder under contracts

thank you ser

@joemonem
Copy link
Contributor

I think this update is worth a changelog entry

@DimitrijeDragasevic
Copy link
Contributor Author

I think this update is worth a changelog entry

why ser, its a small change, just added one more state, no need for change log. Code is almost the same just one more state

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 and nitpick comments (2)
tests-integration/tests/crowdfund_app.rs (2)

409-409: Add test documentation and verify campaign end failure.

Consider adding a test comment explaining why an invalid recipient message is used, and verify that the campaign cannot be ended before discarding. This helps document the test's purpose and validates the discard state's necessity.

+    // Verify that campaign cannot be ended with invalid recipient
+    let end_result = crowdfund.execute_end_campaign(owner.clone(), &mut router);
+    assert!(end_result.is_err());
     assert_eq!(summary.current_stage, CampaignStage::DISCARDED.to_string());

Line range hint 411-424: Enhance refund verification test coverage.

Consider adding:

  1. A comment explaining the refund calculation
  2. Verification that subsequent claims after refund fail
     // Verify refunds after discard
+    // Expected refund: (10 tiers * 100 tokens) + (10 tiers * 200 tokens) = 3000 tokens
     let buyer_one_original_balance = router
         .wrap()
         .query_balance(buyer_one.clone(), "uandr")
         .unwrap()
         .amount;
     let _ = crowdfund
         .execute_claim(buyer_one.clone(), &mut router)
         .unwrap();
     let buyer_one_balance = router
         .wrap()
         .query_balance(buyer_one.clone(), "uandr")
         .unwrap()
         .amount;
     assert_eq!(
         buyer_one_balance,
         buyer_one_original_balance + Uint128::new(10 * 100 + 200 * 10)
     );
+    
+    // Verify subsequent claims fail
+    let claim_result = crowdfund.execute_claim(buyer_one.clone(), &mut router);
+    assert!(claim_result.is_err(), "Subsequent claims should fail");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ec0c28a and 3eaa3b2.

📒 Files selected for processing (1)
  • tests-integration/tests/crowdfund_app.rs (1 hunks)

Comment on lines +409 to +411
assert_eq!(summary.current_stage, CampaignStage::DISCARDED.to_string());

// Refund
// Verify refunds after discard
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add assertions for campaign capital and recipient balance.

Consider adding assertions to verify:

  1. The campaign's capital remains unchanged after discard
  2. The withdrawal recipient hasn't received any funds
     assert_eq!(summary.current_stage, CampaignStage::DISCARDED.to_string());
+    assert_eq!(summary.current_capital, 10 * 100 + 200 * 10, "Capital should remain unchanged");
+    
+    // Verify withdrawal recipient hasn't received funds
+    let recipient_balance = router
+        .wrap()
+        .query_balance(recipient.address, "uandr")
+        .unwrap()
+        .amount;
+    assert_eq!(recipient_balance, Uint128::zero(), "Recipient should not receive funds");

     // Verify refunds after discard

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

@joemonem
Copy link
Contributor

I think this update is worth a changelog entry

why ser, its a small change, just added one more state, no need for change log. Code is almost the same just one more state

I think it's because it involves a schema change in CampaignStage.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3eaa3b2 and bc1ad86.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
🧰 Additional context used
🪛 Markdownlint (0.35.0)
CHANGELOG.md

68-68: null
Bare URL used

(MD034, no-bare-urls)

CHANGELOG.md Outdated
@@ -65,6 +65,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added BuyNow option for Auction [(#533)](https://github.com/andromedaprotocol/andromeda-core/pull/533)
- Include ADOBase Version in Schema [(#574)](https://github.com/andromedaprotocol/andromeda-core/pull/574)
- Added multi-hop support for IBC [(#604)](https://github.com/andromedaprotocol/andromeda-core/pull/604)
- Crowdfund, added additional state: https://github.com/andromedaprotocol/andromeda-core/pull/715
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve the changelog entry format and description.

The current entry needs to be more descriptive and follow the project's changelog formatting conventions. The bare URL should be replaced with proper markdown link formatting, and the description should clearly specify the added state.

Replace the current line with:

-Crowdfund, added additional state: https://github.com/andromedaprotocol/andromeda-core/pull/715
+- Added DISCARDED state to Crowdfund contract to enhance campaign lifecycle management [(#715)](https://github.com/andromedaprotocol/andromeda-core/pull/715)

This change:

  1. Follows the project's established format for PR references
  2. Clearly specifies what state was added
  3. Provides context about the purpose of the change
📝 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
- Crowdfund, added additional state: https://github.com/andromedaprotocol/andromeda-core/pull/715
- Added DISCARDED state to Crowdfund contract to enhance campaign lifecycle management [(#715)](https://github.com/andromedaprotocol/andromeda-core/pull/715)
🧰 Tools
🪛 Markdownlint (0.35.0)

68-68: null
Bare URL used

(MD034, no-bare-urls)

@DimitrijeDragasevic DimitrijeDragasevic merged commit ea483f1 into main Dec 11, 2024
11 checks passed
@DimitrijeDragasevic DimitrijeDragasevic deleted the cfRework branch December 11, 2024 13:53
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