Skip to content

chore: add smaller fixes#21

Merged
gorgos merged 1 commit into
masterfrom
chore/smaller-fixes
Aug 22, 2025
Merged

chore: add smaller fixes#21
gorgos merged 1 commit into
masterfrom
chore/smaller-fixes

Conversation

@gorgos

@gorgos gorgos commented Aug 21, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • None
  • Bug Fixes

    • Corrected refund computation for exact-output swaps to return the precise unused input.
    • Improved simulation of buy-from-source estimates to reduce false “amount too high” errors.
    • Standardized contract name handling during migration to avoid mismatched identifiers.
  • Tests

    • Enabled previously skipped migration test and aligned artifacts.
  • Chores

    • Bumped package version to 1.1.1.

@coderabbitai

coderabbitai Bot commented Aug 21, 2025

Copy link
Copy Markdown

Walkthrough

Version bumped to 1.1.1. Migration code now uses plain contract name without crates.io prefix. Simulation margin in estimate_execution_buy_from_source uses input_quote_quantity. ExactOutputQuantity refund uses required_input. Tests updated: migration test runs unconditionally with artifact/name adjustments; an integration test expectation is corrected.

Changes

Cohort / File(s) Summary
Version bump
contracts/swap/Cargo.toml
Package version updated from 1.1.0 to 1.1.1; no other manifest changes.
Migration naming + tests
contracts/swap/src/contract.rs, contracts/swap/src/testing/migration_test.rs
Migration now expects/stores plain contract name (no crates.io: prefix). Migration test unignored; wasm path updated to swap_contract-v101.wasm; variable renamed to swap_v111_code_id and assertions updated.
Simulation margin tweak
contracts/swap/src/queries.rs
In estimate_execution_buy_from_source (simulation mode), funds_for_margin uses funds_in_contract + input_quote_quantity instead of + available_swap_quote_funds.
Refund calculation (ExactOutputQuantity)
contracts/swap/src/swap.rs
start_swap_flow: refund now computed as provided - required_input (previously used estimation.result_quantity).
Test expectation adjust
contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs
Updated expected USDT post-swap balance from 96201.062128 to 96201.062127 and comment aligned.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant S as Swap Contract
  participant M as Market(s)

  rect rgba(230,245,255,0.5)
    note right of S: ExactOutputQuantity flow (changed refund)
    U->>S: Execute swap (ExactOutput, coin_provided)
    S->>M: Route swap to obtain exact output
    M-->>S: Reports required_input for target output
    S->>S: current_balance = required_input
    S->>U: Refund = coin_provided - required_input
    S-->>U: Success response incl. refund (if any)
  end
Loading
sequenceDiagram
  autonumber
  participant Q as Query Client
  participant S as Swap Contract

  rect rgba(240,255,240,0.6)
    note right of S: Simulation margin uses input_quote_quantity
    Q->>S: estimate_execution_buy_from_source(is_simulation=true, input_quote_quantity)
    S->>S: funds_for_margin = funds_in_contract + input_quote_quantity
    S-->>Q: Estimation result (using updated margin)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

Hop hop! New tag, 1.1.1 gleams,
Names unmasked, sans prefix dreams.
Sim swaps add what users bring,
Refunds now match the needed thing.
Tests awake, a digit’s nudge—
Onward I bound, no bugs to fudge! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/smaller-fixes

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
contracts/swap/src/contract.rs (1)

121-129: Migration should accept both legacy and new cw2 contract names.

If older deployments stored cw2 name as "crates.io:swap-contract", the current match only on "swap-contract" will hard-fail migrations. Support both to avoid bricking upgrades.

Apply:

