andromedaprotocol / andromeda-core

Operating System and ADO Smart Contracts
https://andromedaprotocol.io/
38 stars 27 forks source link

feat: Multiple Rates #517

Open joemonem opened 3 months ago

joemonem commented 3 months ago

Motivation

Allow multiple rates to be set per action.

Implementation

Each action now has a corresponding Vec<Rate> instead of Rate Changes have been made to query_deducted_funds to accommodate multiple rates:

                let mut all_msgs = vec![];
                let mut all_events = vec![];
                let mut all_leftover_funds = vec![];
                for rate in rates {
                    let (mut msgs, mut events, mut leftover_funds) = match rate {
                        Rate::Local(local_rate) => {
                            local_rate.generate_response(deps, coin.clone(), is_native)?
                        }
                        Rate::Contract(rates_address) => {
                            // Query rates contract
                            let addr = rates_address.get_raw_address(&deps)?;
                            let rate = AOSQuerier::get_rate(&deps.querier, &addr, &action)?;
                            rate.generate_response(deps, coin.clone(), is_native)?
                        }
                    };
                    all_msgs.append(&mut msgs);
                    all_events.append(&mut events);
                    all_leftover_funds.append(&mut leftover_funds);
                }
                let total_dedcuted_funds: Uint128 = all_leftover_funds
                    .iter()
                    .map(|x| coin.amount - x.amount)
                    .sum();
                let total_funds = coin.amount.checked_sub(total_dedcuted_funds)?;

Testing

The auction integration test was adjusted to have multiple rates:

vec![
                Rate::Local(LocalRate {
                    rate_type: LocalRateType::Deductive,
                    recipients: vec![
                        Recipient::new(recipient_one, None),
                        Recipient::new(recipient_two, None),
                    ],
                    value: LocalRateValue::Percent(PercentRate {
                        percent: Decimal::percent(25),
                    }),
                    description: None,
                }),
                Rate::Local(LocalRate {
                    rate_type: LocalRateType::Deductive,
                    recipients: vec![
                        Recipient::new(recipient_one, None),
                        Recipient::new(recipient_two, None),
                    ],
                    value: LocalRateValue::Percent(PercentRate {
                        percent: Decimal::percent(10),
                    }),
                    description: None,
                }),
            ]

In that test, the sent funds were 100. Adding the second rate resulted in an additional 10 coins being sent to recipient_one and recipient_two, alongside a decrease of 20 coins to the owner's balance.

Version Changes

No version changes have been made yet. Should the version bump be for all the contracts which use rates or just andromeda-std?

Notes

remove_rates removes the entire vector of rates. If a user wants to modify the rates without removing them all, set_rate can be used since the new rates overwrite the old ones. We should test scenarios like a mix of taxes and royalties, insufficient funds to cover all the taxes, and other possible edge cases. The rates contract still only holds one LocalRate per action, but now multiple rates contracts can be referenced simultaneously.

Summary by CodeRabbit

coderabbitai[bot] commented 3 months ago

Walkthrough

The recent changes enhance the handling of rates across multiple contracts by transitioning from single Rate instances to vectors (Vec<Rate>). This change allows for batch processing of rates, significantly improving flexibility and enabling the management of multiple rates simultaneously. Key updates include modifications to function signatures, message structures, and testing logic, ultimately enriching the contracts' functionality and adaptability in varied scenarios.

Changes

Files Change Summary
contracts/data-storage/.../execute.rs
contracts/data-storage/.../mock.rs
contracts/data-storage/.../testing/tests.rs
Updated to handle multiple rates (Vec<Rate>) instead of a single rate across execution and mocking functions.
contracts/fungible-tokens/.../mock.rs
contracts/fungible-tokens/.../testing/tests.rs
Similar updates for rate handling in execution and test functions, changing parameters to accept vectors.
contracts/non-fungible-tokens/.../mock.rs
contracts/non-fungible-tokens/.../testing/tests.rs
Modified to utilize vectors of rates in mock and test implementations, enhancing rate management.
contracts/non-fungible-tokens/.../marketplace/src/mock.rs
contracts/non-fungible-tokens/.../marketplace/src/testing/tests.rs
Adjusted to support vectors for rates in method signatures and test cases, improving flexibility.
packages/std/src/.../rates.rs
packages/std/src/.../rates.rs
Enum RatesMessage modified to include vectors; functions updated to accommodate multiple rates.
packages/std/src/.../ado_contract/rates.rs ADOContract methods updated to handle collections of rates, improving management and flexibility.
tests-integration/tests/.../auction_app.rs Test updates to include multiple rates, reflecting changes in expected distributions and balances.
tests-integration/tests/.../cw20_app.rs Modified to handle rate vectors in testing, allowing for more flexible rate configurations.
tests-integration/tests/.../marketplace_app.rs Adjustments made to utilize vectors for Rate::Contract in function calls, increasing function flexibility.
tests-integration/tests/.../primitive.rs Changes made to wrap Rate::Local instances in vectors for consistency with new handling logic.
CHANGELOG.md Added entry for "Multiple Rates" associated with pull request #517 to document the new feature.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Contract
    participant MessageHandler
    participant RateProcessor

    User->>Contract: Send RatesMessage(SetRate)
    Contract->>MessageHandler: Process RatesMessage
    MessageHandler->>RateProcessor: Execute with Vec<Rate>
    RateProcessor->>RateProcessor: Validate each Rate
    RateProcessor-->>MessageHandler: Return results
    MessageHandler-->>Contract: Response to User

🐰 Hopping through the fields so bright,
Rates gathered up, what a lovely sight!
From one to many, a grand new way,
Flexibility blooms in the light of day!
Let’s set the rates, let creativity soar,
In our contract garden, there’s always more! 🌼


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 - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `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 generate interesting stats about this repository and render them as a table.` - `@coderabbitai show all the console.log statements in this repository.` - `@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 as 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. Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. ### 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.