Skip to content

chore: update to latest chain#20

Merged
jbernal87 merged 5 commits into
masterfrom
chore/upgrade-to-last-chain
Jun 13, 2025
Merged

chore: update to latest chain#20
jbernal87 merged 5 commits into
masterfrom
chore/upgrade-to-last-chain

Conversation

@gorgos

@gorgos gorgos commented Jun 11, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Bug Fixes

    • Corrected a typo in variable naming within swap order response handling.
  • Chores

    • Upgraded dependency versions for improved stability and compatibility.
    • Updated CI/CD workflow actions to newer versions.
    • Enhanced the release build script for more efficient contract builds.
    • Refactored import statements across multiple modules and tests for improved code clarity.
  • Tests

    • Improved test setup for account and token initialization with precise decimal handling.
    • Refined test helpers for more accurate and flexible market and account configuration.
    • Standardized test account initialization using validator context and explicit denomination handling.
  • New Features

    • Added advanced helper functions for custom spot market launches and account initialization with decimal-aware funds.

@coderabbitai

coderabbitai Bot commented Jun 11, 2025

Copy link
Copy Markdown

Walkthrough

This update revises dependencies, CI workflow action versions, and the build script. It introduces enhanced test utilities for account and market initialization with decimal handling, updates test code to use these utilities, and fixes a minor typo. The workflow and build process are streamlined, and several dependencies are upgraded.

Changes

File(s) Change Summary
.github/workflows/rust.yaml Upgraded GitHub Actions versions for cache and Pages-related steps.
Cargo.toml Updated versions for several dependencies, including injective-* crates and prost.
build_release.sh Updated Docker image version and simplified build loop to a single container run.
contracts/swap/src/swap.rs Fixed typo in variable name from first_messsage to first_message.
contracts/swap/src/testing/authz_tests.rs Enhanced test with validator account setup and explicit token denomination/decimals registration.
contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs,
contracts/swap/src/testing/integration_realistic_tests_min_quantity.rs,
contracts/swap/src/testing/migration_test.rs
Switched test account/coin initialization to new decimal-aware helpers and included validator context.
contracts/swap/src/testing/test_utils.rs Added functions/structs for decimal-aware account and market initialization; improved spot market launch logic.
contracts/swap/src/admin.rs Consolidated multiple crate imports into a single grouped import statement.
contracts/swap/src/testing/config_tests.rs Consolidated multiple crate imports into a single grouped import statement.
contracts/swap/src/testing/queries_tests.rs Reorganized and grouped imports for clarity and conciseness.
contracts/swap/src/testing/storage_tests.rs Consolidated multiple crate imports into a single grouped import statement.
contracts/swap/src/testing/swap_tests.rs Grouped crate imports into a single block; separated external imports for clarity.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Function
    participant Utils as test_utils.rs
    participant App as InjectiveTestApp
    participant Validator as SigningAccount
    participant Exchange as Exchange

    Test->>Utils: must_init_account_with_funds_and_setting_denoms(App, Validator, [InitialCoin])
    Utils->>App: Ensure account has INJ balance
    Utils->>App: Initialize account with decimals
    Utils->>App: Send INJ from account to Validator
    Utils->>Exchange: Register denoms and decimals
    Utils-->>Test: Return SigningAccount

    Test->>Utils: launch_spot_market_custom(Exchange, Validator, ...)
    Utils->>Exchange: MsgInstantSpotMarketLaunch with custom decimals
    Exchange-->>Utils: Market ID
    Utils-->>Test: Market ID
Loading

Poem

🐰
In the warren of code, we hop and we leap,
Upgrading our crates while the CI does sweep.
Decimal precision now shines in our den,
With spot markets launched again and again.
From typo to testing, the changes are neat—
A carrot for progress, a patchwork complete!
🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

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

@gorgos gorgos marked this pull request as ready for review June 13, 2025 09:04
@gorgos gorgos force-pushed the chore/upgrade-to-last-chain branch from 46cfa58 to 5e7170a Compare June 13, 2025 09:09

@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: 3

🔭 Outside diff range comments (1)
.github/workflows/rust.yaml (1)

29-44: 🛠️ Refactor suggestion

Actions rev bump looks good – but actions/checkout is still on v2

While caches were updated to actions/cache@v4, actions/checkout (line 30) remains on v2, which reached EOL and doesn’t support the Node 20 runner image that @v4 cache now requires.
Recommend bumping to actions/checkout@v4 in the same commit to avoid future deprecation warnings.

