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'), + }); + } diff --git a/apps/studio/src/components/svm/scenario-editor.test.tsx b/apps/studio/src/components/svm/scenario-editor.test.tsx index 8f3c346f..4508adb9 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' }] } }; @@ -221,7 +221,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 } }], @@ -367,6 +373,209 @@ 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 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 = traderAccount(pubkey); + return { ok: true, json: async () => (url.endsWith('/templates') ? templates : { result: { value } }) }; + }); + +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: template.name })); + 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({ + 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(comboboxResults('Account')).toEqual([]); + 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)); + + chooseAccount(OTHER_TRADER); + await waitFor(() => expect(collateral()).toHaveValue(null)); + expect((await savedOverride()).account).toEqual({ pubkey: OTHER_TRADER }); + 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(); + chooseAccount(TRADER); + await waitFor(() => expect(collateral()).toHaveValue(42)); + fireEvent.change(collateral(), { target: { value: '7' } }); + + fireEvent.change(account, { target: { value: `${TRADER}.` } }); + chooseAccount(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); + }); + chooseAccount(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); + + 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 () => { + await pickTypedAccountTemplate(ownedTypedAccountTemplate); + 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(FOREIGN_ACCOUNT); + expect(await screen.findByText('Not a Phoenix Eternal account.')).toBeInTheDocument(); + expect(save()).toBeDisabled(); + + chooseAccount(TRADER); + await waitFor(() => expect(collateral()).toHaveValue(42)); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + 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 1bc5ad1d..1e2e8582 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, @@ -42,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 { @@ -152,6 +158,17 @@ const PAUSED_CLOCK_WARNING = const leavesAccountToOverride = (address: any) => !!address && typeof address === 'object' && !address.pda && !(address.pubkey || address.address || address.value); +type TypedAccountIssue = 'missing' | 'foreign' | 'unverified' | null; + +const isSolanaAddress = (value: string) => { + try { + new PublicKey(value); + return true; + } catch { + return false; + } +}; + export default function ScenarioEditor({ scenarioId = 'default', scenarioName = 'Scenario', @@ -173,6 +190,9 @@ 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 [accountQuery, setAccountQuery] = useState(''); + const [typedAccountIssue, setTypedAccountIssue] = useState(null); const [loadingAccountData, setLoadingAccountData] = useState(false); const [showProtocolPanel, setShowProtocolPanel] = useState(false); const [slots, setSlots] = useState([]); @@ -189,7 +209,14 @@ 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 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(''); // A ref, so a second click sees the Step in flight before the next render const steppingRef = useRef(false); const isFirstSlotsChangeRef = useRef(true); @@ -644,13 +671,20 @@ 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 - - if (!action.template?.idl || !action.template?.address) { + setTypedAccount(accountPubkey ?? ''); + setAccountQuery(''); + setTypedAccountIssue(null); + + // 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; @@ -672,6 +706,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); @@ -692,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' }, ], @@ -710,9 +748,21 @@ 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 (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) { // 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); } @@ -720,10 +770,50 @@ 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); } }; + // The read fills the fields and pulls the account into the local VM, without which Play skips it + const handleTypedAccountChange = (option: TokenSelectorOption | null) => { + const pubkey = option?.value != null ? String(option.value) : ''; + setTypedAccount(pubkey); + if (!selectedAction) return; + if (pubkey) { + if (pubkey !== loadedTypedAccountRef.current) handleActionSelect(selectedAction, pubkey); + return; + } + // 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 = ''; + setAccountData({}); + setLoadingAccountData(false); + } + }; + + const isTypedAccountReady = (action: Action) => + !leavesAccountToOverride(action.template?.address) || + (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 = (selectedProduct ?? selectedProtocol)?.actions.filter((action) => { @@ -803,7 +893,9 @@ export default function ScenarioEditor({ overrides: accountData, modifiedFields: Array.from(modifiedFields), fetchBeforeUse: fetchBeforeUse, - account: action.template?.address, + account: leavesAccountToOverride(action.template?.address) + ? { pubkey: typedAccount } + : action.template?.address, }, ], }; @@ -843,15 +935,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: typedAccount } + : action.template?.address, } : existingAction ), @@ -1937,6 +2026,53 @@ export default function ScenarioEditor({
{selectedAction ? ( <> + {needsTypedAccount && ( +
+
+ 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. +

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

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

+ )} +
+
+ )}

@@ -2703,7 +2839,12 @@ export default function ScenarioEditor({