In the "Dark Forest" of Solana, when you receive an account update signal from the Scout module, the competition has entered its final milliseconds. If you still need to send the transaction back to the RPC node for "Simulation" to get a quote, then by the time you get the result, the opportunity has often already been seized by those competitors who completed the calculations locally.

A true professional Searcher never waits for RPC feedback. They maintain a local memory image of the AMM state and, upon receiving the binary data, directly calculate the optimal price through mathematical models in an instant.

This article will break down how to build an efficient local pricing engine for Raydium (CPMM) and Orca (CLMM).

1. Core Concept: Local Calculation vs. RPC Simulation

1.1 Why Choose Local Pricing?

  • Extreme Latency: RPC simulations typically require 50ms-200ms, while local pure mathematical calculations only need microseconds.

  • Concurrency: Local calculations do not consume the performance of RPC nodes and can instantly exhaustively price thousands of arbitrage paths.

  • Determinism: By parsing raw account data (Account Data), you can gain lower-level state control than simulations.

2. Raydium (CPMM): The Art of Constant Product

Raydium's standard pool follows the classic x×y=k formula. Although the logic is simple, the engineering implementation needs to handle small deviations in precision and fees.

2.1 Core Pricing Formula

In scenarios with fees, the integer version formula for calculating amount_out is:

  1. Fee-inclusive input: AmountIn_with_fee=AmountIn×(FeeDenominator−FeeNumerator)

  2. Output calculation: AmountOut=AmountIn_with_fee×Reserve_out/(Reserve_in×FeeDenominator+AmountIn_with_fee)

2.2 Precision Game: The Necessity of U256

On Solana, the token amount is usually u64. However, when calculating the numerator of the aforementioned formula, multiplying two large u64s will immediately cause overflow.

  • Solution: Introduce U256 in the calculation middleware. Although Rust's official library does not provide it directly, we can ensure absolute precision under high volatility (large inputs) using the uint macro or primitive-types library.

3. Orca Whirlpool (CLMM): Precise Analysis of Concentrated Liquidity

Compared to CPMM, Orca's concentrated liquidity (CLMM) model is much more complex. It involves not only prices but also Ticks (price ranges) and liquidity depth.

3.1 Representation of Price: Q64.64 sqrtPrice

Orca uses square root prices (sqrtPrice) and stores them in Q64.64 floating-point format.

  • Formula: Price=(sqrtPriceX64264)2

  • During parsing, we need to handle 128-bit huge integers, extracting the real price through bitwise operations.

3.2 Speedy Analysis: Offset Slicing Method

Orca's Whirlpool account structure is very large (containing multiple sets of rewards, fee parameters, etc.), and using complete deserialization (Borsh Deserialize) incurs significant performance loss.
Industrial-grade optimization solution:
Directly locate the Offset of the account binary data. Since the pool structure is fixed, we can slice and read the key bytes directly:

  • data[49..65] -> Liquidity

  • data[65..81] -> Price (sqrtPrice)

  • data[81..85] -> Current Tick
    This method is more than 10 times faster than complete parsing.

4. Architecture Design: Quote Layer

To ensure that the strategy layer (Strategy) does not need to be concerned with the mathematical differences between different DEXs, we need to build a unified Quote engine:

flowchart LR
RawData[Raw Account Data] --\u003e|Parse| AMMState[AMM Memory Image]
AMMState --\u003e|Input Amount| LocalMath[Local Math Model]
LocalMath --\u003e|Output| AmountOut[Structured Quote]

subgraph "Local Computing Layer"
LocalMath
AMMState
end

This engine will maintain the pool's Vault Balance in real-time. When the Scout detects any changes in a Vault, the Quote engine will immediately recalculate the full-path quote for that token pair.

5. Engineering Optimization: Speed from Details

  1. Zero Allocation Calculation: During the computation process, try to avoid memory allocation (Heap Allocation) and use native types on the stack.

  2. Batch RPC request: Although pricing is local, the vault balance still needs to be synchronized. Use getMultipleAccounts to batch fetch all relevant Vault states to reduce network round trips.

  3. Pre-calculation: For fixed parameters like rates, parsing should be completed during the cold start phase, and not recalculated in every millisecond of the Hot Path.

6. Technical Demonstration: CPMM Pricing Logic (Python Version)

Although production environments pursue the ultimate performance of Rust, its core mathematical logic can be clearly demonstrated in Python:

# Simulating High-Performance Local Quote Calculation
def calculate_local_quote(amount_in, res_in, res_out, fee_pct=0.0025):
"""
CPMM Local Quote: x * y = k
"""
# Simulating U256 calculations to prevent overflow
fee_numerator = int(fee_pct * 10000)
fee_denominator = 10000

# 1. Calculate the effective input after deducting fees
amount_in_with_fee = amount_in * (fee_denominator - fee_numerator)

# 2. Calculate output based on the formula
numerator = amount_in_with_fee * res_out
denominator = (res_in * fee_denominator) + amount_in_with_fee

amount_out = numerator // denominator

# 3. Calculate Price Impact
price_impact = (amount_out / res_out) if res_out > 0 else 1

return amount_out, price_impact

# Simulation: 1 SOL exchanges for USDC, with 1000 SOL / 100,000 USDC in the pool
out, impact = calculate_local_quote(1 10*9, 1000 10*9, 100000 10*6)
print(f"[*] Estimated output: {out / 10**6} USDC")
print(f"[*] Price Impact: {impact:.4%}")

7. Conclusion: Computing Power Equals Profit

In the world of Solana MEV, local pricing ability determines your competitive scale.

  • Beginner players rely on RPC simulations and can only pick up the leftover soup.

  • Intermediate players implement CPMM localization.

  • Advanced players can precisely parse each Tick of CLMM and realize atomic arbitrage in conjunction with Jito.

Next Step Preview

Now that we have the "Scout" and "AMM Math", it's time to enter the most exciting part: how to formulate cross-DEX arbitrage strategies? In the face of complex situations with multiple paths and protocols, how do we find the most profitable route?

This article is written by Levi.eth. On Solana, every optimization of the mathematical formulas can translate into real on-chain profits.

JTO
JTOUSDT
0.4185
+24.81%
SOL
SOLUSDT
127.3
+2.81%