Skip to content

feat(studio): add Jupiter Perps scenario support - #36

Open
92Infinitus92 wants to merge 7 commits into
feat/scenarios/override/jupiter-perps-supportfrom
feat/jupiter-perps-support
Open

92Infinitus92 wants to merge 7 commits into
feat/scenarios/override/jupiter-perps-supportfrom
feat/jupiter-perps-support

Conversation

@92Infinitus92

Copy link
Copy Markdown
Collaborator

Adds Jupiter Perps to the scenario editor and the Market move preset.

  • The preset lists the JLP pool's markets by token, takes a typed custody address too, and moves that market's Doves price.
  • The Market move dialog and its adapter interface are shared code; the Manifest and Velocity PRs carry the same files.
  • Adds the protocol entry and one AI chip.

Tests: vitest, tsc (only the two existing vitest config errors), lint and prettier pass.

Backend: LimeChain/surfpool#49

@github-actions github-actions 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.

Summary

This PR adds a shared Market move preset: a dialog, an adapter interface and RPC helpers in lib/market-move.ts. It also adds a Jupiter Perps adapter. The adapter reads the JLP pool's custodies, labels each one by its mint symbol and writes a moved Doves AgPriceFeed price. Jupiter Perps is also added to the editor's enabled protocols, the protocol icons and the AI example chips.

The code is clean and well tested. Prices are handled with bigint math and rounded half up, the rounding is guarded against overflow and zero, and stale custom-address reads are ignored. I found no blocking bugs. Points to look at:

  • Unused shared code: readProgramAccounts, readWithClock, CLOCK_SYSVAR and I64_MAX aren't used by anything in this PR. They're probably for the Manifest and Velocity PRs, but if those land in a different order or get dropped, this is dead code. Consider adding them in the PR that first uses them.
  • Editor picker labels: ENABLED_PROTOCOLS now includes jupiter-perps and jupiter-perps-doves. The editor uses the raw template protocol string as the title, so the picker will show two separate lowercase entries ("jupiter-perps", "jupiter-perps-doves"). The other protocols show display names like "Phoenix Eternal". Consider grouping them the way KAMINO_PRODUCTS does, or mapping them to display titles.
  • Possible oracle cross-check (not verified): only the Doves price is rewritten (fetchBeforeUse: false). If the custody also checks the price against a second oracle or a maximum price error, or rejects stale feeds by max_price_age_sec, large moves or late replays may fail on-chain. It's worth confirming against the backend PR (surfpool#49).
  • Extra RPC call on reopen: when the dialog reopens, the markets effect runs once with the previous templates before setTemplates(null) takes effect. That fires a listMarkets call that is then cancelled.


// The Pool starts with its name as a Borsh string, then lists its custodies as a u32 count and pubkeys.
function poolCustodies(pool: Uint8Array): string[] {
const countOffset = 12 + dataView(pool).getUint32(8, true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minLength: 12 only guarantees the name length prefix. If the name length is corrupt or the account is truncated, getUint32(countOffset) throws a raw RangeError ("Offset is outside the bounds of the DataView") before the friendly length check below runs. Suggest checking pool.length >= countOffset + 4 first and throwing the same The JLP Pool is shorter… error.

});
};

const handleMoveChange = (event: ChangeEvent<HTMLInputElement>) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

handleMoveChange clears every error, including a failed listMarkets or template load. After the user edits the percentage, the dialog shows an empty, disabled market picker with no explanation. Consider keeping load errors in separate state from submit and read errors.

