Skip to content

Comments

Update Anchor branch#2

Open
luke-truitt wants to merge 11 commits intofeat/anchor-30.0from
main
Open

Update Anchor branch#2
luke-truitt wants to merge 11 commits intofeat/anchor-30.0from
main

Conversation

@luke-truitt
Copy link

No description provided.

@gemini-code-assist
Copy link

Summary of Changes

Hello @luke-truitt, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the protocol's financial infrastructure by upgrading its oracle integration, refining core financial calculations, and introducing a critical liquidation price mechanism. The changes aim to improve the accuracy and robustness of price feeds, asset under management (AUM) calculations, and LP token pricing, while also providing essential tools for risk assessment and management within the system.

Highlights

  • Oracle Integration and Price Handling: Introduced a new CustomOracle type and enhanced OraclePrice with methods for normalization, divergence calculation, and robust price fetching, including checks for price age and volatility. This improves the reliability and flexibility of oracle data consumption.
  • Financial Calculation Refinements: Refactored pool equity calculations, changing data types from u128 to u64 for efficiency, and integrated new logic for subtracting fees and rebates. New functions for calculating LP token prices (SFLP and FLP) have been added, providing more granular financial metrics.
  • Liquidation Price Functionality: Implemented a new get_liquidation_price function, which calculates the price at which a position would be liquidated, considering various fees and collateral. This is a critical addition for risk management and user transparency.
  • Struct and Data Model Enhancements: Significant updates to the Pool and Custody structs, adding numerous fields for more comprehensive state management, such as raw_aum_usd, equity_usd, min_lp_price_usd, and reserved_amount. New utility methods were also added to these structs for fee calculation, trade spread determination, and custody identification.
  • Error Handling and Type Optimization: Added new error types (InvalidOraclePrice, UnsupportedCustody) for better error reporting. Optimized Market struct's custody IDs from usize to u8, potentially reducing memory footprint and enforcing limits.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors how oracle prices and pool equity are handled, adds new functions for real-time price fetching and liquidation price calculation, and updates the Pool and Custody structs, improving modularity and adding new features. However, a critical security vulnerability exists due to a missing program ID constraint in the GetLiquidationPrice account validation struct, which could enable account substitution attacks. Furthermore, missing bounds checks on remaining_accounts in flash-compute could lead to transaction panics and denial of service. Beyond security, there are critical and high-severity issues related to potential integer overflows and functional discrepancies in price calculations, and a magic number should be replaced with a named constant for better maintainability.

let mut custody_details: Box<Vec<CustodyDetails>> = Box::new(Vec::new());
let mut pool_equity: u128 = 0;
let mut custody_prices: Vec<OraclePrice> = Vec::new();
let mut pool_equity: u64 = 0;

Choose a reason for hiding this comment

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

critical

The type of pool_equity has been changed from u128 to u64. Given that the previous implementation used u128, there's a possibility that the total pool equity could exceed u64::MAX (approximately $1.8 \times 10^{13}$ USD if USD_DECIMALS is 6). If the protocol is designed to handle larger values, this change could lead to an integer overflow, resulting in incorrect AUM calculations and potential loss of funds. Please confirm that u64 is sufficient for the maximum expected pool equity.

Comment on lines +340 to +343
pub max_aum_usd: u64,
pub buffer: u64,
pub raw_aum_usd: u64,
pub equity_usd: u64,

Choose a reason for hiding this comment

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

critical

The fields max_aum_usd, raw_aum_usd, and equity_usd in the Pool struct have been changed from u128 to u64. Similar to the pool_equity variable in flash-compute/src/lib.rs, this change could lead to integer overflows if the total AUM or equity of the pool exceeds u64::MAX. Please ensure that u64 provides sufficient capacity for these values under all expected conditions.

Comment on lines +368 to +418
#[account(
seeds = [b"perpetuals"],
bump = perpetuals.perpetuals_bump
)]
pub perpetuals: Box<Account<'info, Perpetuals>>,

#[account(
seeds = [b"pool",
pool.name.as_bytes()],
bump = pool.bump
)]
pub pool: Box<Account<'info, Pool>>,

#[account(
seeds = [b"position",
position.owner.as_ref(),
market.key().as_ref()],
bump = position.bump
)]
pub position: Box<Account<'info, Position>>,

#[account(
seeds = [b"market",
target_custody.key().as_ref(),
collateral_custody.key().as_ref(),
&[market.side as u8]],
bump = market.bump
)]
pub market: Box<Account<'info, Market>>,

#[account(
seeds = [b"custody",
pool.key().as_ref(),
target_custody.mint.key().as_ref()],
bump = target_custody.bump
)]
pub target_custody: Box<Account<'info, Custody>>,

/// CHECK: oracle account for the target token
#[account(
constraint = target_oracle_account.key() == target_custody.oracle.ext_oracle_account
)]
pub target_oracle_account: AccountInfo<'info>,

#[account(
seeds = [b"custody",
pool.key().as_ref(),
collateral_custody.mint.key().as_ref()],
bump = collateral_custody.bump,
)]
pub collateral_custody: Box<Account<'info, Custody>>,

Choose a reason for hiding this comment

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

security-high high

The GetLiquidationPrice struct is missing the seeds::program = FLASH_PROGRAM constraint for several accounts, including perpetuals, pool, position, market, target_custody, and collateral_custody. This causes Anchor to derive the PDA addresses using the current program's ID instead of the intended FLASH_PROGRAM ID. An attacker can exploit this by providing fake accounts owned by the current program that match these seeds, allowing them to manipulate the liquidation price calculation. This is a critical security flaw as it bypasses intended account validation.

math::checked_as_u64(math::checked_div(
math::checked_mul(
math::checked_sub(position.collateral_usd, liabilities_usd)? as u128,
math::checked_pow(10_u128, (position.size_decimals + 3) as usize)?,

Choose a reason for hiding this comment

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

medium

The magic number 3 in (position.size_decimals + 3) as usize should be replaced with a named constant. This improves readability and makes the purpose of the offset clearer. For example, LIQUIDATION_PRICE_DECIMAL_OFFSET.

Suggested change
math::checked_pow(10_u128, (position.size_decimals + 3) as usize)?,
math::checked_pow(10_u128, (position.size_decimals + LIQUIDATION_PRICE_DECIMAL_OFFSET) as usize)?,

math::checked_mul(
math::checked_sub(liabilities_usd, position.collateral_usd)? as u128,
math::checked_pow(10_u128, (position.size_decimals + 3) as usize)?,
)?,

Choose a reason for hiding this comment

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

medium

The magic number 3 in (position.size_decimals + 3) as usize should be replaced with a named constant. This improves readability and makes the purpose of the offset clearer. For example, LIQUIDATION_PRICE_DECIMAL_OFFSET.

Suggested change
)?,
math::checked_pow(10_u128, (position.size_decimals + LIQUIDATION_PRICE_DECIMAL_OFFSET) as usize)?,

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