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

trades-work #6

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

trades-work #6

wants to merge 5 commits into from

Conversation

faddat
Copy link
Collaborator

@faddat faddat commented Dec 31, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for USDC token operations.
    • Enhanced token account management with new methods for account creation and balance retrieval.
    • Introduced new fields in the MeteoraPool struct for improved data handling.
  • Improvements

    • More detailed trade execution logging, including transaction status and error reporting.
    • Refined logic for detecting arbitrage opportunities based on pool types.
    • Simplified error handling for keypair file reading.
  • Technical Updates

    • Updated dependencies to support SPL Token standard.
    • Adjusted visibility of key fields for better access and management.

Copy link

coderabbitai bot commented Dec 31, 2024

Walkthrough

The pull request introduces several modifications to enhance the Solana trading infrastructure. Key changes include the addition of the USDC_MINT constant, improvements in error handling and logging within the CLI, and updates to the trade execution logic. A new dependency on the spl-token crate is added to support SPL Token operations. The TradeExecutor struct is updated with new methods for token account management, and visibility changes allow external access to certain fields, refining the overall functionality of the trading system.

Changes

File Change Summary
packages/cli/src/main.rs - Added USDC_MINT constant
- Simplified error handling
- Enhanced trade execution logging
- Updated find_arbitrage_opportunities method signature
packages/libcheese/Cargo.toml - Added spl-token dependency (v4.0.0)
- Added lazy_static dependency (v1.4.0)
packages/libcheese/src/common.rs - Added USDC_MINT constant
- Added BLACKLISTED_MINTS static reference
- Added is_blacklisted function
packages/libcheese/src/solana.rs - Made rpc_client and wallet fields public
- Added methods for token account management (create_token_account, ensure_token_account, get_token_balance)
- Enhanced transaction simulation and error reporting
- Improved balance checking logic
packages/libcheese/src/meteora.rs - Added new fields in MeteoraPool struct
- Updated fetch_meteora_cheese_pools function
- Introduced MeteoraSwapAccounts struct and related methods
- Enhanced error handling in get_meteora_swap_transaction

Possibly related PRs

  • Faddat/combine data #4: The changes in the main PR involve modifications to the main.rs file, specifically enhancing error handling and trade execution logic, which may relate to the overall data handling and structure changes in the packages/cli/src/main.rs file from the retrieved PR.

Poem

🧀 Arbitrage Rabbit's Delight 🐰
In Solana's vast trading sea,
USDC mint, now set with glee,
Token accounts dance and spin,
With error handling, we shall win!
CodeRabbit's magic, trade so bright! 🚀


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. (Beta)
  • @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

@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

🧹 Nitpick comments (8)
packages/libcheese/src/solana.rs (7)

141-153: Distinguish 'account not found' errors from other RPC errors
In the Err(_) branch, the code immediately attempts to create the token account, but the failure cause might be something other than a missing account (e.g., network issue).
Refining this error handling or logging can prevent unintended account creation.


155-160: Robust parse handling
Using .parse::<u64>().unwrap_or(0) might silently mask parsing errors if the RPC returns unexpected data.
Consider logging or handling parse failures more explicitly to avoid confusion.

Also applies to: 162-168


213-224: Simulation error logging
Capturing and printing the simulation error plus logs is helpful for debugging.
For production usage, consider upgrading to a structured logging framework rather than println!.


Line range hint 415-423: Basic trade execution logs
These logs provide good at-a-glance details for debugging.
Consider adopting consistent, structured logging across the project.


Line range hint 479-480: Percentage-based target token usage
Using a fixed 10% of target liquidity is a simplistic approach.
If you need more dynamic risk management, consider refining this strategy.


Line range hint 528-529: Partial target token usage
Again, 10% is a fixed figure that may not reflect all market conditions.
Consider making this adaptive if needed.


Line range hint 587-591: Static 10% vs 5% trade size
Choosing a constant fraction of liquidity, while simple, may not be optimal.
For sophisticated trading, consider more dynamic logic.

packages/cli/src/main.rs (1)

