From 02a844dd5feaa495e8dae175f663058d7f4d6109 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 14:50:10 +0200 Subject: [PATCH 1/6] feat(studio/scenarios): type the account of an override whose template names none --- .../components/svm/scenario-editor.test.tsx | 79 ++++++++++++++++++- .../src/components/svm/scenario-editor.tsx | 79 ++++++++++++++++--- 2 files changed, 144 insertions(+), 14 deletions(-) diff --git a/apps/studio/src/components/svm/scenario-editor.test.tsx b/apps/studio/src/components/svm/scenario-editor.test.tsx index 8f3c346f..2a82a9ea 100644 --- a/apps/studio/src/components/svm/scenario-editor.test.tsx +++ b/apps/studio/src/components/svm/scenario-editor.test.tsx @@ -104,14 +104,14 @@ async function openEditor( fireEvent.click(await screen.findByText(template.name)); } -const savedOverride = async () => { - fireEvent.click(await screen.findByRole('button', { name: 'Update Action' })); +const savedOverride = async (button = 'Update Action') => { + fireEvent.click(await screen.findByRole('button', { name: button })); const patch = await waitFor(() => { const call = fetchMock.mock.calls.find(([, init]) => init?.method === 'PATCH'); expect(call).toBeDefined(); return call!; }); - return JSON.parse(patch[1].body).overrides[0]; + return JSON.parse(patch[1].body).overrides.at(-1); }; const pda = { pda: { programId: 'pool-program', seeds: [{ string: 'pool' }, { propertyRef: 'mint' }] } }; @@ -367,6 +367,79 @@ it('keeps the later of two saved overrides reopened before the first one loaded' expect(screen.getByPlaceholderText('Enter quoteLotCollateral...')).toHaveValue(2); }); +const TRADER = 'HB66UQf7Bv82q9VPhg9Hz6RcDaTMY1yJm8KVDA8VG7Gp'; +const OTHER_TRADER = '6tgCsPZqZi4rcQWLLgoMHE1XAnRqA7mYYRByGUYxyFwB'; +const typedAccountTemplate = { + ...collateralTemplate, + id: 'typed-collateral', + name: 'Typed collateral', + address: { pubkey: '' }, +}; +const collateral = () => screen.getByPlaceholderText('Enter quoteLotCollateral...'); +const readAccounts = () => rpcParams().map(([pubkey]) => pubkey); + +const mockTraderAccount = (...templates: any[]) => + fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { + const pubkey = url === 'http://rpc' ? JSON.parse(`${init?.body}`).params[0] : undefined; + const value = pubkey === TRADER ? { data: { parsed: { traderState: { quoteLotCollateral: 42 } } } } : null; + return { ok: true, json: async () => (url.endsWith('/templates') ? templates : { result: { value } }) }; + }); + +const pickTypedAccountTemplate = async () => { + mockTraderAccount(collateralTemplate, typedAccountTemplate); + renderEditor(stepAction(collateralTemplate)); + fireEvent.click(await screen.findByTitle(`Phoenix Eternal: ${collateralTemplate.name}`)); + fireEvent.click(await screen.findByText('Phoenix Eternal', { selector: 'span' })); + await screen.findByPlaceholderText('Enter quoteLotCollateral...'); + expect(screen.queryByLabelText('Account')).not.toBeInTheDocument(); + fireEvent.click(await screen.findByRole('heading', { name: typedAccountTemplate.name })); + return screen.findByLabelText('Account'); +}; + +it('adds an override of a template without an address on the account typed for it', async () => { + const account = await pickTypedAccountTemplate(); + expect(account).toHaveValue(''); + expect(readAccounts()).toEqual(['trader']); + + fireEvent.change(account, { target: { value: ` ${TRADER} ` } }); + await waitFor(() => expect(collateral()).toHaveValue(42)); + fireEvent.change(collateral(), { target: { value: '7' } }); + + expect(await savedOverride('Add to Selected Slot')).toMatchObject({ + templateId: typedAccountTemplate.id, + account: { pubkey: TRADER }, + values: { 'traderState.quoteLotCollateral': 7 }, + }); + expect(readAccounts()).toEqual(['trader', TRADER]); +}); + +it('keeps an override of a template without an address from being saved without a valid account', async () => { + const account = await pickTypedAccountTemplate(); + const save = screen.getByRole('button', { name: 'Add to Selected Slot' }); + expect(save).toBeDisabled(); + + fireEvent.change(account, { target: { value: `${TRADER}.` } }); + expect(screen.getByRole('status')).toHaveTextContent('Not a valid Solana address.'); + expect(save).toBeDisabled(); + expect(readAccounts()).toEqual(['trader']); +}); + +it('shows and reads the saved account of a reopened override, and clears the fields for an account with no data', async () => { + mockTraderAccount(typedAccountTemplate); + renderEditor(stepAction(typedAccountTemplate, { pubkey: TRADER }, { 'traderState.quoteLotCollateral': 5 })); + fireEvent.click(await screen.findByTitle(`Phoenix Eternal: ${typedAccountTemplate.name}`)); + fireEvent.click(await screen.findByText(typedAccountTemplate.name)); + + const account = await screen.findByLabelText('Account'); + expect(account).toHaveValue(TRADER); + await waitFor(() => expect(collateral()).toHaveValue(5)); + + fireEvent.change(account, { target: { value: OTHER_TRADER } }); + await waitFor(() => expect(collateral()).toHaveValue(null)); + expect((await savedOverride()).account).toEqual({ pubkey: OTHER_TRADER }); + expect(readAccounts()).toEqual([TRADER, OTHER_TRADER]); +}); + it('steps forward to the slot after the processed one, which surfnet reads ahead of the finalized default', async () => { fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { const body = typeof init?.body === 'string' ? JSON.parse(init.body) : {}; diff --git a/apps/studio/src/components/svm/scenario-editor.tsx b/apps/studio/src/components/svm/scenario-editor.tsx index 1bc5ad1d..0af49326 100644 --- a/apps/studio/src/components/svm/scenario-editor.tsx +++ b/apps/studio/src/components/svm/scenario-editor.tsx @@ -25,6 +25,7 @@ import { StopIcon, TrashIcon, } from '@heroicons/react/24/solid'; +import { PublicKey } from '@solana/web3.js'; import { logger } from '@surfpool/shared'; import { Combobox, @@ -152,6 +153,15 @@ const PAUSED_CLOCK_WARNING = const leavesAccountToOverride = (address: any) => !!address && typeof address === 'object' && !address.pda && !(address.pubkey || address.address || address.value); +const isSolanaAddress = (value: string) => { + try { + new PublicKey(value); + return true; + } catch { + return false; + } +}; + export default function ScenarioEditor({ scenarioId = 'default', scenarioName = 'Scenario', @@ -173,6 +183,7 @@ export default function ScenarioEditor({ // asset - SOL is 3 on the Main Market, USDC 13 - so the index has to be selectable. const [arrayEntryIndex, setArrayEntryIndex] = useState>({}); const [fetchBeforeUse, setFetchBeforeUse] = useState(false); + const [typedAccount, setTypedAccount] = useState(''); const [loadingAccountData, setLoadingAccountData] = useState(false); const [showProtocolPanel, setShowProtocolPanel] = useState(false); const [slots, setSlots] = useState([]); @@ -189,6 +200,10 @@ export default function ScenarioEditor({ const [editingAction, setEditingAction] = useState<{ slotId: string; actionIndex: number } | null>(null); const [dynamicOptions, setDynamicOptions] = useState>({}); + const needsTypedAccount = leavesAccountToOverride(selectedAction?.template?.address); + const typedAccountPubkey = typedAccount.trim(); + const hasTypedAccount = isSolanaAddress(typedAccountPubkey); + const accountRequestRef = useRef(0); // A ref, so a second click sees the Step in flight before the next render const steppingRef = useRef(false); @@ -649,6 +664,7 @@ export default function ScenarioEditor({ setModifiedFields(new Set()); // Clear modified fields when loading new action setArrayEntryIndex({}); setFetchBeforeUse(false); // Reset fetch before use toggle + setTypedAccount(accountPubkey ?? ''); if (!action.template?.idl || !action.template?.address) { console.warn('Action template missing IDL or address'); @@ -672,6 +688,10 @@ export default function ScenarioEditor({ } // A PDA template, or one that leaves the account to the override, reads the saved account. if (accountPubkey && !addressString) addressString = accountPubkey; + if (!addressString && leavesAccountToOverride(action.template.address)) { + setLoadingAccountData(false); + return; + } // Step 1: Fetch account info, parsed as JSON when the template edits account fields logger.log('🔍 Fetching account info for address:', addressString); @@ -724,6 +744,15 @@ export default function ScenarioEditor({ } }; + // The read fills the fields and pulls the account into the local VM, without which Play skips it + const handleTypedAccountChange = (event: React.ChangeEvent) => { + const pubkey = event.target.value.trim(); + setTypedAccount(event.target.value); + if (selectedAction && pubkey !== typedAccountPubkey && isSolanaAddress(pubkey)) { + handleActionSelect(selectedAction, pubkey); + } + }; + // Filter actions in protocol panel, narrowed to the chosen product when there is one const filteredActions = (selectedProduct ?? selectedProtocol)?.actions.filter((action) => { @@ -803,7 +832,9 @@ export default function ScenarioEditor({ overrides: accountData, modifiedFields: Array.from(modifiedFields), fetchBeforeUse: fetchBeforeUse, - account: action.template?.address, + account: leavesAccountToOverride(action.template?.address) + ? { pubkey: typedAccountPubkey } + : action.template?.address, }, ], }; @@ -843,15 +874,12 @@ export default function ScenarioEditor({ overrides: accountData, modifiedFields: Array.from(modifiedFields), fetchBeforeUse: fetchBeforeUse, - // A template with no address keeps the account the override was saved for, such as a trader - // given to a preset. Any other address, a PDA included, comes from the template, so edited seed - // fields such as a token or fee tier pick the new account. - account: - leavesAccountToOverride(action.template?.address) && - existingAction.actionId === action.id && - existingAction.account?.pubkey - ? existingAction.account - : action.template?.address, + // A template with no address takes the typed account, which reopening fills with the one the + // override was saved for, such as a trader given to a preset. Any other address, a PDA included, + // comes from the template, so edited seed fields such as a token or fee tier pick the new account. + account: leavesAccountToOverride(action.template?.address) + ? { pubkey: typedAccountPubkey } + : action.template?.address, } : existingAction ), @@ -1937,6 +1965,32 @@ export default function ScenarioEditor({
{selectedAction ? ( <> + {needsTypedAccount && ( +
+ + + {!!typedAccountPubkey && !hasTypedAccount && ( +

+ Not a valid Solana address. +

+ )} +
+ )}

@@ -2724,9 +2778,12 @@ export default function ScenarioEditor({ setModifiedFields(new Set()); setArrayEntryIndex({}); setFetchBeforeUse(false); + setTypedAccount(''); } }} - disabled={!selectedSlotId || !selectedAction} + disabled={ + !selectedSlotId || !selectedAction || (needsTypedAccount && !hasTypedAccount) + } className="w-[300px] rounded-lg bg-yellow-500 px-6 py-3 font-semibold text-zinc-900 transition-all hover:bg-yellow-400 disabled:cursor-not-allowed disabled:opacity-50" > {editingAction From a27b0e7ae957ffc7af3592ec2f525fab1e02189c Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 14:50:11 +0200 Subject: [PATCH 2/6] ci: add Claude pull request reviews --- .github/workflows/claude-review.yml | 141 ++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 .github/workflows/claude-review.yml diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml new file mode 100644 index 00000000..844c44d6 --- /dev/null +++ b/.github/workflows/claude-review.yml @@ -0,0 +1,141 @@ +name: Perform a code review when a pull request is created. +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +jobs: + claude: + # Skip drafts, and skip fork PRs: on `pull_request` they don't get the + # ANTHROPIC_API_KEY secret, so the review would only fail. + if: >- + !github.event.pull_request.draft && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + structured_output: ${{ steps.run_claude.outputs.structured_output }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + # Explicitly check out the PR's merge commit. + ref: refs/pull/${{ github.event.pull_request.number }}/merge + persist-credentials: false + + - name: Pre-fetch base and head refs for the PR + env: + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + # Pass GitHub expressions through env and quote shell expansions. + git fetch --no-tags origin \ + "$PR_BASE_REF" \ + "+refs/pull/$PR_NUMBER/head" + + # If you want Claude to build and run code, install any dependencies that + # need to be downloaded before the "Run Claude" step, and add the commands + # it may run to --allowedTools below (e.g. "Bash(npm test:*)"). Any tool + # not listed there is denied. + + - name: Run Claude + id: run_claude + uses: anthropics/claude-code-action@86d88e619d8e6caf07b5c3944dd14f441c533718 # v1.0.243 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + # Use this job's read-only token instead of the Claude GitHub App, + # which needs `id-token: write` and would get write access. + github_token: ${{ github.token }} + prompt: | + This is PR #${{ github.event.pull_request.number }} for ${{ github.repository }}. + + Review ONLY the changes introduced by the PR, so consider: + git log --oneline ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} + git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} + + Suggest any improvements, potential bugs, or issues. + Be concise and specific in your feedback. + + Return your review in two parts: + - `summary`: a short Markdown overview of the PR and your overall assessment. + - `comments`: one entry per specific issue, anchored to the line it concerns. + `path` is relative to the repository root. `line` is the line number in + the PR head version of the file (${{ github.event.pull_request.head.sha }}), + and must be a line shown in the diff above. The working tree is the merge + commit, so its line numbers can differ; check them with + `git show ${{ github.event.pull_request.head.sha }}:`. + Put issues that don't belong to a single line in `summary` instead. + + Pull request title and body: + ---- + ${{ github.event.pull_request.title }} + ${{ github.event.pull_request.body }} + claude_args: | + --allowedTools "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*),Bash(git show:*)" + --json-schema '{ + "type": "object", + "properties": { + "summary": { + "type": "string", + "description": "Overall review as Markdown, posted as the review body." + }, + "comments": { + "type": "array", + "description": "Inline comments, each anchored to one line of the PR diff.", + "items": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "File path relative to the repository root." }, + "line": { "type": "integer", "minimum": 1, "description": "Line number in the PR head version of the file. Must be within the diff." }, + "body": { "type": "string", "description": "The comment, as Markdown." } + }, + "required": ["path", "line", "body"] + } + } + }, + "required": ["summary", "comments"] + }' + + post_feedback: + runs-on: ubuntu-latest + needs: claude + if: needs.claude.outputs.structured_output != '' + permissions: + issues: write + pull-requests: write + steps: + - name: Report Claude feedback + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + env: + CLAUDE_STRUCTURED_OUTPUT: ${{ needs.claude.outputs.structured_output }} + with: + github-token: ${{ github.token }} + script: | + const { summary = '', comments = [] } = JSON.parse(process.env.CLAUDE_STRUCTURED_OUTPUT); + const pr = context.payload.pull_request; + if (!summary.trim() && comments.length === 0) { + core.info('Claude returned an empty review; nothing to post.'); + return; + } + + try { + await github.rest.pulls.createReview({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pr.number, + commit_id: pr.head.sha, + event: 'COMMENT', + body: summary.trim() || 'See inline comments.', + comments: comments.map(({ path, line, body }) => ({ path, line, side: 'RIGHT', body })), + }); + } catch (error) { + // GitHub rejects the whole review if any comment points outside the + // diff. Fall back to a single PR comment so no feedback is lost. + core.warning(`Could not post inline review (${error.message}); posting a plain comment instead.`); + const details = comments.map(({ path, line, body }) => `**\`${path}:${line}\`**\n\n${body}`); + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pr.number, + body: [summary.trim(), ...details].filter(Boolean).join('\n\n---\n\n'), + }); + } From 205a3da7a28674b24a0401d0b3737fba5a63ec6f Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Mon, 9 Nov 2026 14:54:11 +0200 Subject: [PATCH 3/6] feat(studio/scenarios): show the override account like the editor's other pickers --- .../components/svm/scenario-editor.test.tsx | 1 + .../src/components/svm/scenario-editor.tsx | 20 ++++++++++--------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/apps/studio/src/components/svm/scenario-editor.test.tsx b/apps/studio/src/components/svm/scenario-editor.test.tsx index 2a82a9ea..30903768 100644 --- a/apps/studio/src/components/svm/scenario-editor.test.tsx +++ b/apps/studio/src/components/svm/scenario-editor.test.tsx @@ -21,6 +21,7 @@ vi.mock('@surfpool/ui', async () => ({ DropdownItem: ({ children, onClick }: any) => , DropdownLabel: ({ children }: any) => {children}, DropdownDescription: ({ children }: any) => {children}, + Input: ({ invalid, ...props }: any) => , Select: ({ children, ...props }: any) => , Switch: ({ checked, onChange }: any) => , })); diff --git a/apps/studio/src/components/svm/scenario-editor.tsx b/apps/studio/src/components/svm/scenario-editor.tsx index 0af49326..3268a187 100644 --- a/apps/studio/src/components/svm/scenario-editor.tsx +++ b/apps/studio/src/components/svm/scenario-editor.tsx @@ -36,6 +36,7 @@ import { DropdownItem, DropdownLabel, DropdownMenu, + Input, Select, Switch, } from '@surfpool/ui'; @@ -203,6 +204,7 @@ export default function ScenarioEditor({ const needsTypedAccount = leavesAccountToOverride(selectedAction?.template?.address); const typedAccountPubkey = typedAccount.trim(); const hasTypedAccount = isSolanaAddress(typedAccountPubkey); + const isTypedAccountInvalid = !!typedAccountPubkey && !hasTypedAccount; const accountRequestRef = useRef(0); // A ref, so a second click sees the Step in flight before the next render @@ -1966,26 +1968,26 @@ export default function ScenarioEditor({ {selectedAction ? ( <> {needsTypedAccount && ( -
+
- The account this override changes.

+ - {!!typedAccountPubkey && !hasTypedAccount && ( -

+ {isTypedAccountInvalid && ( +

Not a valid Solana address.

)} From 8104f447c2e31b34282d2ba42bf03916a69acb6d Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 07:55:40 +0200 Subject: [PATCH 4/6] fix(studio/scenarios): keep edits on a retyped account and refuse a missing or foreign one --- .../components/svm/scenario-editor.test.tsx | 87 +++++++++++++++++-- .../src/components/svm/scenario-editor.tsx | 58 +++++++++++-- 2 files changed, 134 insertions(+), 11 deletions(-) diff --git a/apps/studio/src/components/svm/scenario-editor.test.tsx b/apps/studio/src/components/svm/scenario-editor.test.tsx index 30903768..c0ecc328 100644 --- a/apps/studio/src/components/svm/scenario-editor.test.tsx +++ b/apps/studio/src/components/svm/scenario-editor.test.tsx @@ -222,7 +222,13 @@ it('keeps the trader of a dialog-created collateral override when it is saved fr address: { pubkey: '' }, properties: [{ path: 'effective_collateral_usdc', type: 'input', value_type: 'string' }], }; - await openEditor(template, { effective_collateral_usdc: '1000' }, { pubkey: trader }); + await loadEditor(template, { effective_collateral_usdc: '1000' }, { pubkey: trader }); + fetchMock.mockImplementation(async () => ({ + ok: true, + json: async () => ({ result: { value: { data: ['', 'base64'] } } }), + })); + fireEvent.click(await screen.findByTitle(`Phoenix Eternal: ${template.name}`)); + fireEvent.click(await screen.findByText(template.name)); await waitFor(() => expect(rpcParams()).toEqual([ [trader, { commitment: 'confirmed', encoding: 'base64', dataSlice: { offset: 0, length: 0 } }], @@ -370,30 +376,46 @@ it('keeps the later of two saved overrides reopened before the first one loaded' const TRADER = 'HB66UQf7Bv82q9VPhg9Hz6RcDaTMY1yJm8KVDA8VG7Gp'; const OTHER_TRADER = '6tgCsPZqZi4rcQWLLgoMHE1XAnRqA7mYYRByGUYxyFwB'; +const FOREIGN_ACCOUNT = 'So11111111111111111111111111111111111111112'; +const MISSING_ACCOUNT = 'AvPTRe4XjC1xdVhwzUiVwDDfqrqm6eVaKMAnS39raEjW'; +const PHOENIX_PROGRAM = 'EtrnLzgbS7nMMy5fbD42kXiUzGg8XQzJ972Xtk1cjWih'; const typedAccountTemplate = { ...collateralTemplate, id: 'typed-collateral', name: 'Typed collateral', address: { pubkey: '' }, }; +const ownedTypedAccountTemplate = { + ...typedAccountTemplate, + id: 'owned-typed-collateral', + name: 'Owned collateral', + idl: { ...collateralTemplate.idl, address: PHOENIX_PROGRAM }, +}; +// A new object per read, since the editor writes edits into the account it read +const traderAccount = (pubkey: string) => + ({ + [TRADER]: { owner: PHOENIX_PROGRAM, data: { parsed: { traderState: { quoteLotCollateral: 42 } } } }, + [OTHER_TRADER]: { owner: PHOENIX_PROGRAM, data: ['', 'base64'] }, + [FOREIGN_ACCOUNT]: { owner: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', data: ['', 'base64'] }, + })[pubkey] ?? null; const collateral = () => screen.getByPlaceholderText('Enter quoteLotCollateral...'); const readAccounts = () => rpcParams().map(([pubkey]) => pubkey); const mockTraderAccount = (...templates: any[]) => fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { const pubkey = url === 'http://rpc' ? JSON.parse(`${init?.body}`).params[0] : undefined; - const value = pubkey === TRADER ? { data: { parsed: { traderState: { quoteLotCollateral: 42 } } } } : null; + const value = traderAccount(pubkey); return { ok: true, json: async () => (url.endsWith('/templates') ? templates : { result: { value } }) }; }); -const pickTypedAccountTemplate = async () => { - mockTraderAccount(collateralTemplate, typedAccountTemplate); +const pickTypedAccountTemplate = async (template: any = typedAccountTemplate) => { + mockTraderAccount(collateralTemplate, template); renderEditor(stepAction(collateralTemplate)); fireEvent.click(await screen.findByTitle(`Phoenix Eternal: ${collateralTemplate.name}`)); fireEvent.click(await screen.findByText('Phoenix Eternal', { selector: 'span' })); await screen.findByPlaceholderText('Enter quoteLotCollateral...'); expect(screen.queryByLabelText('Account')).not.toBeInTheDocument(); - fireEvent.click(await screen.findByRole('heading', { name: typedAccountTemplate.name })); + fireEvent.click(await screen.findByRole('heading', { name: template.name })); return screen.findByLabelText('Account'); }; @@ -441,6 +463,61 @@ it('shows and reads the saved account of a reopened override, and clears the fie expect(readAccounts()).toEqual([TRADER, OTHER_TRADER]); }); +it('keeps the edits of a typed account retyped to the same address after an invalid one', async () => { + const account = await pickTypedAccountTemplate(); + fireEvent.change(account, { target: { value: TRADER } }); + await waitFor(() => expect(collateral()).toHaveValue(42)); + fireEvent.change(collateral(), { target: { value: '7' } }); + + fireEvent.change(account, { target: { value: `${TRADER}.` } }); + fireEvent.change(account, { target: { value: TRADER } }); + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(collateral()).toHaveValue(7); + expect(readAccounts()).toEqual(['trader', TRADER]); + expect((await savedOverride('Add to Selected Slot')).values).toEqual({ 'traderState.quoteLotCollateral': 7 }); +}); + +it('drops the read of a typed account that is cleared before the read returns', async () => { + const account = await pickTypedAccountTemplate(); + const reply = fetchMock.getMockImplementation()!; + let releaseRead = () => {}; + const readReleased = new Promise((resolve) => (releaseRead = resolve)); + fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { + await readReleased; + return reply(url, init); + }); + fireEvent.change(account, { target: { value: TRADER } }); + await waitFor(() => expect(readAccounts()).toEqual(['trader', TRADER])); + + fireEvent.change(account, { target: { value: '' } }); + releaseRead(); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(collateral()).toHaveValue(null); + + fireEvent.change(account, { target: { value: TRADER } }); + await waitFor(() => expect(collateral()).toHaveValue(42)); + expect(readAccounts()).toEqual(['trader', TRADER, TRADER]); +}); + +it('keeps an override off a typed account that does not exist or that another program owns', async () => { + const account = await pickTypedAccountTemplate(ownedTypedAccountTemplate); + const save = () => screen.getByRole('button', { name: 'Add to Selected Slot' }); + + fireEvent.change(account, { target: { value: MISSING_ACCOUNT } }); + expect(await screen.findByText('No account at this address.')).toBeInTheDocument(); + expect(save()).toBeDisabled(); + + fireEvent.change(account, { target: { value: FOREIGN_ACCOUNT } }); + expect(await screen.findByText('Not a Phoenix Eternal account.')).toBeInTheDocument(); + expect(save()).toBeDisabled(); + + fireEvent.change(account, { target: { value: TRADER } }); + await waitFor(() => expect(collateral()).toHaveValue(42)); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + expect(save()).toBeEnabled(); +}); + it('steps forward to the slot after the processed one, which surfnet reads ahead of the finalized default', async () => { fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { const body = typeof init?.body === 'string' ? JSON.parse(init.body) : {}; diff --git a/apps/studio/src/components/svm/scenario-editor.tsx b/apps/studio/src/components/svm/scenario-editor.tsx index 3268a187..d9c8df76 100644 --- a/apps/studio/src/components/svm/scenario-editor.tsx +++ b/apps/studio/src/components/svm/scenario-editor.tsx @@ -154,6 +154,8 @@ const PAUSED_CLOCK_WARNING = const leavesAccountToOverride = (address: any) => !!address && typeof address === 'object' && !address.pda && !(address.pubkey || address.address || address.value); +type TypedAccountIssue = 'missing' | 'foreign' | null; + const isSolanaAddress = (value: string) => { try { new PublicKey(value); @@ -185,6 +187,7 @@ export default function ScenarioEditor({ const [arrayEntryIndex, setArrayEntryIndex] = useState>({}); const [fetchBeforeUse, setFetchBeforeUse] = useState(false); const [typedAccount, setTypedAccount] = useState(''); + const [typedAccountIssue, setTypedAccountIssue] = useState(null); const [loadingAccountData, setLoadingAccountData] = useState(false); const [showProtocolPanel, setShowProtocolPanel] = useState(false); const [slots, setSlots] = useState([]); @@ -205,8 +208,10 @@ export default function ScenarioEditor({ const typedAccountPubkey = typedAccount.trim(); const hasTypedAccount = isSolanaAddress(typedAccountPubkey); const isTypedAccountInvalid = !!typedAccountPubkey && !hasTypedAccount; + const hasUsableTypedAccount = hasTypedAccount && !typedAccountIssue; const accountRequestRef = useRef(0); + const loadedTypedAccountRef = useRef(''); // A ref, so a second click sees the Step in flight before the next render const steppingRef = useRef(false); const isFirstSlotsChangeRef = useRef(true); @@ -661,12 +666,14 @@ export default function ScenarioEditor({ // Register IDL and fetch account data when an action is selected const handleActionSelect = async (action: Action, accountPubkey?: string) => { const requestId = ++accountRequestRef.current; + loadedTypedAccountRef.current = accountPubkey ?? ''; setSelectedAction(action); setAccountData({}); setModifiedFields(new Set()); // Clear modified fields when loading new action setArrayEntryIndex({}); setFetchBeforeUse(false); // Reset fetch before use toggle setTypedAccount(accountPubkey ?? ''); + setTypedAccountIssue(null); if (!action.template?.idl || !action.template?.address) { console.warn('Action template missing IDL or address'); @@ -732,9 +739,18 @@ export default function ScenarioEditor({ logger.log('✅ Account info received:', accountInfoData); if (requestId !== accountRequestRef.current) return; - if (accountInfoData.result?.value?.data?.parsed) { + const account = accountInfoData.result?.value; + let issue: TypedAccountIssue = null; + if (accountPubkey && leavesAccountToOverride(action.template.address)) { + const programId = action.template.idl.address; + if (!account) issue = 'missing'; + else if (programId && account.owner !== programId) issue = 'foreign'; + } + setTypedAccountIssue(issue); + + if (!issue && account?.data?.parsed) { // Populate accountData with the parsed data - const parsed = accountInfoData.result.value.data.parsed; + const parsed = account.data.parsed; logger.log('📊 Parsed account data:', parsed); setAccountData(parsed); } @@ -750,11 +766,24 @@ export default function ScenarioEditor({ const handleTypedAccountChange = (event: React.ChangeEvent) => { const pubkey = event.target.value.trim(); setTypedAccount(event.target.value); - if (selectedAction && pubkey !== typedAccountPubkey && isSolanaAddress(pubkey)) { - handleActionSelect(selectedAction, pubkey); + if (!selectedAction) return; + if (isSolanaAddress(pubkey)) { + if (pubkey !== loadedTypedAccountRef.current) handleActionSelect(selectedAction, pubkey); + return; + } + // A finished read stays, so retyping its address keeps the edits; a read in flight must not fill the fields + if (loadingAccountData) { + accountRequestRef.current++; + loadedTypedAccountRef.current = ''; + setAccountData({}); + setLoadingAccountData(false); } }; + const isTypedAccountReady = (action: Action) => + !leavesAccountToOverride(action.template?.address) || + (hasUsableTypedAccount && typedAccountPubkey === loadedTypedAccountRef.current); + // Filter actions in protocol panel, narrowed to the chosen product when there is one const filteredActions = (selectedProduct ?? selectedProtocol)?.actions.filter((action) => { @@ -1991,6 +2020,16 @@ export default function ScenarioEditor({ Not a valid Solana address.

)} + {hasTypedAccount && typedAccountIssue === 'missing' && ( +

+ No account at this address. +

+ )} + {hasTypedAccount && typedAccountIssue === 'foreign' && ( +

+ Not a {selectedProtocol?.title} account. +

+ )}
)}
@@ -2759,7 +2798,12 @@ export default function ScenarioEditor({
, DropdownLabel: ({ children }: any) => {children}, DropdownDescription: ({ children }: any) => {children}, - Input: ({ invalid, ...props }: any) => , Select: ({ children, ...props }: any) => , Switch: ({ checked, onChange }: any) => , })); @@ -419,13 +418,22 @@ const pickTypedAccountTemplate = async (template: any = typedAccountTemplate) => return screen.findByLabelText('Account'); }; +const chooseAccount = (pubkey: string) => { + fireEvent.change(screen.getByLabelText('Account'), { target: { value: pubkey } }); + fireEvent.click(screen.getByRole('button', { name: pubkey.trim() })); +}; + it('adds an override of a template without an address on the account typed for it', async () => { const account = await pickTypedAccountTemplate(); expect(account).toHaveValue(''); expect(readAccounts()).toEqual(['trader']); fireEvent.change(account, { target: { value: ` ${TRADER} ` } }); + expect(comboboxResults('Account')).toEqual([TRADER]); + expect(readAccounts()).toEqual(['trader']); + fireEvent.click(screen.getByRole('button', { name: TRADER })); await waitFor(() => expect(collateral()).toHaveValue(42)); + expect(account).toHaveValue(TRADER); fireEvent.change(collateral(), { target: { value: '7' } }); expect(await savedOverride('Add to Selected Slot')).toMatchObject({ @@ -443,6 +451,7 @@ it('keeps an override of a template without an address from being saved without fireEvent.change(account, { target: { value: `${TRADER}.` } }); expect(screen.getByRole('status')).toHaveTextContent('Not a valid Solana address.'); + expect(comboboxResults('Account')).toEqual([]); expect(save).toBeDisabled(); expect(readAccounts()).toEqual(['trader']); }); @@ -457,7 +466,7 @@ it('shows and reads the saved account of a reopened override, and clears the fie expect(account).toHaveValue(TRADER); await waitFor(() => expect(collateral()).toHaveValue(5)); - fireEvent.change(account, { target: { value: OTHER_TRADER } }); + chooseAccount(OTHER_TRADER); await waitFor(() => expect(collateral()).toHaveValue(null)); expect((await savedOverride()).account).toEqual({ pubkey: OTHER_TRADER }); expect(readAccounts()).toEqual([TRADER, OTHER_TRADER]); @@ -465,12 +474,12 @@ it('shows and reads the saved account of a reopened override, and clears the fie it('keeps the edits of a typed account retyped to the same address after an invalid one', async () => { const account = await pickTypedAccountTemplate(); - fireEvent.change(account, { target: { value: TRADER } }); + chooseAccount(TRADER); await waitFor(() => expect(collateral()).toHaveValue(42)); fireEvent.change(collateral(), { target: { value: '7' } }); fireEvent.change(account, { target: { value: `${TRADER}.` } }); - fireEvent.change(account, { target: { value: TRADER } }); + chooseAccount(TRADER); await new Promise((resolve) => setTimeout(resolve, 50)); expect(collateral()).toHaveValue(7); @@ -487,7 +496,7 @@ it('drops the read of a typed account that is cleared before the read returns', await readReleased; return reply(url, init); }); - fireEvent.change(account, { target: { value: TRADER } }); + chooseAccount(TRADER); await waitFor(() => expect(readAccounts()).toEqual(['trader', TRADER])); fireEvent.change(account, { target: { value: '' } }); @@ -495,24 +504,24 @@ it('drops the read of a typed account that is cleared before the read returns', await new Promise((resolve) => setTimeout(resolve, 50)); expect(collateral()).toHaveValue(null); - fireEvent.change(account, { target: { value: TRADER } }); + chooseAccount(TRADER); await waitFor(() => expect(collateral()).toHaveValue(42)); expect(readAccounts()).toEqual(['trader', TRADER, TRADER]); }); it('keeps an override off a typed account that does not exist or that another program owns', async () => { - const account = await pickTypedAccountTemplate(ownedTypedAccountTemplate); + await pickTypedAccountTemplate(ownedTypedAccountTemplate); const save = () => screen.getByRole('button', { name: 'Add to Selected Slot' }); - fireEvent.change(account, { target: { value: MISSING_ACCOUNT } }); + chooseAccount(MISSING_ACCOUNT); expect(await screen.findByText('No account at this address.')).toBeInTheDocument(); expect(save()).toBeDisabled(); - fireEvent.change(account, { target: { value: FOREIGN_ACCOUNT } }); + chooseAccount(FOREIGN_ACCOUNT); expect(await screen.findByText('Not a Phoenix Eternal account.')).toBeInTheDocument(); expect(save()).toBeDisabled(); - fireEvent.change(account, { target: { value: TRADER } }); + chooseAccount(TRADER); await waitFor(() => expect(collateral()).toHaveValue(42)); expect(screen.queryByRole('status')).not.toBeInTheDocument(); expect(save()).toBeEnabled(); diff --git a/apps/studio/src/components/svm/scenario-editor.tsx b/apps/studio/src/components/svm/scenario-editor.tsx index d9c8df76..85609663 100644 --- a/apps/studio/src/components/svm/scenario-editor.tsx +++ b/apps/studio/src/components/svm/scenario-editor.tsx @@ -36,7 +36,6 @@ import { DropdownItem, DropdownLabel, DropdownMenu, - Input, Select, Switch, } from '@surfpool/ui'; @@ -44,7 +43,12 @@ import { AnimatePresence, motion } from 'framer-motion'; import { LosslessNumber } from 'lossless-json'; import React, { useEffect, useRef, useState } from 'react'; import { getFieldsFromRawLayout } from './raw-layout-fields'; -import { customValueOption, findOptionByTypedValue, resolveTokenSelectorOptions } from './token-selector-options'; +import { + customValueOption, + findOptionByTypedValue, + resolveTokenSelectorOptions, + type TokenSelectorOption, +} from './token-selector-options'; import TransactionInspector from './transaction-inspector'; interface Protocol { @@ -187,6 +191,7 @@ export default function ScenarioEditor({ const [arrayEntryIndex, setArrayEntryIndex] = useState>({}); const [fetchBeforeUse, setFetchBeforeUse] = useState(false); const [typedAccount, setTypedAccount] = useState(''); + const [accountQuery, setAccountQuery] = useState(''); const [typedAccountIssue, setTypedAccountIssue] = useState(null); const [loadingAccountData, setLoadingAccountData] = useState(false); const [showProtocolPanel, setShowProtocolPanel] = useState(false); @@ -205,10 +210,10 @@ export default function ScenarioEditor({ const [dynamicOptions, setDynamicOptions] = useState>({}); const needsTypedAccount = leavesAccountToOverride(selectedAction?.template?.address); - const typedAccountPubkey = typedAccount.trim(); - const hasTypedAccount = isSolanaAddress(typedAccountPubkey); - const isTypedAccountInvalid = !!typedAccountPubkey && !hasTypedAccount; + const hasTypedAccount = isSolanaAddress(typedAccount); + const isAccountQueryInvalid = !!accountQuery.trim() && !isSolanaAddress(accountQuery.trim()); const hasUsableTypedAccount = hasTypedAccount && !typedAccountIssue; + const accountSelection = resolveTokenSelectorOptions([], typedAccount); const accountRequestRef = useRef(0); const loadedTypedAccountRef = useRef(''); @@ -673,6 +678,7 @@ export default function ScenarioEditor({ setArrayEntryIndex({}); setFetchBeforeUse(false); // Reset fetch before use toggle setTypedAccount(accountPubkey ?? ''); + setAccountQuery(''); setTypedAccountIssue(null); if (!action.template?.idl || !action.template?.address) { @@ -763,15 +769,15 @@ export default function ScenarioEditor({ }; // The read fills the fields and pulls the account into the local VM, without which Play skips it - const handleTypedAccountChange = (event: React.ChangeEvent) => { - const pubkey = event.target.value.trim(); - setTypedAccount(event.target.value); + const handleTypedAccountChange = (option: TokenSelectorOption | null) => { + const pubkey = option?.value != null ? String(option.value) : ''; + setTypedAccount(pubkey); if (!selectedAction) return; - if (isSolanaAddress(pubkey)) { + if (pubkey) { if (pubkey !== loadedTypedAccountRef.current) handleActionSelect(selectedAction, pubkey); return; } - // A finished read stays, so retyping its address keeps the edits; a read in flight must not fill the fields + // A finished read stays, so choosing its address again keeps the edits; a read in flight must not fill the fields if (loadingAccountData) { accountRequestRef.current++; loadedTypedAccountRef.current = ''; @@ -782,7 +788,20 @@ export default function ScenarioEditor({ const isTypedAccountReady = (action: Action) => !leavesAccountToOverride(action.template?.address) || - (hasUsableTypedAccount && typedAccountPubkey === loadedTypedAccountRef.current); + (hasUsableTypedAccount && typedAccount === loadedTypedAccountRef.current); + + const typedAccountOption = (query: string) => + isSolanaAddress(query) && !findOptionByTypedValue(accountSelection.options, query) + ? customValueOption(query) + : null; + + const displayAccount = (option: TokenSelectorOption | null) => (option?.value != null ? String(option.value) : ''); + + const renderAccountOption = (option: TokenSelectorOption) => ( + + {option.metadata?.symbol} + + ); // Filter actions in protocol panel, narrowed to the chosen product when there is one const filteredActions = @@ -864,7 +883,7 @@ export default function ScenarioEditor({ modifiedFields: Array.from(modifiedFields), fetchBeforeUse: fetchBeforeUse, account: leavesAccountToOverride(action.template?.address) - ? { pubkey: typedAccountPubkey } + ? { pubkey: typedAccount } : action.template?.address, }, ], @@ -909,7 +928,7 @@ export default function ScenarioEditor({ // override was saved for, such as a trader given to a preset. Any other address, a PDA included, // comes from the template, so edited seed fields such as a token or fee tier pick the new account. account: leavesAccountToOverride(action.template?.address) - ? { pubkey: typedAccountPubkey } + ? { pubkey: typedAccount } : action.template?.address, } : existingAction @@ -1997,39 +2016,45 @@ export default function ScenarioEditor({ {selectedAction ? ( <> {needsTypedAccount && ( -
- -

The account this override changes.

- - {isTypedAccountInvalid && ( -

- Not a valid Solana address. -

- )} - {hasTypedAccount && typedAccountIssue === 'missing' && ( -

- No account at this address. -

- )} - {hasTypedAccount && typedAccountIssue === 'foreign' && ( -

- Not a {selectedProtocol?.title} account. +

+
+ Account selection +
+
+ +

+ The account this override changes. Paste its address.

- )} + + value={accountSelection.selectedOption} + onChange={handleTypedAccountChange} + options={accountSelection.options} + displayValue={displayAccount} + customOption={typedAccountOption} + onQueryChange={setAccountQuery} + invalid={isAccountQueryInvalid} + immediate + placeholder="Paste an account address..." + aria-label="Account" + > + {renderAccountOption} + + {isAccountQueryInvalid && ( +

+ Not a valid Solana address. +

+ )} + {hasTypedAccount && typedAccountIssue === 'missing' && ( +

+ No account at this address. +

+ )} + {hasTypedAccount && typedAccountIssue === 'foreign' && ( +

+ Not a {selectedProtocol?.title} account. +

+ )} +
)}
diff --git a/apps/studio/src/test-utils.tsx b/apps/studio/src/test-utils.tsx index bd3491ac..e71cd701 100644 --- a/apps/studio/src/test-utils.tsx +++ b/apps/studio/src/test-utils.tsx @@ -101,19 +101,31 @@ export function MockCombobox({ displayValue, filter, customOption, + onQueryChange, onChange, disabled, placeholder, children, }: any) { const [query, setQuery] = React.useState(null); - const handleQueryChange = (event: React.ChangeEvent) => setQuery(event.target.value); - const matches = query ? options.filter((option: any) => filter(option, query)) : options; + const handleQueryChange = (event: React.ChangeEvent) => { + setQuery(event.target.value); + onQueryChange?.(event.target.value); + if (event.target.value === '') onChange(null); + }; + const matchesQuery = (option: any) => + filter ? filter(option, query) : displayValue(option)?.toLowerCase().includes(query!.toLowerCase()); + const handleSelect = (option: any) => { + setQuery(null); + onQueryChange?.(''); + onChange(option); + }; + const matches = query ? options.filter(matchesQuery) : options; const typedOption = customOption && query?.trim() ? customOption(query.trim()) : null; const shown = typedOption === null ? matches : [...matches, typedOption]; const renderOption = (option: any) => (
  • - + {displayValue(option)} {children(option)} diff --git a/packages/ui/src/catalyst/combobox.tsx b/packages/ui/src/catalyst/combobox.tsx index 17999ced..f3548924 100644 --- a/packages/ui/src/catalyst/combobox.tsx +++ b/packages/ui/src/catalyst/combobox.tsx @@ -9,6 +9,7 @@ export function Combobox({ displayValue, filter, customOption, + onQueryChange, anchor = 'bottom', className, placeholder, @@ -22,6 +23,8 @@ export function Combobox({ filter?: (value: T, query: string) => boolean // Offers the typed text as a last option, for values the list does not have; null offers nothing. customOption?: (query: string) => T | null + // Reports the typed text, and '' once the list closes and the input shows the value again. + onQueryChange?: (query: string) => void className?: string placeholder?: string autoFocus?: boolean @@ -29,6 +32,10 @@ export function Combobox({ children: (value: NonNullable) => React.ReactElement } & Omit, 'as' | 'multiple' | 'children'> & { anchor?: 'top' | 'bottom' }) { const [query, setQuery] = useState('') + const changeQuery = (typed: string) => { + setQuery(typed) + onQueryChange?.(typed) + } const filteredOptions = query === '' @@ -40,7 +47,7 @@ export function Combobox({ const visibleOptions = typedOption === null ? filteredOptions : [...filteredOptions, typedOption] return ( - setQuery('')}> + changeQuery('')}> ({ data-slot="control" aria-label={ariaLabel} displayValue={(option: T) => displayValue(option) ?? ''} - onChange={(event) => setQuery(event.target.value)} + onChange={(event) => changeQuery(event.target.value)} placeholder={placeholder} className={clsx([ className, From 7179db5a8afd9b874abada1b2c13a3c50058ca90 Mon Sep 17 00:00:00 2001 From: 92Infinitus92 <92georgepetroff92@gmail.com> Date: Tue, 10 Nov 2026 12:37:16 +0200 Subject: [PATCH 6/6] fix(studio/scenarios): check a typed account without an IDL and block one the RPC could not read --- .../components/svm/scenario-editor.test.tsx | 49 +++++++++++++++++++ .../src/components/svm/scenario-editor.tsx | 28 ++++++++--- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/apps/studio/src/components/svm/scenario-editor.test.tsx b/apps/studio/src/components/svm/scenario-editor.test.tsx index 59796014..4508adb9 100644 --- a/apps/studio/src/components/svm/scenario-editor.test.tsx +++ b/apps/studio/src/components/svm/scenario-editor.test.tsx @@ -527,6 +527,55 @@ it('keeps an override off a typed account that does not exist or that another pr expect(save()).toBeEnabled(); }); +const UNREADABLE = 'Could not read this account. Pick it again to retry.'; + +it('keeps an override off a typed account the RPC could not read, until a read of it works', async () => { + await pickTypedAccountTemplate(ownedTypedAccountTemplate); + const save = () => screen.getByRole('button', { name: 'Add to Selected Slot' }); + const reply = fetchMock.getMockImplementation()!; + let failedReads = 0; + fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { + const pubkey = url === 'http://rpc' ? JSON.parse(`${init?.body}`).params[0] : undefined; + if (pubkey === TRADER && failedReads < 2) { + failedReads += 1; + if (failedReads === 1) return { ok: true, json: async () => ({ error: { code: -32000, message: 'rate limited' } }) }; + throw new Error('network down'); + } + return reply(url, init); + }); + + chooseAccount(TRADER); + expect(await screen.findByText(UNREADABLE)).toBeInTheDocument(); + expect(save()).toBeDisabled(); + + chooseAccount(TRADER); + await waitFor(() => expect(failedReads).toBe(2)); + expect(await screen.findByText(UNREADABLE)).toBeInTheDocument(); + expect(save()).toBeDisabled(); + + chooseAccount(TRADER); + await waitFor(() => expect(collateral()).toHaveValue(42)); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + expect(save()).toBeEnabled(); +}); + +it('checks that a typed account of a template without an IDL exists, without decoding it', async () => { + await pickTypedAccountTemplate({ ...typedAccountTemplate, id: 'raw-collateral', name: 'Raw collateral', idl: null }); + const save = () => screen.getByRole('button', { name: 'Add to Selected Slot' }); + + chooseAccount(MISSING_ACCOUNT); + expect(await screen.findByText('No account at this address.')).toBeInTheDocument(); + expect(save()).toBeDisabled(); + + chooseAccount(TRADER); + await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument()); + expect(save()).toBeEnabled(); + expect(rpcParams().at(-1)).toEqual([ + TRADER, + { commitment: 'confirmed', encoding: 'base64', dataSlice: { offset: 0, length: 0 } }, + ]); +}); + it('steps forward to the slot after the processed one, which surfnet reads ahead of the finalized default', async () => { fetchMock.mockImplementation(async (url: string, init?: RequestInit) => { const body = typeof init?.body === 'string' ? JSON.parse(init.body) : {}; diff --git a/apps/studio/src/components/svm/scenario-editor.tsx b/apps/studio/src/components/svm/scenario-editor.tsx index 85609663..1e2e8582 100644 --- a/apps/studio/src/components/svm/scenario-editor.tsx +++ b/apps/studio/src/components/svm/scenario-editor.tsx @@ -158,7 +158,7 @@ const PAUSED_CLOCK_WARNING = const leavesAccountToOverride = (address: any) => !!address && typeof address === 'object' && !address.pda && !(address.pubkey || address.address || address.value); -type TypedAccountIssue = 'missing' | 'foreign' | null; +type TypedAccountIssue = 'missing' | 'foreign' | 'unverified' | null; const isSolanaAddress = (value: string) => { try { @@ -681,7 +681,10 @@ export default function ScenarioEditor({ setAccountQuery(''); setTypedAccountIssue(null); - if (!action.template?.idl || !action.template?.address) { + // Without an IDL, as on raw-layout templates, only a given account is read: nothing is decoded, + // but the read checks that the account exists. + const hasIdl = !!action.template?.idl; + if (!action.template?.address || (!hasIdl && !accountPubkey)) { console.warn('Action template missing IDL or address'); setLoadingAccountData(false); return; @@ -727,7 +730,7 @@ export default function ScenarioEditor({ method: 'getAccountInfo', params: [ addressString, - inputsOnly + inputsOnly || !hasIdl ? { commitment: 'confirmed', encoding: 'base64', dataSlice: { offset: 0, length: 0 } } : { commitment: 'confirmed', encoding: 'jsonParsed' }, ], @@ -748,10 +751,13 @@ export default function ScenarioEditor({ const account = accountInfoData.result?.value; let issue: TypedAccountIssue = null; if (accountPubkey && leavesAccountToOverride(action.template.address)) { - const programId = action.template.idl.address; - if (!account) issue = 'missing'; + const programId = action.template.idl?.address; + if (accountInfoData.error) issue = 'unverified'; + else if (!account) issue = 'missing'; else if (programId && account.owner !== programId) issue = 'foreign'; } + // A read that failed is no read: choosing the same address again retries it. + if (issue === 'unverified') loadedTypedAccountRef.current = ''; setTypedAccountIssue(issue); if (!issue && account?.data?.parsed) { @@ -764,7 +770,12 @@ export default function ScenarioEditor({ setLoadingAccountData(false); } catch (error) { console.error('Error loading account data:', error); - if (requestId === accountRequestRef.current) setLoadingAccountData(false); + if (requestId !== accountRequestRef.current) return; + if (accountPubkey && leavesAccountToOverride(action.template?.address)) { + loadedTypedAccountRef.current = ''; + setTypedAccountIssue('unverified'); + } + setLoadingAccountData(false); } }; @@ -2054,6 +2065,11 @@ export default function ScenarioEditor({ Not a {selectedProtocol?.title} account.

    )} + {hasTypedAccount && typedAccountIssue === 'unverified' && ( +

    + Could not read this account. Pick it again to retry. +

    + )}
  • )}