-      - name: Checkout sources
-        uses: actions/checkout@v2
+      - name: Checkout sources
+        uses: actions/checkout@v4
🧰 Tools
🪛 actionlint (1.7.7)

30-30: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


33-33: the runner of "actions-rs/toolchain@v1" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

♻️ Duplicate comments (1)
contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (1)

70-74: Same validator-funding concern as noted earlier

The validator is brought up with 1.2f64 INJ and is later used by must_init_account_with_funds_and_setting_denoms, triggering the same potential overdraft described for migration_test.rs.
Please apply the fix uniformly across all test suites.

🧹 Nitpick comments (8)
.github/workflows/rust.yaml (1)

41-44: Add explicit save-cache key for cargo registry

actions/cache@v4 no longer infers the save behaviour when a step fails.
If you rely on cache writes even on successful jobs only, add save-if: ${{ success() }}.
Otherwise you may notice reduced cache hit rates.

with:
  path: |
    ~/.cargo/…
  key: 
  restore-keys: 
  save-if: ${{ success() }}

Also applies to: 105-108

build_release.sh (1)

8-12: Single-shot build may omit per-crate optimisations

The refactor from looping through contracts/* to building "./" greatly simplifies the script, but results in:

  1. Every crate in the workspace being built, including dev-only helpers.
  2. A heavier Docker image pulled on every run (0.16.1, nice!) with no layer cache across crates.

If the intent was to ship only contract WASMs, consider adding --package swap-contract (and others) to keep build time low, or restore the loop with the new optimiser tag.

No action needed if the broader build is intentional.

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

15-17: Unused imports hint at missed assertions

Bank, send, and add_denom_notional_and_decimal are imported separately from both injective_test_tube and injective_testing.
It’s easy to accidentally mix the two versions of the helper when both are in scope; consider re-exporting them from a single testing util module to keep call-sites tidy.

contracts/swap/src/testing/integration_realistic_tests_min_quantity.rs (2)

41-43: Repeated ad-hoc validator retrieval + “_signer” dummy accounts add avoidable overhead

Every test case fetches its own validator (get_first_validator_signing_account) and then immediately spawns a throw-away _signer solely to register the INJ denom.
Besides noise, each call drains another 1 000 INJ from the validator (see previous comment) and lengthens execution.

Consider factoring this into a small fixture:

fn setup_validator(app: &InjectiveTestApp) -> SigningAccount {
    static ONCE: Once = Once::new();
    let validator = app
        .get_first_validator_signing_account(INJ.to_string(), 20_000f64)
        .unwrap();
    ONCE.call_once(|| {
        // register INJ denom once
        must_init_account_with_funds_and_setting_denoms(
            app,
            &validator,
            &[initial_coin("1", INJ, Decimals::Eighteen)],
        );
    });
    validator
}

This removes the _signer hack, saves several transfers, and keeps the tests clearer.


63-70: INJ amount unexpectedly ballooned

The initial_funds already contain 1 INJ, yet must_init_account_with_funds_and_setting_denoms unconditionally appends another 1 000 INJ (or adds it to an existing INJ entry).
If the test really needs only a dust amount for gas, specify 0 here and rely on the helper’s internal top-up; otherwise document that the effective balance becomes 1 001 INJ to avoid confusion for future readers.

contracts/swap/src/testing/test_utils.rs (3)

51-62: Prefer typed decimals & fail-safe parsing in launch_spot_market_custom

Passing base_decimals/quote_decimals as raw i32 and converting to u32 loses type-safety, while must_from_str will abort the test binary on a typo.
Consider a signature like:

-pub fn launch_spot_market_custom(
-    ...
-    base_decimals: i32,
-    quote_decimals: i32,
+pub fn launch_spot_market_custom(
+    ...
+    base_decimals: Decimals,
+    quote_decimals: Decimals,

and replace must_from_str with FPDecimal::from_str(&s).expect("invalid tick-size") (or bubble Result) to abort with context instead of an opaque panic.


64-78: Don’t silence exchange errors with unwrap()

instant_spot_market_launch(...).unwrap() panics on any chain failure (e.g., duplicate ticker, invalid decimals).
Returning Result<_, E> from this helper and propagating the error keeps test failures descriptive and avoids aborting mid-suite:

-).unwrap();
+)?;           // propagate anyhow::Error or injective_test_tube::Error

(Same pattern applies to the subsequent get_spot_market_id call if you convert the function to Result).


657-660: Derive useful traits for InitialCoin

InitialCoin is frequently cloned & printed in tests; deriving Clone, Debug, and perhaps PartialEq will simplify assertions and logging:

-pub struct InitialCoin {
+#[derive(Clone, Debug, PartialEq)]
+pub struct InitialCoin {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2a4ba4 and 5e7170a.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • .github/workflows/rust.yaml (3 hunks)
  • Cargo.toml (1 hunks)
  • build_release.sh (1 hunks)
  • contracts/swap/src/swap.rs (1 hunks)
  • contracts/swap/src/testing/authz_tests.rs (2 hunks)
  • contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (21 hunks)
  • contracts/swap/src/testing/integration_realistic_tests_min_quantity.rs (18 hunks)
  • contracts/swap/src/testing/migration_test.rs (2 hunks)
  • contracts/swap/src/testing/test_utils.rs (11 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
contracts/swap/src/testing/migration_test.rs (1)
contracts/swap/src/testing/test_utils.rs (3)
  • initial_coin (811-816)
  • must_init_account_with_funds_and_setting_denoms (666-699)
  • str_coin (805-809)
contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (1)
contracts/swap/src/testing/test_utils.rs (7)
  • init_rich_account (782-795)
  • init_self_relaying_contract_and_get_address (618-634)
  • initial_coin (811-816)
  • must_init_account_with_funds_and_setting_denoms (666-699)
  • query_bank_balance (711-724)
  • set_route_and_assert_success (636-655)
  • str_coin (805-809)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Lints
  • GitHub Check: Unit Tests
🔇 Additional comments (3)
Cargo.toml (1)

14-19: Double-check compatibility of mixed beta crates

injective-* crates are now pinned to 1.16.0-beta.*, but the versions are not all aligned (beta.2, beta.3). These crates are usually released in lock-step; a minor skew often compiles but can yield subtle codec mismatches at runtime.

  • Make sure the beta tags are intended and that the versions compile together against the same protobuf definitions.
  • Consider bumping injective-test-tube to 1.16.0-beta.2 (or the rest to beta.3) for consistency.

If the mismatch is required, please add a short comment in Cargo.toml so that future upgrades don’t silently regress.

Also applies to: 24-24

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

23-34:

Details

❌ Incorrect review comment

Validator balance very likely insufficient for the subsequent 1 000 INJ transfers

must_init_account_with_funds_and_setting_denoms automatically transfers 1 000 INJ from the supplied validator to every newly-created account.
With only 1.2f64 INJ pre-funded here, the very first call will already overdraw the validator, leading to flaky “insufficient funds” panics once the helper executes the Bank::send.

-let validator = app.get_first_validator_signing_account(INJ.to_string(), 1.2f64).unwrap();
+// Provide a balance that safely covers all helper-triggered transfers.
+// 10_000 INJ is the amount used in other tests and guarantees head-room.
+let validator = app
+    .get_first_validator_signing_account(INJ.to_string(), 10_000_f64)
+    .unwrap();

Please bump the amount (or make it a shared constant) to guarantee test stability.


Let’s verify the helper’s behavior and how other tests fund the validator:


🏁 Script executed:

#!/bin/bash
echo "🔍 Searching for must_init_account_with_funds_and_setting_denoms definition and usage"
rg -n "must_init_account_with_funds_and_setting_denoms" -C 3

echo
echo "🔍 Searching for get_first_validator_signing_account calls and their funding amounts"
rg -n "get_first_validator_signing_account" -C 3

Length of output: 54746


Let’s inspect the helper and validator-funding implementations to confirm behavior:


🏁 Script executed:

#!/bin/bash
echo "📝 must_init_account_with_funds_and_setting_denoms (lines 650–750):"
sed -n '650,750p' contracts/swap/src/testing/test_utils.rs

echo
echo "📝 get_first_validator_signing_account definition:"
rg -n -A5 "pub fn get_first_validator_signing_account" -C5 contracts/swap/src/testing/test_utils.rs

Length of output: 3537


Invalid drain assumption: helper seeds new account and uses its funds to register decimals – no outflow from validator
The helper mints the extra 1 e21 INJ into the new account, then sends it to the validator; it does not withdraw tokens from the validator. Your existing 1.2_f64 INJ for get_first_validator_signing_account remains sufficient.

Likely an incorrect or invalid review comment.

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

308-308: 👍 min_notional set to a non-zero value

The previous 0 caused edge-case rejections on order creation; the new 0.000000001 aligns with exchange validation rules.

Comment on lines +263 to 265
let first_message = binding.msg_responses.first();
let order_response = MsgCreateSpotMarketOrderResponse::decode(first_message.unwrap().value.as_slice())
.map_err(|err| ContractError::ReplyParseFailure {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Still an unwrap() landmine – surface proper errors to the caller

The typo fix is 👍, but first_message.unwrap() will panic if the reply contains no messages, turning a recoverable protocol error into a contract abort.

-let first_message = binding.msg_responses.first();
-let order_response = MsgCreateSpotMarketOrderResponse::decode(first_message.unwrap().value.as_slice())
+let first_message = binding
+    .msg_responses
+    .first()
+    .ok_or_else(|| ContractError::CustomError { val: "empty msg_responses".into() })?;
+
+let order_response = MsgCreateSpotMarketOrderResponse::decode(first_message.value.as_slice())

Same applies to the trailing .unwrap() on decode. Eliminating these will make on-chain behaviour deterministic and queryable.

📝 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
let first_message = binding.msg_responses.first();
let order_response = MsgCreateSpotMarketOrderResponse::decode(first_message.unwrap().value.as_slice())
.map_err(|err| ContractError::ReplyParseFailure {
// Don’t unwrap a possibly empty list—return a ContractError instead
let first_message = binding
.msg_responses
.first()
.ok_or_else(|| ContractError::CustomError {
val: "empty msg_responses".into(),
})?;
let order_response = MsgCreateSpotMarketOrderResponse::decode(first_message.value.as_slice())
.map_err(|err| ContractError::ReplyParseFailure {
// …existing fields…
})?;
🤖 Prompt for AI Agents
In contracts/swap/src/swap.rs around lines 263 to 265, the code uses unwrap() on
first_message and decode results, which can cause panics if no messages exist or
decoding fails. Replace unwrap() calls with proper error handling by checking if
first_message is Some and returning a ContractError if None, and handle decode
errors by mapping them to ContractError without panicking, ensuring
deterministic and safe on-chain behavior.

Comment on lines +37 to +43
let validator = app.get_first_validator_signing_account(INJ.to_string(), 1.2f64).unwrap();
send(&Bank::new(&app), "1000000000000000000000", "inj", &owner, &validator);
add_denom_notional_and_decimal(&app, &validator, INJ.to_string(), "1".to_string(), 18);
add_denom_notional_and_decimal(&app, &validator, ETH.to_string(), "1".to_string(), 18);
add_denom_notional_and_decimal(&app, &validator, ATOM.to_string(), "1".to_string(), 6);
add_denom_notional_and_decimal(&app, &validator, USDT.to_string(), "1".to_string(), 6);

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

Swallowing Result from send & add_denom_notional_and_decimal hides failing pre-conditions

All three helpers return Result<…, Error>. Ignoring them may lead to silently skipped funding / denomination setup when the chain parameters change.

-send(&Bank::new(&app), "1000000000000000000000", "inj", &owner, &validator);
+send(&Bank::new(&app), "1000000000000000000000", "inj", &owner, &validator)
+    .unwrap();

-add_denom_notional_and_decimal(&app, &validator, INJ.to_string(), "1".to_string(), 18);
+add_denom_notional_and_decimal(&app, &validator, INJ.to_string(), "1".to_string(), 18).unwrap();

Applying unwrap() (or expect) keeps the test deterministic and will fail fast if the chain API ever rejects these operations.

🤖 Prompt for AI Agents
In contracts/swap/src/testing/authz_tests.rs around lines 37 to 43, the calls to
send and add_denom_notional_and_decimal ignore their Result return values, which
can hide errors and cause silent test failures. Update these calls to use
unwrap() or expect() to handle the Result properly, ensuring the test fails
immediately if any operation returns an error.

Comment on lines +666 to +699
pub fn must_init_account_with_funds_and_setting_denoms(
app: &InjectiveTestApp,
validator: &SigningAccount,
initial_funds: &[InitialCoin],
) -> SigningAccount {
let mut initial_funds_coin: Vec<Coin> = initial_funds
.iter()
.map(|ic| coin(ic.coin.amount.into(), ic.coin.denom.clone()))
.collect();
let mut initial_funds_decimals = initial_funds.iter().map(|ic| ic.decimals).collect::<Vec<u32>>();

// add 1000000000000000000000 inj to initial funds with adding to element if inj already in it
if let Some(pos) = initial_funds_coin.iter().position(|c| c.denom == INJ) {
initial_funds_coin[pos].amount += Uint128::from(1_000_000_000_000_000_000_000u128);
} else {
initial_funds_coin.push(coin(1_000_000_000_000_000_000_000u128, INJ.to_string()));
initial_funds_decimals.push(18);
}

let account = app.init_account_decimals(&initial_funds_coin, &initial_funds_decimals).unwrap();
send(&Bank::new(app), "1000000000000000000000", "inj", &account, validator);

for initial_coin in initial_funds {
add_denom_notional_and_decimal(
app,
validator,
initial_coin.coin.denom.to_string(),
"1".to_string(),
initial_coin.decimals as u64,
);
}

account
}

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

INJ denom is added but not registered

When the caller omits inj, the helper pushes the coin/decimals but skips add_denom_notional_and_decimal, so later spot-market ops can fail with “denom not registered”.

 if let Some(pos) = initial_funds_coin.iter().position(|c| c.denom == INJ) {
     ...
 } else {
     initial_funds_coin.push(coin(1_000_000_000_000_000_000_000u128, INJ.to_string()));
     initial_funds_decimals.push(18);
+    add_denom_notional_and_decimal(
+        app,
+        validator,
+        INJ.to_string(),
+        "1".to_string(),
+        18,
+    );
 }

Please ensure the extra denom is registered before returning the account.

📝 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 fn must_init_account_with_funds_and_setting_denoms(
app: &InjectiveTestApp,
validator: &SigningAccount,
initial_funds: &[InitialCoin],
) -> SigningAccount {
let mut initial_funds_coin: Vec<Coin> = initial_funds
.iter()
.map(|ic| coin(ic.coin.amount.into(), ic.coin.denom.clone()))
.collect();
let mut initial_funds_decimals = initial_funds.iter().map(|ic| ic.decimals).collect::<Vec<u32>>();
// add 1000000000000000000000 inj to initial funds with adding to element if inj already in it
if let Some(pos) = initial_funds_coin.iter().position(|c| c.denom == INJ) {
initial_funds_coin[pos].amount += Uint128::from(1_000_000_000_000_000_000_000u128);
} else {
initial_funds_coin.push(coin(1_000_000_000_000_000_000_000u128, INJ.to_string()));
initial_funds_decimals.push(18);
}
let account = app.init_account_decimals(&initial_funds_coin, &initial_funds_decimals).unwrap();
send(&Bank::new(app), "1000000000000000000000", "inj", &account, validator);
for initial_coin in initial_funds {
add_denom_notional_and_decimal(
app,
validator,
initial_coin.coin.denom.to_string(),
"1".to_string(),
initial_coin.decimals as u64,
);
}
account
}
pub fn must_init_account_with_funds_and_setting_denoms(
app: &InjectiveTestApp,
validator: &SigningAccount,
initial_funds: &[InitialCoin],
) -> SigningAccount {
let mut initial_funds_coin: Vec<Coin> = initial_funds
.iter()
.map(|ic| coin(ic.coin.amount.into(), ic.coin.denom.clone()))
.collect();
let mut initial_funds_decimals = initial_funds.iter().map(|ic| ic.decimals).collect::<Vec<u32>>();
// add 1000000000000000000000 inj to initial funds with adding to element if inj already in it
if let Some(pos) = initial_funds_coin.iter().position(|c| c.denom == INJ) {
initial_funds_coin[pos].amount += Uint128::from(1_000_000_000_000_000_000_000u128);
} else {
initial_funds_coin.push(coin(1_000_000_000_000_000_000_000u128, INJ.to_string()));
initial_funds_decimals.push(18);
// ensure INJ is registered just as we do for other denoms
add_denom_notional_and_decimal(
app,
validator,
INJ.to_string(),
"1".to_string(),
18,
);
}
let account = app.init_account_decimals(&initial_funds_coin, &initial_funds_decimals).unwrap();
send(&Bank::new(app), "1000000000000000000000", "inj", &account, validator);
for initial_coin in initial_funds {
add_denom_notional_and_decimal(
app,
validator,
initial_coin.coin.denom.to_string(),
"1".to_string(),
initial_coin.decimals as u64,
);
}
account
}
🤖 Prompt for AI Agents
In contracts/swap/src/testing/test_utils.rs around lines 666 to 699, the
function adds the INJ coin and decimals to initial_funds_coin and
initial_funds_decimals but does not call add_denom_notional_and_decimal for INJ,
which can cause "denom not registered" errors later. To fix this, after pushing
INJ to initial_funds_coin and initial_funds_decimals, call
add_denom_notional_and_decimal with the INJ denom, a notional value (e.g., "1"),
and decimals (18) before returning the account.

@jbernal87 jbernal87 self-requested a review June 13, 2025 10:56
jbernal87
jbernal87 previously approved these changes Jun 13, 2025

@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

@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: 0

♻️ Duplicate comments (1)
contracts/swap/src/testing/test_utils.rs (1)

681-700: inj denom still not registered when auto-injected

This is the same gap flagged in the previous review: when the caller’s initial_funds omit inj, the helper pushes an extra inj coin but never registers the denom via add_denom_notional_and_decimal.
Tests that rely on later spot-market ops will still fail with “denom not registered”.

     } else {
         initial_funds_coin.push(coin(1_000_000_000_000_000_000_000u128, INJ.to_string()));
         initial_funds_decimals.push(18);
+
+        // Ensure the newly added denom is registered
+        add_denom_notional_and_decimal(
+            app,
+            validator,
+            INJ.to_string(),
+            "1".to_string(),
+            18,
+        );
     }

Please address this before merging; otherwise any test that relies on the helper without explicitly passing inj will continue to exhibit flaky failures.

🧹 Nitpick comments (2)
contracts/swap/src/testing/test_utils.rs (2)

55-85: Avoid the extra String clone by accepting &str

launch_spot_market_custom currently takes ticker: String and then immediately performs ticker.clone() to satisfy MsgInstantSpotMarketLaunch. Accepting &str (or impl Into<String>) removes the redundant allocation and avoids ownership juggling.

- pub fn launch_spot_market_custom(
-     exchange: &Exchange<InjectiveTestApp>,
-     signer: &SigningAccount,
-     ticker: String,
+ pub fn launch_spot_market_custom(
+     exchange: &Exchange<InjectiveTestApp>,
+     signer: &SigningAccount,
+     ticker: &str,
@@
-             ticker: ticker.clone(),
+             ticker: ticker.to_owned(),
@@
-     get_spot_market_id(exchange, ticker)
+     get_spot_market_id(exchange, ticker)
 )

This keeps the API flexible, prevents an unnecessary heap allocation, and still works with all current call-sites.


689-692: Handle the send result explicitly

send returns a Result; ignoring it discards potential errors (e.g., insufficient funds) and will trigger a compiler warning (#[must_use]). Recommend unwrapping or proper error bubbling:

-    send(&Bank::new(app), "1000000000000000000000", "inj", &account, validator);
+    send(&Bank::new(app), "1000000000000000000000", "inj", &account, validator)
+        .unwrap();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e7170a and 44d166b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • Cargo.toml (1 hunks)
  • contracts/swap/src/admin.rs (1 hunks)
  • contracts/swap/src/testing/authz_tests.rs (2 hunks)
  • contracts/swap/src/testing/config_tests.rs (1 hunks)
  • contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs (21 hunks)
  • contracts/swap/src/testing/integration_realistic_tests_min_quantity.rs (18 hunks)
  • contracts/swap/src/testing/queries_tests.rs (1 hunks)
  • contracts/swap/src/testing/storage_tests.rs (1 hunks)
  • contracts/swap/src/testing/swap_tests.rs (1 hunks)
  • contracts/swap/src/testing/test_utils.rs (12 hunks)
✅ Files skipped from review due to trivial changes (4)
  • contracts/swap/src/testing/storage_tests.rs
  • contracts/swap/src/admin.rs
  • contracts/swap/src/testing/queries_tests.rs
  • contracts/swap/src/testing/config_tests.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • contracts/swap/src/testing/authz_tests.rs
  • Cargo.toml
  • contracts/swap/src/testing/integration_realistic_tests_min_quantity.rs
  • contracts/swap/src/testing/integration_realistic_tests_exact_quantity.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Lints
  • GitHub Check: Unit Tests
🔇 Additional comments (1)
contracts/swap/src/testing/swap_tests.rs (1)

1-7: Import consolidation LGTM

Grouping the internal crate imports into a single nested block improves readability and keeps the external cosmwasm_std import visually separated. No functional impact spotted.

@jbernal87 jbernal87 self-requested a review June 13, 2025 11:15
@jbernal87 jbernal87 merged commit 89f870b into master Jun 13, 2025
5 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.

2 participants