122-122: Improved error handling with anyhow!
This change provides a more direct error context for keypair file reading.
For more robust error tracking, consider structured or contextual logs.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7b3737 and f65a79b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • packages/cli/src/main.rs (10 hunks)
  • packages/libcheese/Cargo.toml (1 hunks)
  • packages/libcheese/src/common.rs (1 hunks)
  • packages/libcheese/src/solana.rs (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/libcheese/src/common.rs
🔇 Additional comments (16)
packages/libcheese/src/solana.rs (13)

12-12: Use of spl_token import
No issues found. This import is necessary for the new token-related logic.


112-123: Blockhash verification and signing improvements
This logic ensures the transaction is refreshed with the latest blockhash and handles signing if the transaction is not already signed.
Consider verifying multi-sig requirements if other signers are needed in certain contexts.


175-199: Creating associated token account
Implementation closely follows recommended patterns for creating an associated token account.
This looks correct and maintains clarity.


230-247: Error reporting in send_and_confirm_transaction
Fetching the transaction status on failure is valuable for diagnosing issues.
This approach is acceptable; consider structured logs for improved maintainability.


249-263: Ensuring token account creation
Similar logic to check_token_balance: a generic Err(_) from get_account triggers creation.
Distinguishing “account not found” from other errors may improve correctness.


Line range hint 431-442: Ensuring token accounts exist before trading
Sequential sanity checks on token account existence reduce failures mid-trade.
No major issues noted.


Line range hint 445-450: Sell path initialization
Clear step-by-step user-facing logs.
Verify these path details match the intended trade flow in docs or comments.


Line range hint 464-465: CHEESE amount conversion
Multiplying by 1_000_000_000.0 assumes 9 decimals for CHEESE.
Confirm the token’s decimal precision to prevent under/overfunding.


Line range hint 493-494: Final step usage
This logs the initial amount of CHEESE again. If you accumulate more (or less) CHEESE after prior steps, ensure that’s reflected.


Line range hint 500-505: Buy path initialization
Similar approach to the sell path, with consistent logging.
No immediate issues noticed.


Line range hint 513-514: CHEESE amount conversion
As above, verify 9 decimal places are correct for CHEESE to avoid mismatch.


Line range hint 542-543: Final step: CHEESE -> USDC
Re-check that the final step’s amount in CHEESE accurately reflects any preceding trades.


Line range hint 575-575: Identifying USDC pool
Using pool_token_mints.contains(...) is clear and straightforward.

packages/cli/src/main.rs (2)

1-1: Use of anyhow::Result
Imports look good. This is a convenient and flexible error type.


3-3: Added USDC_MINT import
Consistent with the code in libcheese/src/common.rs, ensuring a unified reference to USDC.

packages/libcheese/Cargo.toml (1)

15-15: Added spl-token = "4.0.0"
Aligns with new token account functionalities in solana.rs.

Copy link

@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 comments (1)
packages/libcheese/src/solana.rs (1)

Line range hint 282-286: Critical: Missing test coverage for trade execution

The test module contains only a TODO comment. Given the critical nature of trading functionality, comprehensive test coverage is essential.

Would you like me to help generate a comprehensive test suite that covers:

  • Trade execution with various scenarios
  • Token account management
  • Error conditions and edge cases
  • Transaction simulation and confirmation
🧹 Nitpick comments (6)
packages/cli/src/main.rs (3)

122-154: LGTM! Consider extracting magic numbers.

The wallet information display is well-implemented with proper error handling and clear formatting.

Consider extracting the denomination constants:

+const LAMPORTS_PER_SOL: f64 = 1_000_000_000.0;
+const DECIMALS_USDC: f64 = 1_000_000.0;
+const DECIMALS_CHEESE: f64 = 1_000_000.0;

-println!("SOL balance: {} SOL", sol_balance as f64 / 1_000_000_000.0);
+println!("SOL balance: {} SOL", sol_balance as f64 / LAMPORTS_PER_SOL);

443-471: LGTM! Consider using proper log levels.

The trade execution logging is comprehensive and well-structured.

Consider using proper log levels instead of println:

use log::{info, debug, warn, error};

// Instead of println!
info!("=== Starting Trade Execution ===");
debug!("Trade details:");
debug!("- Is sell: {}", opp.is_sell);

622-626: Extract pool size constants for better maintainability.

The differentiation between USDC and non-USDC pools is good, but the percentages should be constants.

+const USDC_POOL_SIZE_PERCENT: f64 = 0.1;  // 10%
+const OTHER_POOL_SIZE_PERCENT: f64 = 0.05; // 5%

 let max_trade_size = if is_usdc_pool {
-    cheese_qty * 0.1
+    cheese_qty * USDC_POOL_SIZE_PERCENT
 } else {
-    cheese_qty * 0.05
+    cheese_qty * OTHER_POOL_SIZE_PERCENT
 };
packages/libcheese/src/solana.rs (3)

23-24: Consider maintaining encapsulation of TradeExecutor fields

Making rpc_client and wallet public exposes internal implementation details and could lead to potential misuse. Consider providing specific public methods instead of exposing these fields directly.

-    pub rpc_client: RpcClient,
-    pub wallet: Keypair,
+    rpc_client: RpcClient,
+    wallet: Keypair,

142-169: Good improvements in token balance verification

The changes improve reliability by:

  • Checking token account existence
  • Creating missing accounts automatically
  • Using raw amounts for accurate comparison

Consider extracting the power of 10 calculation to a constant or helper method for better readability:

+ const fn get_token_decimals_multiplier(decimals: u8) -> f64 {
+     10f64.powi(decimals as i32)
+ }

- amount as f64 / 10f64.powi(balance.decimals as i32)
+ amount as f64 / get_token_decimals_multiplier(balance.decimals)

214-225: Good enhancement of transaction simulation feedback

The improved error reporting helps with debugging. Consider formatting the logs for better readability:

- println!("Transaction logs:");
+ println!("\nTransaction logs:");
  for log in logs {
-     println!("  {}", log);
+     println!("    {}", log);
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f65a79b and 46b9ad4.

📒 Files selected for processing (2)
  • packages/cli/src/main.rs (11 hunks)
  • packages/libcheese/src/solana.rs (5 hunks)
🔇 Additional comments (3)
packages/cli/src/main.rs (1)

603-609: LGTM! Clear and concise USDC pool handling.

The USDC pool detection and price calculation logic is well-implemented.

packages/libcheese/src/solana.rs (2)

113-124: Well-implemented transaction preparation logic

Good improvements in transaction handling:

  • Verifies and updates blockhash if needed
  • Checks for existing signatures before signing
  • Clear and defensive programming approach

176-199: Well-structured token account creation implementation

The implementation follows Solana best practices:

  • Uses official SPL associated token account program
  • Proper transaction construction and signing
  • Good error handling and user feedback

Comment on lines +250 to +272
/// Ensure a token account exists for the given mint
pub async fn ensure_token_account(&self, mint: &str) -> Result<()> {
let token_account = self.find_token_account(mint)?;

// Check if token account exists
match self.rpc_client.get_account(&token_account) {
Ok(_) => {
println!("Token account {} exists", token_account);
Ok(())
}
Err(_) => {
println!("Creating token account for mint {}", mint);
self.create_token_account(mint).await
}
}
}

pub async fn get_token_balance(&self, mint: &Pubkey) -> Result<u64> {
let token_account = get_associated_token_address(&self.wallet.pubkey(), mint);
match self.rpc_client.get_token_account_balance(&token_account) {
Ok(balance) => Ok(balance.amount.parse().unwrap_or(0)),
Err(_) => Ok(0), // Return 0 if account doesn't exist
}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing test coverage for new token account utility methods

The codebase has a test module in solana.rs, but it currently only has a placeholder for test_trade_executor. The newly added public methods ensure_token_account and get_token_balance lack test coverage. These methods handle critical token account operations and should be thoroughly tested to ensure reliability.

Required test coverage:

  • ensure_token_account: Test both scenarios where token account exists and needs creation
  • get_token_balance: Test successful balance retrieval and handling of non-existent accounts
🔗 Analysis chain

Well-designed utility methods with clear responsibilities

Good addition of utility methods with proper error handling. However, these new public methods need test coverage.

Would you like me to help generate unit tests for these new methods?

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing tests of the new methods
rg -l "test.*ensure_token_account|test.*get_token_balance" 

Length of output: 60


Script:

#!/bin/bash
# Let's try a broader search for test files in the package
fd "test.*\.rs$" packages/libcheese/

# Also search for any test modules in solana.rs
rg "#\[cfg\(test\)\]" packages/libcheese/src/solana.rs -A 10

Length of output: 236

Copy link

@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 (11)
packages/libcheese/src/meteora.rs (7)

35-37: Potentially verbose or sensitive debug logging
Printing the entire raw response is great for debugging but may be verbose and could include sensitive data. Consider limiting the length or adding log levels.


38-38: Parse error handling
When parsing JSON, consider adding more contextual information to the error message to aid in debugging.


69-71: String-based token amount fields
Storing token amounts as strings could lead to repeated parsing. Consider storing them as numeric types to improve usability.


86-90: Flags for unknown and permissioned pools
Adding boolean flags is a neat approach, but clarify how or when these fields are enforced to maintain consistent behavior across the codebase.


94-96: Fee percentage stored as string
While storing the fee as a string can work, using a numeric type avoids extra parse steps and potential conversion errors.


197-206: MeteoraQuoteResponse storing amounts as strings
Maintaining amounts as String may require frequent runtime parsing. Consider numeric fields to simplify calculations.


298-343: Hard-coded vault program string
While this may be correct for now, refactoring to consistently use get_vault_program() might reduce duplication and potential mismatches.

packages/libcheese/src/solana.rs (4)

49-54: Detailed logs in execute_trade
In-depth logging is beneficial, but consider using a structured logger if you find logs too verbose.


96-127: Enhanced debugging of accounts
Logging each account is extremely helpful but can be dense. For large-scale production, consider grouping logs or using structured data.


143-156: Inlined MeteoraSwapAccounts construction
Manually building the struct is fine. However, reusing the existing get_swap_accounts from MeteoraPool might reduce code duplication.


224-247: Creating the token account with minimal error details
Consider improved error messages if account creation fails, possibly adding logs or context.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16ac47a and 94ee5a6.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • packages/cli/src/main.rs (16 hunks)
  • packages/libcheese/Cargo.toml (1 hunks)
  • packages/libcheese/src/common.rs (2 hunks)
  • packages/libcheese/src/meteora.rs (5 hunks)
  • packages/libcheese/src/solana.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/cli/src/main.rs
🔇 Additional comments (21)
packages/libcheese/src/meteora.rs (9)

5-6: New imports for JSON and Pubkey
Importing serde_json::json and solana_sdk::pubkey::Pubkey looks standard and necessary for upcoming enhancements.


73-76: Defaulting token decimals and prices
Using #[serde(default)] ensures missing fields won't break deserialization. Verify that these defaults match the real-world data.


91-93: Fee volume default
Ensure that initializing fee_volume to 0.0 is intentional if the API doesn’t provide a fee volume.


97-108: Vault address fields as String
All vault fields are stored as strings and converted to Pubkey later. This can be fine for external JSON but might fail if an incorrect address is supplied. Make sure to validate or handle exceptions.


148-168: Parsing addresses in get_swap_accounts
Multiple .parse() calls on strings. Consider adding more context or using a utility to handle malformed addresses gracefully.


174-188: MeteoraSwapAccounts struct
The structure is consistent and straightforward, facilitating organized handling of swap-related accounts.


208-218: Request/response struct definitions
Using dedicated structs for requests and responses is a clean design choice, making the code more expressive.


243-250: Fee percentage fallback
Defaulting the fee to 0.3% hides parse errors. Consider explicitly handling unexpected values for easier debugging.


289-295: Ensuring pools exist before initialization
The check for Pool not found is good. Confirm that init_vault_fields() remains valid even with minimal pool data.

packages/libcheese/Cargo.toml (1)

15-18: Added dependencies: spl-token and lazy_static
Both additions look appropriate for token handling and static references.

packages/libcheese/src/common.rs (4)

1-4: Imports for lazy_static and HashSet
No issues with introducing lazy_static and HashSet, these are standard solutions for static references.


7-8: USDC_MINT constant
Defining USDC_MINT here is convenient for referencing in other modules, ensuring consistency throughout the codebase.


9-16: BLACKLISTED_MINTS static reference
Using lazy_static! for a set of blacklisted mints is a simple way to keep them accessible and immutable at runtime.


45-47: is_blacklisted function
This helper cleanly checks membership in the blacklist. Straightforward and effective.

packages/libcheese/src/solana.rs (7)

12-13: Importing token account utilities
get_associated_token_address and spl_token are essential for the new token operations.


17-17: Re-exporting Meteora references
No concerns. The link to MeteoraPool and MeteoraSwapAccounts is clear.


23-24: Making rpc_client and wallet public
Double-check the rationale for exposing these fields. It might be required for integration, but consider potential security or concurrency implications.


47-47: Switch from u64 to u16 for slippage
A narrower type for basis points is typically safer and more conventional.


160-173: Blockhash update & manual signing
Updating the blockhash and signing logic ensures transactions remain valid. This is a robust approach.


190-217: On-demand token account creation
Automatically creating the token account if it doesn’t exist is convenient, but watch for possible race conditions in concurrent trades.


298-320: Missing test coverage for account utility methods
Unit tests for ensure_token_account and get_token_balance remain essential.

Comment on lines +115 to +146
// Add helper methods to MeteoraPool
impl MeteoraPool {
pub fn get_vault_program(&self) -> Result<Pubkey> {
// This is Meteora's vault program ID
Ok("24Uqj9JCLxUeoC3hGfh5W3s9FM9uCHDS2SG3LYwBpyTi".parse()?)
}

pub fn get_token_program(&self) -> Pubkey {
spl_token::ID
}

// Add this method to initialize vault fields from the vaults array
pub fn init_vault_fields(&mut self) -> Result<()> {
if self.vaults.len() < 2 {
return Err(anyhow!("Pool must have at least 2 vaults"));
}

self.vault_a = self.vaults[0].clone();
self.vault_b = self.vaults[1].clone();

// For now, use placeholder values for other vault fields
self.token_vault_a = "placeholder".to_string();
self.token_vault_b = "placeholder".to_string();
self.vault_lp_mint_a = "placeholder".to_string();
self.vault_lp_mint_b = "placeholder".to_string();
self.vault_lp_token_a = "placeholder".to_string();
self.vault_lp_token_b = "placeholder".to_string();
self.protocol_fee_token_a = "placeholder".to_string();
self.protocol_fee_token_b = "placeholder".to_string();

Ok(())
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Placeholder fields in init_vault_fields
Storing "placeholder" in production code can lead to confusion or runtime errors. Prefer more definitive logic for setting these vault fields or remove them if unused.

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.

1 participant