Repository navigation
feat(studio): add PancakeSwap scenario presets - #22
92Infinitus92 merged 16 commits into
Conversation
093bd17 to
7ab34f3
Compare
Tests were not run because dependencies are not installed. |
The test suite could not be run because dependencies are absent; the numeric boundary example was reproduced independently. |
There was a problem hiding this comment.
Summary
This PR adds a PancakeSwap preset card and dialog with two modes: CLMM price shock and fee tier. It also adds two goal-level AI chips, the protocol icon and editor wiring, and a Claude review workflow.
The price-shock mode works in the browser: it reads the pool, computes the new sqrt price and tick, walks the tick arrays to recompute active liquidity, and refuses a shock whose destination tick array doesn't exist. The structure is clean and the tests cover the layout offsets. The liquidity-crossing logic is correct: ticks in (old, new] are added when the price rises and ticks in (new, old] are subtracted when it falls, and the i128 liquidity_net decode is signed correctly. The "safe factor" suggestion also rounds toward the inside of the array.
Main concerns
- Float precision in the tick and sqrt price math.
sqrt_price_x64can be as large as about 2^96 but is handled as a JSNumber.tick_currentcomes fromMath.log, so near a tick boundary the writtentick_currentcan disagree with the program's ownget_tick_at_sqrt_price. That inconsistent state matters because swaps start fromtick_current, and the liquidity recompute depends on the same tick. - Unbounded path walk. For extreme factors on small tick spacings, the path can cover thousands of tick arrays. Each one costs a PDA derivation and roughly 10 KB of RPC data, fetched in sequential batches. Consider capping the path or failing early.
- Dialog state persists across opens. Pool, factor, fee and error stay set after closing; this is minor and probably acceptable.
- CI workflow.
.github/workflows/claude-review.ymlis unrelated to the feature and would be better in its own PR. As written it looks safe: fork PRs are skipped, the PR body goes into an action input rather than a shell, and the job token is read-only.
| const sqrtPriceX64 = | ||
| view.getBigUint64(SQRT_PRICE_X64_OFFSET, true) | (view.getBigUint64(SQRT_PRICE_X64_OFFSET + 8, true) << BigInt(64)); | ||
|
|
||
| const shocked = Math.round(Number(sqrtPriceX64) * Math.sqrt(priceFactor)); |
There was a problem hiding this comment.
Number(sqrtPriceX64) loses precision above 2^53, and Q64 sqrt prices are usually around 2^64 or higher. shocked is then a rounded double, so BigInt(shocked) is only accurate to about 1 part in 2^53. That's fine for the price itself, but see the next comment about tick_current.
| `price factor moves sqrt_price_x64 to ${BigInt(shocked)}, outside the range the program accepts [${MIN_SQRT_PRICE_X64}, ${MAX_SQRT_PRICE_X64})` | ||
| ); | ||
| } | ||
| const newTickCurrent = Math.floor((2 * Math.log(shocked / Q64)) / Math.log(TICK_BASE)); |
There was a problem hiding this comment.
tick_current is derived with floating-point Math.log. When shocked falls close to a tick boundary, floor can return tick ±1 relative to the program's get_tick_at_sqrt_price. That writes an inconsistent (sqrt_price_x64, tick_current) pair, and the first swap may then skip or double-cross a tick. The liquidity recompute also uses this tick.
Suggested fix: port the integer get_sqrt_price_at_tick (it's small), then adjust the tick by ±1 until sqrt_at(tick) <= shocked < sqrt_at(tick+1) holds. Alternatively, snap shocked to sqrt_at(newTick).
| // Every array from the current one to the destination, in the direction of the move. | ||
| const step = newTickCurrent >= oldTickCurrent ? TICK_ARRAY_SIZE * tickSpacing : -TICK_ARRAY_SIZE * tickSpacing; | ||
| const pathStarts = [tickArrayStartIndex(oldTickCurrent, tickSpacing)]; | ||
| while (pathStarts[pathStarts.length - 1] !== startIndex) pathStarts.push(pathStarts[pathStarts.length - 1] + step); |
There was a problem hiding this comment.
The number of path arrays isn't bounded. For example, factor 1e-6 with tick spacing 1 moves about 138k ticks, which is about 2,300 tick arrays. That means 2,300 PDA derivations followed by about 23 sequential getMultipleAccounts calls returning roughly 23 MB.
Consider capping the path length and returning a clear error, or reading the pool's tick array bitmap so only initialized arrays are fetched.
|
|
||
| async function fetchSurfnetAccounts(rpcUrl: string, accounts: string[]): Promise<(PoolAccount | null)[]> { | ||
| const found: (PoolAccount | null)[] = []; | ||
| for (let start = 0; start < accounts.length; start += 100) { |
There was a problem hiding this comment.
These batches run sequentially. Combined with the unbounded path above, a large shock can block the dialog for a long time with no progress shown. The batches could run with Promise.all, or the path could be capped upstream.
| protocols: ['pancakeswap'], | ||
| }, | ||
| { | ||
| label: 'PancakeSwap Swap Freeze', |
There was a problem hiding this comment.
Please confirm the backend (LimeChain/surfpool#24) exposes a pool-status/swap-disable template that the AI can reach. The dialog only offers price-shock and fee-tier, so if no such template exists this chip will produce a failed or hallucinated scenario.
…ace the price-shock chip
… the fee spike chip
eebcde9 to
bb51e8d
Compare
There was a problem hiding this comment.
Overview
This PR adds a PancakeSwap card under Scenario presets. It opens a dialog with two modes:
- CLMM price shock: reads the pool over RPC, computes the new sqrt price, tick and active liquidity in the browser, then POSTs a template override.
- CLMM fee tier: fills the fee-tier picker from the backend template's constants.
It also adds a goal-level AI chip and the PancakeSwap icon.
I checked the PoolState offsets (235/237/253/269) and the TickState layout (liquidity_net i128 at +4, liquidity_gross at +20, 168-byte stride) against the Raydium-style layout, and they look right. The liquidity-crossing logic is also correct: ticks in (low, high], add net going up, subtract it going down, and missing arrays are treated as empty. The code is clean and the tests are focused.
Issues
- Float tick math (main risk):
tick_currentcomes fromMath.logon a value already rounded to a double. When the shocked price lands very close to a tick boundary, the computed tick can be off by one from the program's exactget_tick_at_sqrt_price. The pool would then be written with an inconsistent(sqrt_price_x64, tick_current)pair. See the inline comment. - Extreme factors: with tick spacing 1, a factor such as
1e-6or1e6crosses roughly 2,300 tick arrays. That means thousands of async PDA derivations and about 23 sequentialgetMultipleAccountscalls, with no progress shown. Consider capping the path length or the factor, or showing a clearer loading state. - RPC response not checked:
fetchSurfnetAccountsnever checks that the response length matches the request length, so a short response would misalignpathAccounts. See inline. - Unrelated CI change: the CI workflow change (
claude-review.yml) has nothing to do with the feature and would be better in its own PR. - Dialog state persists: fields are not cleared when the dialog closes, so reopening it shows the previous pool, factor and fee. This may be fine, but commit e253a61 says the dialog opens with empty fields, and that only holds on first mount.
| `price factor moves sqrt_price_x64 to ${BigInt(shocked)}, outside the range the program accepts [${MIN_SQRT_PRICE_X64}, ${MAX_SQRT_PRICE_X64})` | ||
| ); | ||
| } | ||
| const newTickCurrent = Math.floor((2 * Math.log(shocked / Q64)) / Math.log(TICK_BASE)); |
There was a problem hiding this comment.
The tick is derived with floating point: Number(sqrtPriceX64) keeps 53 bits of a ~96-bit value, and then Math.log is applied. When the shocked price falls within about 1e-9 ticks of a boundary, floor can land one tick away from the program's exact get_tick_at_sqrt_price. The pool would then get a tick_current that doesn't match sqrt_price_x64, and the next swap would cross ticks incorrectly.
Suggested fix: once the tick is computed, recompute sqrt(1.0001^tick)·2^64 and sqrt(1.0001^(tick+1))·2^64 with BigInt or the program's exact algorithm, and adjust the tick by ±1 (or clamp shocked into [sqrtAt(tick), sqrtAt(tick+1))) so the pair is guaranteed consistent.
| // Every array from the current one to the destination, in the direction of the move. | ||
| const step = newTickCurrent >= oldTickCurrent ? TICK_ARRAY_SIZE * tickSpacing : -TICK_ARRAY_SIZE * tickSpacing; | ||
| const pathStarts = [tickArrayStartIndex(oldTickCurrent, tickSpacing)]; | ||
| while (pathStarts[pathStarts.length - 1] !== startIndex) pathStarts.push(pathStarts[pathStarts.length - 1] + step); |
There was a problem hiding this comment.
The path size has no upper bound. Large shocks on spacing-1 pools produce thousands of arrays, and the next line derives a PDA for each one with Promise.all; the caller then fetches them in sequential batches of 100. Consider capping the number of arrays crossed (and failing with a clear message) or limiting the factor range.
| result?: { value: ({ owner: string; data: [string, string] } | null)[] }; | ||
| }; | ||
| if (result.error) throw new Error(`Failed to read accounts from the surfnet: ${result.error.message}`); | ||
| for (const value of result.result?.value ?? []) { |
There was a problem hiding this comment.
If result.result is missing or returns fewer entries than were requested, found silently ends up shorter than accounts. The caller indexes pathAccounts by position (and buildPancakeswapPriceShockScenario uses pathAccounts[length-1] as the destination array), so a short response misaligns the arrays. That could produce a false "does not exist" error or the wrong liquidity. Throw when value.length !== batch.length.
| } | ||
| // Rounded toward the array's interior, so the suggestion itself lands inside it. | ||
| const exact = TICK_BASE ** (bound - oldTickCurrent) * 1e6; | ||
| const safeFactor = ((priceFactor > 1 ? Math.floor(exact) : Math.ceil(exact)) / 1e6).toFixed(6); |
There was a problem hiding this comment.
Minor: safeFactor is exact only when the computed tick for the shocked price is exact. Because of the float rounding in line 75, a factor right at exact can still land one tick outside the array. Rounding one more step inward (for example, subtracting or adding 1e-6) would make the suggested factor reliable.
# Conflicts: # apps/studio/src/components/svm/scenario-editor.tsx # apps/studio/src/components/svm/scenario-presets.test.tsx # apps/studio/src/components/svm/scenario-presets.tsx # apps/studio/src/components/svm/scenarios-bento.tsx # apps/studio/src/components/svm/scenarios-bento.types.ts # apps/studio/src/lib/protocol-icons.ts # apps/studio/src/lib/scenarios-api.test.ts # apps/studio/src/lib/scenarios-api.ts
There was a problem hiding this comment.
Summary
This PR adds a PancakeSwap CLMM preset to Studio. A dialog offers two modes:
- Price shock: reads the pool over RPC, computes the new
sqrt_price_x64,tick_currentand active liquidity in the browser, and refuses the shock when the destination tick array doesn't exist. - Fee tier: overrides the pool's
AmmConfig.
The PR also adds a goal-level AI chip and the protocol icon.
Overall the code is clean and well tested. The liquidity-crossing logic is correct: it crosses (old, new] going up and (new, old] going down, adds or subtracts the signed i128 liquidity_net accordingly, and handles missing intermediate arrays. Most of my notes are about numerical robustness and validation.
Notes
- Floating-point tick derivation. The new tick comes from
Math.logon a value already rounded to an f64 (see the inline comment). The program requiressqrt_price_at(tick) <= sqrt_price < sqrt_price_at(tick+1). Near a tick boundary the float result can be off by one, which would write an inconsistent(sqrt_price, tick)pair. It's worth checking with an exact integerget_sqrt_price_at_tickport, or nudging the price inside the tick. - Unrelated CI change.
.github/workflows/claude-review.yml(commits9e12131,1ed0661) has nothing to do with the PancakeSwap feature. It would be easier to review and revert as its own PR. - Dialog state survives reopening. The dialog stays mounted, so pool, factor and fee keep their last values after a successful create followed by a reopen. If "open with empty fields" was the goal of
e253a61, reset the state inhandleClose/onCreated, or key the dialog onopen. - Very large or small factors. These still walk every tick array on the path. For example, a factor of
1e-20with tick spacing 1 means about 7.7k PDA derivations and 77 sequential RPC batches before any error appears. A sanity cap on the number of path arrays, with a clear error, would help.
| const sqrtPriceX64 = | ||
| view.getBigUint64(SQRT_PRICE_X64_OFFSET, true) | (view.getBigUint64(SQRT_PRICE_X64_OFFSET + 8, true) << BigInt(64)); | ||
|
|
||
| const shocked = Math.round(Number(sqrtPriceX64) * Math.sqrt(priceFactor)); |
There was a problem hiding this comment.
Number(sqrtPriceX64) drops the u128 to 53 bits of precision, and the tick on line 81 then comes from Math.log of that float. Near a tick boundary newTickCurrent can be off by one relative to newSqrtPriceX64, which breaks the program's invariant sqrt_price_at(tick) <= sqrt_price < sqrt_price_at(tick+1). Suggestion: compute the tick, then check it against an exact BigInt get_sqrt_price_at_tick port and adjust by ±1. Alternatively, do the multiplication in BigInt (e.g. scale Math.sqrt(factor) to a fixed-point BigInt).
| // Every array from the current one to the destination, in the direction of the move. | ||
| const step = newTickCurrent >= oldTickCurrent ? TICK_ARRAY_SIZE * tickSpacing : -TICK_ARRAY_SIZE * tickSpacing; | ||
| const pathStarts = [tickArrayStartIndex(oldTickCurrent, tickSpacing)]; | ||
| while (pathStarts[pathStarts.length - 1] !== startIndex) pathStarts.push(pathStarts[pathStarts.length - 1] + step); |
There was a problem hiding this comment.
There's no limit on the length of the path. Extreme factors with a small tick spacing produce thousands of PDA derivations and sequential 100-account RPC batches before the user sees anything. Consider capping pathStarts.length and throwing a descriptive error.
| ): Promise<PancakeswapScenarioResult> { | ||
| const normalizedPool = pool.trim(); | ||
| if (!isAddress(normalizedPool)) throw new Error(`Invalid pool address: ${normalizedPool}`); | ||
| const bps = feeBps.trim(); |
There was a problem hiding this comment.
The exported function relies on the dialog for validation. Called directly, '' turns into a fee of 0, and 'abc' turns into NaN and then null in JSON. Mirror the dialog's /^\d+$/ and < 10000 check here, as createPancakeswapPriceShockScenario already does with validatePriceFactor.
|
|
||
| const scenario = pancakeswapScenario( | ||
| `PancakeSwap CLMM Fee Tier ${bps} bps (${normalizedPool.slice(0, 6)}…)`, | ||
| `Change the trade fee of the fee tier PancakeSwap CLMM pool ${normalizedPool} points to. Every pool on that tier is affected.`, |
There was a problem hiding this comment.
This description is hard to parse ("the fee tier PancakeSwap CLMM pool X points to"). Suggested wording: Set the trade fee to ${bps} bps on the AmmConfig ${config} used by PancakeSwap CLMM pool ${normalizedPool}. Every pool on that tier is affected. Naming the config and the bps value also makes the scenario self-describing.
| const handlePriceFactorChange = resettingError(setPriceFactor); | ||
| const handleFeeBpsChange = resettingError(setFeeBps); | ||
|
|
||
| const handleClose = () => { |
There was a problem hiding this comment.
The fields aren't cleared on close or after a successful create. The component stays mounted in ScenariosBento, so reopening it shows the previous pool, factor and fee. If the dialog is meant to open empty, reset the state here and in the success path.
…, write the mid-tick price, cap the path and validate the fee
…swap # Conflicts: # apps/studio/src/components/svm/scenario-editor.tsx # apps/studio/src/components/svm/scenario-presets.test.tsx # apps/studio/src/components/svm/scenario-presets.tsx # apps/studio/src/components/svm/scenarios-bento.tsx # apps/studio/src/components/svm/scenarios-bento.types.ts # apps/studio/src/lib/scenarios-api.test.ts # apps/studio/src/lib/scenarios-api.ts
Studio side of the PancakeSwap scenario templates (backend: LimeChain/surfpool#24).
mode POSTs a plain template scenario to
/v1/scenarios. The price-shock mode reads thepool over RPC, computes the coupled sqrt price and tick in the browser, derives the tick array PDA and
refuses the shock when that array does not exist on chain (the error names a factor that
works), so no backend builder or MCP tool is needed.
template id.
Tests: the math and layout offsets against the bundled IDL, dialog and preset tests with
vitest;
tscand lint clean. Every mode was exercised against a forked surfnet with areal transaction after the scenario played.