useEffect(() => {
if (!open) return;
let cancelled = false;
setTemplates(null);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When the dialog reopens, the markets effect below runs in the same commit using the previous templates (still non-null), so it starts a listMarkets RPC that is cancelled right away once templates becomes null. One fix is to reset templates and markets on close (in handleClose or a !open branch) instead of on open.

return value.map((account): RpcAccount | null => account && { ...account, data: decodeBase64(account.data[0]) });
}

export async function readProgramAccounts(rpcUrl: string, kind: AccountKind, dataSlice: Slice) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

readProgramAccounts, readWithClock, CLOCK_SYSVAR and I64_MAX have no users in this PR. If they're only for the Manifest and Velocity adapters, consider adding them in whichever PR first uses them, so this one doesn't ship untested dead exports.


async function post(url: string, body: string) {
const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body });
if (!response.ok) throw new Error((await response.text()) || `${url} answered ${response.status}`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For a non-OK response this throws the whole response.text() as the error message, which the dialog then shows. A proxy or RPC HTML error page would be dumped into the UI. Consider truncating it, or preferring the status message when the body isn't JSON or plain text.

@github-actions github-actions 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.

Summary

This PR adds a shared Market move preset (a dialog, an adapter interface and helpers in market-move.ts) plus a Jupiter Perps adapter. The adapter lists the JLP pool's custodies, resolves each custody's Doves AgPriceFeed, and writes a moved price override. It also registers jupiter-perps / jupiter-perps-doves in the editor, adds the protocol icon and adds one AI example chip.

Overall the PR is clean and well tested. The bigint percentage handling is exact, expectAccount checks owner, discriminator and length, and a request counter stops stale reads from landing after the protocol changes. A few points to look at:

  • Oracle staleness: with fetchBeforeUse: false, the override writes only price onto the feed copy loaded when the scenario was created. The perps program checks how old the oracle is. If Play runs well after creation, or after the surfnet clock moves forward, the feed's publish time/slot may be stale and trades could be rejected. Please confirm the jupiter-perps-doves-price template in the backend (surfpool#49) also bumps the timestamp, or document the limitation.
  • Unused shared exports: readProgramAccounts, readWithClock, I64_MAX and CLOCK_SYSVAR are not used by this PR. The PR body says the shared file is carried by the Manifest and Velocity PRs too, so whichever lands second or third will conflict unless the files match byte for byte. Consider landing the shared module once, on its own.
  • Unrelated CI change: the PR also adds .github/workflows/claude-review.yml (commit 49e3be0), which has nothing to do with Jupiter Perps. Consider splitting it into its own PR.

// The Pool starts with its name as a Borsh string, then lists its custodies as a u32 count and pubkeys.
function poolCustodies(pool: Uint8Array): string[] {
const countOffset = 12 + dataView(pool).getUint32(8, true);
const count = dataView(pool).getUint32(countOffset, true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

POOL.minLength is 12, but the name length read from offset 8 isn't bounds-checked before getUint32(countOffset). A truncated or odd pool account throws a raw RangeError: Offset is outside the bounds of the DataView instead of the friendly error on the next line. Check pool.length < countOffset + 4 first.

(await readPoolCustodies(rpcUrl)).map(({ custody, data }) => toMarket(custody, data, symbols)),
readMarket: async (rpcUrl, address, symbols) => {
const [account] = await readAccounts(rpcUrl, [address]);
return toMarket(address, expectAccount(account, address, CUSTODY), symbols);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

readMarket accepts any account owned by the perps program with the custody discriminator, but never checks that the custody belongs to JLP_POOL. The custody's pool pubkey (offset 8) is ignored. That's probably fine since JLP is currently the only pool, but a one-line check would make 'refusing one that is not a market' strictly true.

// The price is derived from the feed read below, which also loads it into the local VM. Play writes that
// copy; a refetch would put the derived price on a newer feed.
fetchBeforeUse: false,
listMarkets: async (rpcUrl, symbols) =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

With fetchBeforeUse: false, the override writes price on the feed snapshot taken at creation time. If the Doves feed's timestamp isn't refreshed as well (here or in the backend template), Jupiter Perps' oracle staleness check may reject the moved price once surfnet time has moved on. Please confirm that the backend template handles this.

label: 'Jupiter Perps Crash',
prompt: 'SOL crashes 20% on Jupiter Perps',
icon: '📉',
protocols: ['jupiter-perps', 'jupiter-perps-doves'],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

jupiter-perps-doves is not in PROTOCOLS, so buildAiPrompt and the chip UI filter it out and it does nothing here. It does stay in selectedProtocols as hidden state the user can't toggle off. Just use ['jupiter-perps'].

return value.map((account): RpcAccount | null => account && { ...account, data: decodeBase64(account.data[0]) });
}

export async function readProgramAccounts(rpcUrl: string, kind: AccountKind, dataSlice: Slice) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

readProgramAccounts, readWithClock, I64_MAX and CLOCK_SYSVAR are not used in this PR. They're dead code until the Manifest/Velocity PRs land, and they invite merge conflicts if those PRs carry slightly different copies. Consider landing the shared module once, on its own.

@github-actions github-actions 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.

Summary

This PR adds a Jupiter Perps adapter for a new shared Market move preset, plus the dialog, the shared market-move helpers, the protocol and icon entries, and one AI example chip. The code is clean and well tested, and the BigInt percentage math (parseMarketMove / moveValue) is exact and handles out-of-range moves properly.

Issues

  • Dialog can get stuck on "Loading markets…" after a protocol is picked. See the inline comment. This is the main issue to fix before merging.
  • Unrelated CI workflow: commit 49e3be0 adds .github/workflows/claude-review.yml, which has nothing to do with Jupiter Perps. Consider moving it to its own PR.
  • Shared code not used yet: readWithClock, readProgramAccounts, I64_MAX and CLOCK_SYSVAR are only used by tests in this PR (they're for the Manifest and Velocity adapters). That's fine since the files are shared, but whichever PR lands second has to reconcile identical new files. Merging the shared files once first would avoid churn.
  • Dialog state isn't reset when it closes: the market, move and custom market carry over to the next open. A pending readMarket can also still call setError/setCustomMarket after close. Both are minor.

const handleProtocolSelect = (selectedProtocol: string) => {
marketRequestRef.current++;
setProtocol(selectedProtocol);
setMarkets(null);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: setMarkets(null) here only works if the effect at L177 runs again, and that effect depends on adapter. The adapter objects are module constants, so adapter doesn't change when:

  • the user first picks the protocol that's already shown (protocol is null, so adapter falls back to availableAdapters[0], and with only Jupiter Perps that's always the case), or
  • the user picks the currently selected protocol again (Headless UI's controlled Listbox calls onChange even when the value is the same).

In both cases markets stays null for good: the Market picker is disabled with "Loading markets…" and can't be used until the dialog is reopened.

Fix: return early when selectedProtocol === adapter?.protocol, or don't clear markets here and let the effect handle it (for example by keying it on adapter.protocol plus a reload counter). A test that picks the already-selected protocol would catch this.


// The Pool starts with its name as a Borsh string, then lists its custodies as a u32 count and pubkeys.
function poolCustodies(pool: Uint8Array): string[] {
const countOffset = 12 + dataView(pool).getUint32(8, true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

POOL.minLength is 12, but nothing checks that countOffset + 4 <= pool.length before getUint32(countOffset). A short or corrupt pool with a large name length throws a raw RangeError: Offset is outside the bounds of the DataView instead of the clear message used on L43. Check the length before reading the count.

setError(null);
if (markets?.some((listed) => listed.value === address) || customMarket?.value === address) return;
adapter
.readMarket(rpcUrl, address, knownTokenSymbols(templates ?? []))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing cancels this read when the dialog closes, so a slow readMarket can call setError/setCustomMarket after close, and the result shows up on the next open. Consider bumping marketRequestRef in handleClose, or resetting the dialog state when open goes false.

@github-actions github-actions 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.

Overview

This PR adds a shared Market move preset (a dialog, an adapter interface, and RPC/byte helpers in lib/market-move.ts) plus a Jupiter Perps adapter. The adapter lists the JLP pool's custodies, resolves each one's Doves AG feed, and writes a moved price override. It also adds the jupiter-perps protocol entry and icon, an AI example chip, and a Claude review workflow.

Assessment

The code is clean and well tested. Prices are moved with bigint arithmetic, large values stay exact through toScenarioNumber and lossless serialization, and accounts are checked against their owner, discriminator and minimum length before any bytes are read. Stale market reads are dropped through the request-id ref. I found no blocking bugs. Notes:

  • Oracle staleness: the override changes only the Doves price, and fetchBeforeUse: false freezes the snapshot. If Perps checks the feed's age against the clock, a scenario played some time after it was created could be refused as stale. Please confirm that the backend template (surfpool#49) also refreshes the feed's timestamp.
  • Dialog state on reopen: protocol, market, customMarket and move survive close and reopen; only error is reset. That may be intended, but a custom market from an earlier session can still show as selected once the lists load again.
  • No progress shown for a typed address: after an address is pasted, nothing indicates that readMarket is running. The combobox shows nothing selected until the read resolves.
  • Shared code across three PRs: the dialog and market-move.ts are duplicated in the Manifest and Velocity PRs. Merging them in sequence will need care to avoid conflicts or drift. readProgramAccounts, readWithClock, I64_MAX and CLOCK_SYSVAR have no user in this PR.
  • Workflow: claude-review.yml has nothing to do with Jupiter Perps and might be better as its own PR. It is reasonably hardened: actions pinned by SHA, read-only token, fork PRs skipped, and refs passed through env.

},
buildOverrides: async (rpcUrl, market, move) => {
const [account] = await readAccounts(rpcUrl, [market.account]);
const price = moveValue(dataView(expectAccount(account, market.account, FEED)).getBigUint64(168, true), move);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Only price (offset 168) is moved; the feed's publish timestamp stays as it was in the snapshot. With fetchBeforeUse: false, a scenario played later could be refused by Perps' oracle staleness check, if it has one. Does the jupiter-perps-doves-price template on the backend also bump the timestamp? If not, it may be worth reading the clock here (e.g. with the unused readWithClock) and overriding the timestamp too.

fetchBeforeUse: false,
listMarkets: async (rpcUrl, symbols) =>
(await readPoolCustodies(rpcUrl)).map(({ custody, data }) => toMarket(custody, data, symbols)),
readMarket: async (rpcUrl, address, symbols) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

readMarket accepts any Custody account owned by the Perps program, not just the JLP pool's custodies. That's fine today, since only one pool exists, but say so in a comment or check membership if more pools are added.

if (!option || !adapter) return;
const address = option.value;
const requestId = ++marketRequestRef.current;
setMarket(address);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

While readMarket is running for a pasted address, selectedMarket is undefined, so the combobox clears and nothing shows progress. Consider a "Reading…" placeholder or a pending state so the address doesn't look ignored.

}, [open, studioUrl]);

useEffect(() => {
if (!open || !adapter || templates === null) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

On reopen, templates is reset but protocol, market, customMarket and move keep their old values. If the next session should start fresh, reset them in handleClose along with error.

<span className="min-w-0 flex-1">
<span className="block text-sm font-semibold text-zinc-100">Market move</span>
<span className="mt-1 block text-sm leading-5 text-zinc-500">
Move an order book, perps or oracle price by a percentage.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nit: the copy mentions order books and oracles, but this PR only ships the Perps adapter. It's fine once the Manifest and Velocity PRs land, but it overpromises if this one merges alone.

@github-actions github-actions 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.

Summary

This PR adds Jupiter Perps to the scenario editor. It turns the Kamino-only grouping into a general PRODUCT_GROUPS list, so Perps and Doves sit behind one icon. It also adds a Market move preset: a shared dialog plus an adapter interface, with one Jupiter Perps adapter that reads the JLP pool's custody list and rewrites the Doves AgPriceFeed price. The rest is an AI chip and icon mappings.

Overall the code is clean. The adapter checks the owner, discriminator and length of every account before decoding it. Stale market reads are dropped through a request id, and the price math uses exact bigint fractions. Nothing here blocks the merge. Notes:

  • Unrelated file: .github/workflows/claude-review.yml adds CI and has nothing to do with Jupiter Perps. It should go in its own PR so it can be reviewed and reverted on its own.
  • Unused shared code: market-move.ts exports readWithClock, readProgramAccounts, CLOCK_SYSVAR and I64_MAX, and nothing in this PR uses them (they're meant for the Manifest and Velocity PRs). Since the PR body says the three PRs carry the same files, whichever merges second will conflict on them. Landing the shared dialog and lib once, or dropping the unused exports here, would avoid that.
  • Preset copy: the card says "Move an order book, perps or oracle price", but only the Perps adapter ships here. Until the other adapters land, the order book option doesn't exist.
  • Tests: coverage of the parsing and math, the adapter, and the dialog's race handling looks good.

// HANDLERS
const handleClose = () => {
if (isCreating) return;
marketRequestRef.current++;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

handleClose only clears error. market, customMarket, move and protocol all survive a close. On reopen the previous market comes back selected after listMarkets resolves, even though the templates and markets are fetched again. If that's not intentional, reset these here (or when open turns true) so each open starts fresh.

if (!option || !adapter) return;
const address = option.value;
const requestId = ++marketRequestRef.current;
setMarket(address);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When a custom address is picked, market is set right away but selectedMarket stays undefined until readMarket resolves. The combobox goes blank and the submit button turns disabled, with nothing telling the user a read is running. A small isReadingMarket state (placeholder 'Reading market…') would make this clearer, especially on a slow RPC.

}

/** Reads an account together with the Clock sysvar, the time and slot programs see as now. */
export async function readWithClock(rpcUrl: string, address: string) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

readWithClock, readProgramAccounts (L116), CLOCK_SYSVAR and I64_MAX aren't used anywhere in this PR. Consider leaving them for the PRs that use them, so nobody has to maintain unused code and the sibling PRs don't hit merge conflicts on it.

},
buildOverrides: async (rpcUrl, market, move) => {
const [account] = await readAccounts(rpcUrl, [market.account]);
const price = moveValue(dataView(expectAccount(account, market.account, FEED)).getBigUint64(168, true), move);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Only price is scaled. That's correct as long as the Doves expo stays the same, but the price is derived from a feed the surfnet just loaded. If the scenario is played much later with fetchBeforeUse: false, the feed's timestamp may be stale, and Perps could reject the price as too old. Worth confirming the backend template (surfpool#49) also refreshes the feed's timestamp field, or noting the limitation.

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