-    match contract_version.contract.as_ref() {
-        "swap-contract" => match contract_version.version.as_ref() {
+    match contract_version.contract.as_ref() {
+        "swap-contract" | "crates.io:swap-contract" => match contract_version.version.as_ref() {
             "1.0.1" => {
-                set_contract_version(deps.storage, CONTRACT_NAME.to_string(), CONTRACT_VERSION)?;
+                set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
             }
             _ => return Err(ContractError::MigrationError {}),
         },
         _ => return Err(ContractError::MigrationError {}),
     }
🧹 Nitpick comments (7)
contracts/swap/src/swap.rs (1)

91-97: Double-check Coin::new accepts the FPDecimal-derived refund_amount.

refund is constructed via Coin::new(refund_amount, ...), where refund_amount is FPDecimal. If Coin::new expects an integer (Uint128/u128) in your cosmwasm_std version, this won’t compile or may require explicit conversion (e.g., refund_amount.int() or Into). If this compiled before, ignore; otherwise, make the conversion explicit for clarity.

Example tweak (only if needed):

-        refund: Coin::new(refund_amount, source_denom.to_owned()),
+        refund: Coin::new(refund_amount.int().try_into().unwrap(), source_denom.to_owned()),
contracts/swap/src/testing/migration_test.rs (2)

21-21: Artifact path rename: verify file exists in CI.

Path switched to swap_contract-v101.wasm (underscore). Ensure the artifact is checked in at ../../contracts/swap/src/testing/test_artifacts/ with the new name, or the test will panic on read().


94-96: Optional: assert cw2 version post-migration via contract query.

You already assert the code_id updated. Add a quick GetConfig query to assert the contract_version equals "1.1.1" to catch accidental version drift.

Example snippet (add after Line 96):

let cfg: crate::types::ConfigResponse = wasm
    .query(&swap_v101_address, &crate::msg::QueryMsg::GetConfig {})
    .unwrap();
assert_eq!(cfg.contract_version, "1.1.1");
contracts/swap/src/queries.rs (4)

161-167: Use rounded result_quantity for margin check to avoid overly conservative rejections

required_funds is computed using expected_base_quantity before rounding to the market’s min tick. This can overshoot and cause unnecessary simulation failures. Consider basing the margin check on the actual order size (result_quantity) that would be placed after tick rounding.

Apply this minimal change:

-    let expected_base_quantity = available_swap_quote_funds / average_price;
-    let result_quantity = round_to_min_tick(expected_base_quantity, market.min_quantity_tick_size);
+    let expected_base_quantity = available_swap_quote_funds / average_price;
+    let result_quantity = round_to_min_tick(expected_base_quantity, market.min_quantity_tick_size);

     let fee_estimate = input_quote_quantity - available_swap_quote_funds;

     // check if user funds + contract funds are enough to create order
-    let required_funds = worst_price * expected_base_quantity * (FPDecimal::ONE + fee_percent);
+    let required_funds = worst_price * result_quantity * (FPDecimal::ONE + fee_percent);

This mirrors the target-path behavior where you first round the base quantity, then validate funds against that rounded size.


167-173: Avoid panics in queries: replace expect with error propagation

Using expect("query own balance should not fail") will abort execution on transient node issues. Since the function already returns StdResult, propagate the error instead. Same pattern exists in the target-path function.

Apply these diffs in both places:

-    let funds_in_contract = deps
-        .querier
-        .query_balance(contract_address, &market.quote_denom)
-        .expect("query own balance should not fail")
-        .amount
-        .into();
+    let funds_in_contract: FPDecimal = deps
+        .querier
+        .query_balance(contract_address, &market.quote_denom)?
+        .amount
+        .into();

This keeps the contract fail-safe without panicking on external query hiccups.

Also applies to: 228-234


376-383: Prefer slices over &Vec<T> in function signatures

Accepting &[PriceLevel] is more idiomatic and flexible than &Vec<PriceLevel>; it also avoids unnecessary constraints on callers.

-pub fn get_minimum_liquidity_levels(
-    _deps: &Deps<InjectiveQueryWrapper>,
-    levels: &Vec<PriceLevel>,
+pub fn get_minimum_liquidity_levels(
+    _deps: &Deps<InjectiveQueryWrapper>,
+    levels: &[PriceLevel],

No call-site changes needed due to Deref coercions.


451-568: Add a unit test to lock in the new simulation behavior (fees counted in available funds)

Recommend a focused test that would have failed before this change (non-zero fee, small contract balance), and now passes.

Here’s a sketch you can adapt within your existing test module:

#[test]
fn test_buy_from_source_simulation_uses_full_input_for_margin() {
    // Arrange: market with non-zero fee, small contract balance,
    // and orderbook such that worst_price > average_price.
    // Create deps/env, mock market, and orderbook levels so that:
    // - input_quote_quantity is just enough when fees are included
    // - using only available_swap_quote_funds would fail the margin check.
    // Assert: estimate_execution_buy_from_source(...) returns Ok(..)
    // after this change, whereas previous logic would have Err(..).
}

If useful, I can draft a full test using your inj mocks and helpers.

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 89f870b and 18cbb78.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • contracts/swap/src/testing/test_artifacts/swap_contract-v101.wasm is excluded by !**/*.wasm
📒 Files selected for processing (6)
  • contracts/swap/Cargo.toml (1 hunks)
  • contracts/swap/src/contract.rs (2 hunks)
  • contracts/swap/src/queries.rs (1 hunks)
  • contracts/swap/src/swap.rs (1 hunks)
  • contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (1 hunks)
  • contracts/swap/src/testing/migration_test.rs (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (1)
contracts/swap/src/testing/test_utils.rs (1)
  • human_to_dec (801-803)
⏰ 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). (4)
  • GitHub Check: Lints
  • GitHub Check: Unit Tests
  • GitHub Check: Lints
  • GitHub Check: Unit Tests
🔇 Additional comments (7)
contracts/swap/src/swap.rs (1)

63-87: Fix uses required_input for refund — this is the right invariant.

Using required_input rather than estimation.result_quantity ensures the refund excludes any rounding-up needed for tick sizes/quote-int casting, preventing over-refunds and underfunded executions. CurrentBalance is also aligned to required_input, which keeps subsequent step estimation consistent.

contracts/swap/src/contract.rs (1)

131-136: Good: expose new name/version via attributes.

new_contract_name and new_contract_version attributes reflect the post-migration cw2 state and help observability.

contracts/swap/src/testing/migration_test.rs (1)

68-69: store_code name alignment looks consistent with artifact rename.

Passing "swap_contract" to store_code aligns with the new underscore artifact naming convention; nice.

contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (1)

801-804: Expectation tweak by 1 micro-unit is fine and likely driven by rounding changes.

The USDT post-swap expectation from 96201.062128 to 96201.062127 matches the refund/round-up correction. Comment updated accordingly — good.

contracts/swap/Cargo.toml (1)

5-5: Version bump to 1.1.1 acknowledged.

Ensure you tag the release and update any downstream deployment scripts referencing the artifact name change (underscore) to keep CI/CD green.

contracts/swap/src/queries.rs (2)

174-177: Simulation margin now adds full user input (incl. fees) — correct and consistent with target-path logic

Switching from adding available_swap_quote_funds to input_quote_quantity in simulation makes the margin check reflect the actual funds the user will provide with the tx (principal + fees). This prevents false “Swap amount too high” errors when fees are non-zero and aligns with estimate_execution_buy_from_target which already uses funds_in_contract + required_input_quote_quantity. Looks good.


235-238: Symmetry check — good

The target-path simulation already adds required_input_quote_quantity to contract funds, which is the full amount the user must provide. Your source-path change restores symmetry between the two paths. No action needed.

Comment on lines +124 to 125
set_contract_version(deps.storage, CONTRACT_NAME.to_string(), CONTRACT_VERSION)?;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Compile error: passing String to set_contract_version.

set_contract_version expects &str params; CONTRACT_NAME.to_string() passes String by value and won’t compile. Use the &'static str directly.

Apply:

-                set_contract_version(deps.storage, CONTRACT_NAME.to_string(), CONTRACT_VERSION)?;
+                set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
📝 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
set_contract_version(deps.storage, CONTRACT_NAME.to_string(), CONTRACT_VERSION)?;
}
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
}
🤖 Prompt for AI Agents
In contracts/swap/src/contract.rs around lines 124-125, the call to
set_contract_version passes CONTRACT_NAME.to_string() (a String) but
set_contract_version expects &str; remove the .to_string() and pass the string
constants directly (e.g., CONTRACT_NAME and CONTRACT_VERSION as &str / &'static
str) so the function receives &str parameters.

@jbernal87 jbernal87 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM check unit tests

@gorgos gorgos merged commit a2e5c52 into master Aug 22, 2025
6 of 7 checks passed
@gorgos gorgos deleted the chore/smaller-fixes branch August 22, 2025 09:35
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