From f1d3066d0b57f81806bb7982e9a388fee4f39257 Mon Sep 17 00:00:00 2001 From: Andrey Gruzdev Date: Sat, 28 Nov 2026 15:51:41 +0100 Subject: [PATCH 1/7] ci: run lint, build and tests on pull requests and main tests/registry.test.cjs had no script and nothing ran it. Add `npm test` (the Node test runner over tests/**/*.test.cjs) and a GitHub Actions workflow that runs npm ci, lint, build and test on Node 24 for pull requests and pushes to main. AGENTS.md lists `npm test` with the other checks. `node --test tests/` fails on Node 24 (the directory is loaded as a module), so the script passes an explicit glob. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 37 +++++++++++++++++++++++++++++++++++++ AGENTS.md | 3 ++- package.json | 3 ++- 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3da3c70 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: CI + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + env: + NEXT_TELEMETRY_DISABLED: 1 + + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js 24.x LTS + uses: actions/setup-node@v4 + with: + node-version: '24.x' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Lint + run: npm run lint + + - name: Build + run: npm run build + + - name: Test + run: npm test diff --git a/AGENTS.md b/AGENTS.md index ecd7b69..87e2867 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,5 +2,6 @@ - Use Conventional Commits for commit messages, PR titles, and squash merges. - Use **Why**, **Change**, and **Validation** sections by default in PR descriptions. Explain the reason, summarize what changed, and report what was actually checked. Reserve comments for decisions, blockers, and review replies. -- Install dependencies and run builds in a fresh development VM. For frontend changes, run `npm ci`, `npm run lint`, and `npm run build` from the repository root. +- Install dependencies and run builds in a fresh development VM. For frontend changes, run `npm ci`, `npm run lint`, `npm run build`, and `npm test` from the repository root. CI runs the same checks on Node 24. - For registry or contract-page changes, check both Mainnet and Testnet in a browser. Keep a recorded verification distinct from a match with the currently deployed code. An RPC failure must show an unknown status, never a match or mismatch. +- `npm test` runs `tests/**/*.test.cjs` with the Node test runner, which loads `.ts` modules directly (Node 22.18 or later). Put tested logic in modules whose `@/` imports are type-only. diff --git a/package.json b/package.json index cd937df..13f7287 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "dev": "next dev", "build": "next build", "start": "next start", - "lint": "next lint" + "lint": "next lint", + "test": "node --test \"tests/**/*.test.cjs\"" }, "dependencies": { "@chakra-ui/icons": "^2.1.1", From 1a296858a695d2c5dbadb8d3a86c30b9237be7df Mon Sep 17 00:00:00 2001 From: Andrey Gruzdev Date: Sat, 28 Nov 2026 15:51:41 +0100 Subject: [PATCH 2/7] fix(contract): keep recorded evidence apart from current metadata The Evidence tab and the source tree took the repository, commit and contract path from the contract's current NEP-330 metadata, so after a redeploy they showed the new build next to the old verification. The registry records only the snapshot (cid), code hash and block, so the recorded repository now comes from the record's github field or from the git checkout stored in the recorded snapshot. The current metadata stays on the Build tab, labelled as current, and picks the tree folder only when it names the same repository and commit; otherwise the folder is offered as a labelled choice. NEP-330 metadata is parsed once into a typed shape. Fields with the wrong type are flagged instead of rendered, duplicate standards are collapsed, and each workspace pane has an error boundary. A metadata read that fails (RPC failure or a panic in the method) is unknown with a retry and is never cached. Only MethodNotFound, missing code or a missing account count as "no metadata". Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + components/Common/PaneBoundary.tsx | 37 ++++++ components/Workspace/BuildPane.tsx | 178 +++++++++++++++++++------- components/Workspace/EvidencePane.tsx | 60 ++++++++- components/Workspace/SourcePane.tsx | 97 +++++++++++++- hooks/useContract.ts | 40 ++---- hooks/useRecordedSource.ts | 42 ++++++ pages/contract/[slug].tsx | 71 ++++++---- tests/evidence.test.cjs | 121 +++++++++++++++++ tests/metadata.test.cjs | 169 ++++++++++++++++++++++++ tests/registry.test.cjs | 8 +- utils/contractMetadata.ts | 164 ++++++++++++++++++++++++ utils/evidence.ts | 100 +++++++++++++++ utils/extractGithub.ts | 54 +++++++- utils/near/view.ts | 17 ++- utils/sourceFiles.ts | 25 ++++ 16 files changed, 1074 insertions(+), 111 deletions(-) create mode 100644 components/Common/PaneBoundary.tsx create mode 100644 hooks/useRecordedSource.ts create mode 100644 tests/evidence.test.cjs create mode 100644 tests/metadata.test.cjs create mode 100644 utils/contractMetadata.ts create mode 100644 utils/evidence.ts diff --git a/README.md b/README.md index f6d865d..144c6d0 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ The registry rows show recorded verifications. The contract workspace checks dep Registry totals come from the REST API configured by `NEXT_PUBLIC_API_HOST`. IPFS source snapshots use the app's `/api/proxy-ipfs` route. +The Evidence tab names the repository and commit of the recorded snapshot: the record's own `github`, or the git checkout stored in the snapshot. The contract's NEP-330 metadata, read at the latest final block, is shown on the Build tab as current metadata. It picks the source tree's folder only when it names that same repository and commit. + ## Learn More To learn more about Next.js, take a look at the following resources: diff --git a/components/Common/PaneBoundary.tsx b/components/Common/PaneBoundary.tsx new file mode 100644 index 0000000..73b1e3c --- /dev/null +++ b/components/Common/PaneBoundary.tsx @@ -0,0 +1,37 @@ +import StatePanel from '@/components/Common/StatePanel' +import { Button } from '@chakra-ui/react' +import { Component, ErrorInfo, ReactNode } from 'react' + +/** + * Contains a render error to one workspace pane, so the verdict, tabs and + * header stay usable. Give it a `key` that changes with the pane's input to + * start over when the reader moves on. + */ +export default class PaneBoundary extends Component<{ label: string; children: ReactNode }, { failed: boolean }> { + state = { failed: false } + + static getDerivedStateFromError() { + return { failed: true } + } + + componentDidCatch(error: Error, info: ErrorInfo) { + console.error(`${this.props.label} failed to render`, error, info.componentStack) + } + + render() { + if (!this.state.failed) return this.props.children + return ( + this.setState({ failed: false })}> + Try again + + } + > + Something in this section failed to render. The verdict and the other sections are unaffected. + + ) + } +} diff --git a/components/Workspace/BuildPane.tsx b/components/Workspace/BuildPane.tsx index 45e57af..c88f69f 100644 --- a/components/Workspace/BuildPane.tsx +++ b/components/Workspace/BuildPane.tsx @@ -1,9 +1,11 @@ import CopyButton from '@/components/Common/CopyButton' import ExternalTextLink from '@/components/Common/ExternalTextLink' +import GithubLink from '@/components/Common/GithubLink' import { Field, Fields, Panel } from '@/components/Common/Panel' -import type { MetadataLoad } from '@/hooks/useContract' import { parseImageRef, registryPage } from '@/utils/buildImage' -import { Badge, Box, Code, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react' +import type { MetadataField, MetadataLoad } from '@/utils/contractMetadata' +import { liveRelation, LiveSource, RecordedSource } from '@/utils/evidence' +import { Badge, Box, Button, Code, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react' import { ReactNode } from 'react' const Mono = (props: { children: ReactNode }) => ( @@ -12,6 +14,12 @@ const Mono = (props: { children: ReactNode }) => ( ) const NotSet = (props: { children: ReactNode }) => {props.children} +/** A field the contract published with the wrong type: flagged, never rendered. */ +const Flagged = (props: { children: ReactNode }) => ( + + {props.children} + +) /** * The exact image reference from the metadata (tag and digest included), with a @@ -46,59 +54,135 @@ function BuildImage(props: { value: string }) { ) } -export default function BuildPane(props: { metadata: MetadataLoad }) { +const TITLE = 'Current build metadata (NEP-330)' + +const ABSENT: Record['reason'], string> = { + no_method: 'The deployed contract doesn’t expose contract_source_metadata, so no build metadata is published on-chain.', + no_code: 'No contract code is deployed on this account at the latest final block, so there is no build metadata.', + no_account: 'This account doesn’t exist at the latest final block, so there is no build metadata.', + null: 'The deployed contract’s contract_source_metadata returns null, so no build metadata is published.', +} + +function Status(props: { tone?: 'muted' | 'warn'; children: ReactNode }) { + return ( + + + {props.children} + + + ) +} + +/** The contract's NEP-330 metadata as read now, labelled as describing the code deployed now. */ +export default function BuildPane(props: { metadata: MetadataLoad; onRetry: () => void; recorded: RecordedSource; live: LiveSource }) { const { metadata } = props - if (metadata.status !== 'ready') + if (metadata.status === 'loading') return ( - - - {metadata.status === 'loading' ? ( - - - Loading contract_source_metadata… - - ) : metadata.status === 'missing' ? ( - 'This contract doesn’t expose contract_source_metadata, so no build metadata is published on-chain.' - ) : ( - 'Couldn’t load the contract metadata from the RPC.' - )} - - + + + + Loading contract_source_metadata… + + ) + if (metadata.status === 'unknown') + return ( + + + Couldn’t read contract_source_metadata: the RPC request failed or the call returned an error. The build metadata is unknown. + + + + ) + if (metadata.status === 'absent') return {ABSENT[metadata.reason]} + if (metadata.status === 'invalid') + return The deployed contract’s contract_source_metadata returns a value that isn’t a NEP-330 metadata object, so it isn’t shown. + const m = metadata.metadata - const build = m.build_info - const env = typeof build?.build_environment === 'string' ? build.build_environment.trim() : '' - const standards = Array.isArray(m.standards) ? m.standards : [] - const command = Array.isArray(build?.build_command) ? build?.build_command ?? [] : [] + const build = m.buildInfo + const bad = (field: MetadataField) => m.invalid.includes(field) + const wrongType = Published with the wrong type; not shown + const env = build?.buildEnvironment?.trim() ?? '' + const relation = liveRelation(props.recorded, props.live) + const liveGithub = props.live.status === 'ready' ? props.live.github : null + return ( - + + + Read from the deployed contract at the latest final block. It describes the code deployed now, which can differ from the verified build. + - {m.version ? {m.version} : Not specified} + {bad('version') ? wrongType : m.version ? {m.version} : Not specified} - {standards.length ? ( - - {standards.map((s) => ( - - {s.standard} {s.version} - - ))} - - ) : ( - None declared - )} - - - {command.length ? ( - - {command.join(' ')} - - ) : ( - Not specified - )} + + {m.standards.length ? ( + + {m.standards.map((s) => ( + + {s.standard} {s.version} + + ))} + + ) : ( + !bad('standards') && None declared + )} + {bad('standards') && Entries that aren’t a standard and version string were ignored.} + - {env ? : Not specified} - {build?.contract_path ? {build.contract_path} : / (repository root)} - {build?.source_code_snapshot ? {build.source_code_snapshot} : Not specified} + {bad('build_info') || !build ? ( + {bad('build_info') ? wrongType : Not published} + ) : ( + <> + + {bad('build_command') ? ( + Not a list of strings; not shown + ) : build.buildCommand?.length ? ( + + {build.buildCommand.join(' ')} + + ) : ( + Not specified + )} + + {bad('build_environment') ? wrongType : env ? : Not specified} + + {build.contractPath ? ( + + {build.contractPath} + {bad('contract_path') && Not a relative folder inside the source, so it isn’t used to open the source.} + + ) : bad('contract_path') ? ( + wrongType + ) : ( + / (repository root) + )} + + + {bad('source_code_snapshot') ? ( + wrongType + ) : build.sourceCodeSnapshot ? ( + + {build.sourceCodeSnapshot} + {liveGithub && } + {relation === 'same' && ( + + Same repository and commit as the verified snapshot. + + )} + {relation === 'different' && ( + + Not the repository and commit of the verified snapshot; the Evidence tab shows the verified one. + + )} + + ) : ( + Not specified + )} + + + )} ) diff --git a/components/Workspace/EvidencePane.tsx b/components/Workspace/EvidencePane.tsx index 8240190..ac576da 100644 --- a/components/Workspace/EvidencePane.tsx +++ b/components/Workspace/EvidencePane.tsx @@ -6,10 +6,10 @@ import { Field, Fields, Panel } from '@/components/Common/Panel' import { verdictSummary } from '@/components/Contracts/Verdict' import { NETWORKS, NetworkType } from '@/contexts/NetworkContext' import type { HashCheck } from '@/hooks/useCodeHashCheck' -import type { GithubDto } from '@/Interfaces/github/github.dto' import { ContractData, recordedBlock } from '@/utils/contracts' +import type { RecordedSource } from '@/utils/evidence' import { explorerContractUrl } from '@/utils/urls' -import { HStack, Text } from '@chakra-ui/react' +import { Button, HStack, Spinner, Stack, Text } from '@chakra-ui/react' import { ReactNode } from 'react' const Mono = (props: { children: ReactNode }) => ( @@ -18,12 +18,60 @@ const Mono = (props: { children: ReactNode }) => ( ) +const Muted = (props: { children: ReactNode }) => ( + + {props.children} + +) + +/** Only the repository the record itself proves: the record's own, or the git checkout inside its snapshot. */ +function RecordedRepository(props: { recorded: RecordedSource; onRetry: () => void }) { + const { recorded } = props + if (recorded.status === 'loading') + return ( + + + Reading the snapshot… + + ) + if (recorded.status === 'known') + return ( + + + {recorded.origin === 'snapshot' && ( + + From the git checkout stored in the verified snapshot. + + )} + + ) + if (recorded.status === 'unknown') + return ( + + + Unknown: the snapshot couldn’t be read. + + + + ) + return ( + + Not recorded. The registry stores the snapshot above, not a repository, and the snapshot has no git checkout that names one. The Build tab shows the + repository named in the contract’s current metadata, which may describe a later deployment. + + ) +} + export default function EvidencePane(props: { accountId: string network: NetworkType data: ContractData check: HashCheck - github: GithubDto | null + recorded: RecordedSource + onRetryRecorded: () => void + /** Entry file on GitHub, only when the recorded source and its crate folder are both known. */ entryFileUrl: string | null entryFile: string }) { @@ -67,8 +115,10 @@ export default function EvidencePane(props: { - {props.github ? : Not published} - {props.github && props.entryFileUrl && ( + + + + {props.entryFileUrl && ( {props.entryFile || 'Repository root'} diff --git a/components/Workspace/SourcePane.tsx b/components/Workspace/SourcePane.tsx index 3e2ae08..2659486 100644 --- a/components/Workspace/SourcePane.tsx +++ b/components/Workspace/SourcePane.tsx @@ -4,6 +4,7 @@ import { verdictTone } from '@/components/Contracts/Verdict' import type { NetworkType } from '@/contexts/NetworkContext' import type { HashCheck } from '@/hooks/useCodeHashCheck' import type { ContractData } from '@/utils/contracts' +import type { SourceRoot } from '@/utils/evidence' import { cachedSource, cachedSourcePaths, entryPath, fetchSource, listSourcePaths } from '@/utils/sourceFiles' import { HEADER_H } from '@/utils/theme' import { ipfsFileUrl } from '@/utils/urls' @@ -11,6 +12,7 @@ import { Box, Button, Center, + Code, Flex, Icon, Input, @@ -43,11 +45,93 @@ const STRIPE: Record = { type Files = { key: string; status: 'loading' | 'error' | 'ready'; paths: string[] } type Content = { key: string; status: 'loading' | 'error' | 'ready'; text: string } +/** + * Says where the tree is opened when the record doesn't prove the folder: + * the folder the current metadata names is only offered, labelled as such. + */ +function FolderNotice(props: { root: SourceRoot; onOpenHint: (_open: boolean) => void; onRetryMetadata: () => void }) { + const { root } = props + const hint = root.hint + if (hint.status === 'none') return null + const warn = hint.status === 'unknown' + return ( + + + {hint.status === 'unknown' ? ( + <>Couldn’t read the contract’s current metadata, so it’s unknown which folder of this snapshot holds the contract. Showing the snapshot root. + ) : root.basis === 'hint' ? ( + <> + Showing {hint.dir}, the folder named in the contract’s current metadata. The verification record doesn’t name a folder, so + this may not be the crate that was verified. + + ) : ( + <> + The verification record doesn’t name the contract’s folder in this snapshot. The contract’s current metadata names{' '} + {hint.dir}, which may describe a later deployment. + + )} + + {hint.status === 'unknown' ? ( + + ) : root.basis === 'hint' ? ( + + ) : ( + + )} + + ) +} + export default function SourcePane(props: { network: NetworkType data: ContractData - /** NEP-330 contract_path, '/' when absent; null while metadata is still loading. */ + root: SourceRoot + onOpenHint: (_open: boolean) => void + onRetryMetadata: () => void + /** Also re-reads the snapshot's git checkout when the snapshot couldn't be opened. */ + onRetrySnapshot: () => void + /** `?file=` from the URL. */ + requested: string | null + hrefFor: (_file: string) => string + onSelect: (_file: string) => void + check: HashCheck +}) { + const { root, onOpenHint, onRetryMetadata, ...tree } = props + return ( + <> + + + + ) +} + +function SourceTree(props: { + network: NetworkType + data: ContractData + /** Snapshot folder to list ('/' = root); null while it is still being decided. */ rootPath: string | null + onRetrySnapshot: () => void /** `?file=` from the URL. */ requested: string | null hrefFor: (_file: string) => string @@ -178,7 +262,14 @@ export default function SourcePane(props: { Couldn’t open the IPFS snapshot The verified source for this record could not be read from IPFS right now. - @@ -302,7 +393,7 @@ export default function SourcePane(props: { {missing && ( - {props.requested} isn’t in this snapshot; showing {active}. + {props.requested} isn’t among the files listed from {rootPath === '/' ? 'the snapshot root' : `${rootPath}/`}; showing {active}. )} diff --git a/hooks/useContract.ts b/hooks/useContract.ts index 090321b..65c0308 100644 --- a/hooks/useContract.ts +++ b/hooks/useContract.ts @@ -1,6 +1,7 @@ import { NETWORKS, NetworkType, useNetwork } from '@/contexts/NetworkContext' +import { isCacheableMetadata, MetadataLoad, metadataLoadFromError, metadataLoadFromValue } from '@/utils/contractMetadata' import { ContractData, isContractData } from '@/utils/contracts' -import { isRpcFailure, viewFunction } from '@/utils/near/view' +import { viewFunction } from '@/utils/near/view' import { useCallback, useEffect, useState } from 'react' const TTL_MS = 60 * 1000 @@ -72,31 +73,18 @@ export function useContractRecord(accountId: string, enabled: boolean) { /* ---------------------------------------------------------------- metadata */ -export interface SourceMetadata { - version?: string - link?: string - standards?: { standard: string; version: string }[] - build_info?: { - build_environment?: string - build_command?: string[] - contract_path?: string - source_code_snapshot?: string - } -} - -export type MetadataLoad = - | { status: 'loading' } - | { status: 'missing' } // contract does not expose contract_source_metadata - | { status: 'error' } - | { status: 'ready'; metadata: SourceMetadata } - const metadataCache = new Map() -/** NEP-330 `contract_source_metadata` read from the contract itself. */ +/** + * NEP-330 `contract_source_metadata` read from the contract at the latest + * final block: the metadata of the code deployed now. A failed read is + * `unknown` with a retry and is never cached. + */ export function useSourceMetadata(accountId: string, enabled: boolean) { const { network } = useNetwork() const key = `${network}:${accountId}` const [state, setState] = useState<{ key: string; load: MetadataLoad }>({ key, load: { status: 'loading' } }) + const [attempt, setAttempt] = useState(0) useEffect(() => { if (!enabled) return @@ -107,16 +95,16 @@ export function useSourceMetadata(accountId: string, enabled: boolean) { } const controller = new AbortController() setState({ key, load: { status: 'loading' } }) - viewFunction(network, accountId, 'contract_source_metadata', undefined, controller.signal) - .then((metadata): MetadataLoad => (metadata && typeof metadata === 'object' ? { status: 'ready', metadata } : { status: 'missing' })) - .catch((error): MetadataLoad => (isRpcFailure(error) && error.kind !== 'unavailable' ? { status: 'missing' } : { status: 'error' })) + viewFunction(network, accountId, 'contract_source_metadata', undefined, controller.signal) + .then(metadataLoadFromValue, metadataLoadFromError) .then((load) => { if (controller.signal.aborted) return - if (load.status !== 'error') metadataCache.set(key, { at: Date.now(), load }) + if (isCacheableMetadata(load)) metadataCache.set(key, { at: Date.now(), load }) setState({ key, load }) }) return () => controller.abort() - }, [enabled, network, accountId, key]) + }, [enabled, network, accountId, key, attempt]) - return state.key === key ? state.load : ({ status: 'loading' } as MetadataLoad) + const retry = useCallback(() => setAttempt((n) => n + 1), []) + return { load: state.key === key ? state.load : ({ status: 'loading' } as MetadataLoad), retry } } diff --git a/hooks/useRecordedSource.ts b/hooks/useRecordedSource.ts new file mode 100644 index 0000000..7f65a6b --- /dev/null +++ b/hooks/useRecordedSource.ts @@ -0,0 +1,42 @@ +import type { NetworkType } from '@/contexts/NetworkContext' +import type { ContractData } from '@/utils/contracts' +import type { RecordedSource } from '@/utils/evidence' +import { githubFromGitCheckout, isGithubDto } from '@/utils/extractGithub' +import { readSnapshotCheckout } from '@/utils/sourceFiles' +import { useCallback, useEffect, useState } from 'react' + +/** + * Repository and commit of the recorded snapshot: the record's own `github` + * when it has one, otherwise the git checkout stored in the snapshot. + */ +export function useRecordedSource(network: NetworkType, data: ContractData | null) { + const recorded = data && isGithubDto(data.github) ? data.github : null + const cid = data?.cid + const key = `${network}:${cid}` + const [state, setState] = useState<{ key: string; source: RecordedSource }>({ key, source: { status: 'loading' } }) + const [attempt, setAttempt] = useState(0) + + useEffect(() => { + if (!cid || recorded) return + let active = true + setState({ key, source: { status: 'loading' } }) + readSnapshotCheckout(network, cid) + .then((checkout): RecordedSource => { + const github = checkout && githubFromGitCheckout(checkout.head, checkout.config) + return github ? { status: 'known', github, origin: 'snapshot' } : { status: 'none' } + }) + .catch((): RecordedSource => ({ status: 'unknown' })) + .then((source) => active && setState({ key, source })) + return () => { + active = false + } + }, [network, cid, key, recorded, attempt]) + + const retry = useCallback(() => setAttempt((n) => n + 1), []) + const source: RecordedSource = recorded + ? { status: 'known', github: recorded, origin: 'record' } + : state.key === key + ? state.source + : { status: 'loading' } + return { source, retry } +} diff --git a/pages/contract/[slug].tsx b/pages/contract/[slug].tsx index 734b877..daffc13 100644 --- a/pages/contract/[slug].tsx +++ b/pages/contract/[slug].tsx @@ -6,14 +6,16 @@ import Verdict, { VerdictPending } from '@/components/Contracts/Verdict' import BuildPane from '@/components/Workspace/BuildPane' import EvidencePane from '@/components/Workspace/EvidencePane' import SourcePane from '@/components/Workspace/SourcePane' +import PaneBoundary from '@/components/Common/PaneBoundary' import { NetworkType, useNetwork } from '@/contexts/NetworkContext' -import { GithubDto } from '@/Interfaces/github/github.dto' import { useAccountNetwork } from '@/hooks/useAccountNetwork' import { useCodeHashCheck } from '@/hooks/useCodeHashCheck' import { useContractRecord, useSourceMetadata } from '@/hooks/useContract' +import { useRecordedSource } from '@/hooks/useRecordedSource' import { langLabel } from '@/utils/contracts' import { detectNetworkFromAddress } from '@/utils/detectNetwork' -import { extractGitHubDetails } from '@/utils/extractGithub' +import { chooseSourceRoot, liveSource } from '@/utils/evidence' +import { githubFromSnapshot } from '@/utils/extractGithub' import { hasClientNavigated, registryUrl } from '@/utils/navigation' import { githubEntryPath } from '@/utils/sourceFiles' import { explorerContractUrl, workspaceHref } from '@/utils/urls' @@ -29,6 +31,7 @@ const TABS: { id: Tab; label: string }[] = [ { id: 'evidence', label: 'Evidence' }, { id: 'build', label: 'Build' }, ] +const PANE_LABEL: Record = { source: 'the verified source', evidence: 'the evidence', build: 'the build metadata' } const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v) const asTab = (v?: string): Tab => (v === 'evidence' || v === 'build' ? v : 'source') @@ -50,6 +53,7 @@ function Workspace({ accountId }: { accountId: string }) { const { load, retry } = useContractRecord(accountId, netState === 'ready') const data = netState === 'ready' && load.status === 'ready' ? load.data : null const metadata = useSourceMetadata(accountId, !!data) + const recorded = useRecordedSource(network, data) const { check, retry: retryHashCheck } = useCodeHashCheck(network, accountId, data?.code_hash) const headingRef = useRef(null) @@ -63,23 +67,22 @@ function Workspace({ accountId }: { accountId: string }) { const [backHref, setBackHref] = useState('/') useEffect(() => setBackHref(registryUrl()), []) - const github = useMemo(() => { - const snapshot = metadata.status === 'ready' ? metadata.metadata.build_info?.source_code_snapshot : undefined - if (snapshot) { - try { - return extractGitHubDetails(snapshot) - } catch { - // fall through to the registry record - } - } - const g = data?.github - return g && g.owner && g.repo && g.sha ? g : null - }, [metadata, data]) - - const contractPathMeta = metadata.status === 'ready' ? metadata.metadata.build_info?.contract_path : undefined - const rootPath = metadata.status === 'loading' ? null : contractPathMeta || '/' - const entryFile = github ? githubEntryPath(contractPathMeta, data?.lang) : '' - const entryFileUrl = github ? `https://github.com/${github.owner}/${github.repo}/blob/${github.sha}/${entryFile}` : null + // The current metadata describes the code deployed now; it stands in for the + // recorded snapshot only where it names the same repository and commit. + const live = useMemo(() => { + const load = metadata.load + const snapshot = load.status === 'ready' ? load.metadata.buildInfo?.sourceCodeSnapshot : null + return liveSource(load, githubFromSnapshot(snapshot)) + }, [metadata.load]) + // The reader's choice to open the folder the current metadata names, per snapshot. + const [hintOpenFor, setHintOpenFor] = useState(null) + const sourceRoot = chooseSourceRoot(recorded.source, live, requestedFile, !!data && hintOpenFor === data.cid) + const verifiedGithub = recorded.source.status === 'known' ? recorded.source.github : null + const entryFile = verifiedGithub && sourceRoot.verifiedDir !== null ? githubEntryPath(sourceRoot.verifiedDir, data?.lang) : '' + const entryFileUrl = + verifiedGithub && sourceRoot.verifiedDir !== null + ? `https://github.com/${verifiedGithub.owner}/${verifiedGithub.repo}/blob/${verifiedGithub.sha}/${entryFile}` + : null const linkNetwork = detectNetworkFromAddress(accountId) ? undefined : network const hrefFor = (opts: { tab?: Tab; file?: string | null }) => { @@ -198,12 +201,32 @@ function Workspace({ accountId }: { accountId: string }) { {!data ? ( - ) : tab === 'source' ? ( - hrefFor({ file })} onSelect={(file) => replaceQuery({ file })} check={check} /> - ) : tab === 'evidence' ? ( - ) : ( - + // One broken pane shows its own error instead of blanking the page. + + {tab === 'source' ? ( + { + // A file picked in the other folder would no longer be listed. + setHintOpenFor(open ? data.cid : null) + replaceQuery({ file: null }) + }} + onRetryMetadata={metadata.retry} + onRetrySnapshot={recorded.retry} + requested={requestedFile} + hrefFor={(file) => hrefFor({ file })} + onSelect={(file) => replaceQuery({ file })} + check={check} + /> + ) : tab === 'evidence' ? ( + + ) : ( + + )} + )} diff --git a/tests/evidence.test.cjs b/tests/evidence.test.cjs new file mode 100644 index 0000000..a725ab0 --- /dev/null +++ b/tests/evidence.test.cjs @@ -0,0 +1,121 @@ +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { metadataLoadFromValue } = require('../utils/contractMetadata.ts') +const { chooseSourceRoot, liveRelation, liveSource, sameSource } = require('../utils/evidence.ts') +const { githubFromGitCheckout, githubFromSnapshot, isGithubDto } = require('../utils/extractGithub.ts') + +const SHA = 'a2dd140892b68140bf7e70814604d3ba074d656c' +const LATER = '16d04f6ec4401263f8914638710260da50bb46b0' +const verified = { owner: 'near', repo: 'intents', sha: SHA } +const known = (github, origin = 'snapshot') => ({ status: 'known', github, origin }) + +/** Live source as the page builds it from a contract_source_metadata result. */ +function live(buildInfo) { + const load = metadataLoadFromValue({ build_info: buildInfo }) + return liveSource(load, githubFromSnapshot(buildInfo.source_code_snapshot)) +} +const deployedLater = live({ source_code_snapshot: `git+https://github.com/near/intents?rev=${LATER}`, contract_path: 'contracts/defuse' }) +const deployedSame = live({ source_code_snapshot: `git+https://github.com/near/intents?rev=${SHA}`, contract_path: 'contracts/defuse' }) + +test('a snapshot string is parsed into a link-safe repository and full commit, or nothing', () => { + assert.deepEqual(githubFromSnapshot(`git+https://github.com/near/intents.git?rev=${SHA}`), verified) + assert.deepEqual(githubFromSnapshot(`git+git@github.com:near/intents.git#${SHA}`), verified) + for (const value of [ + undefined, + null, + {}, + `https://github.com/near/intents?rev=${SHA}`, + `git+https://gitlab.com/near/intents?rev=${SHA}`, + 'git+https://github.com/near/intents?rev=main', + `git+https://github.com/near%2F..%2Fx/intents?rev=${SHA}`, + `git+https://github.com/-near/intents?rev=${SHA}`, + ]) + assert.equal(githubFromSnapshot(value), null, String(value)) + + assert.equal(isGithubDto(verified), true) + for (const value of [null, { ...verified, sha: SHA.slice(0, 12) }, { ...verified, repo: '..' }, { ...verified, owner: 'a/b' }, { owner: 'near', repo: 'intents' }]) + assert.equal(isGithubDto(value), false) +}) + +test('the git checkout stored in a snapshot names its repository and commit', () => { + const config = ['[core]', '\trepositoryformatversion = 0', '[remote "origin"]', '\turl = https://github.com/near/intents', '\tfetch = +refs/heads/*:refs/remotes/origin/*', '[branch "main"]', '\tremote = origin'].join('\n') + assert.deepEqual(githubFromGitCheckout(`${SHA}\n`, config), verified) + assert.deepEqual(githubFromGitCheckout(SHA, config.replace('https://github.com/near/intents', 'git@github.com:near/intents.git')), verified) + // A branch checkout, another remote or a non-GitHub remote doesn't pin a GitHub commit. + assert.equal(githubFromGitCheckout('ref: refs/heads/main\n', config), null) + assert.equal(githubFromGitCheckout(SHA, config.replace('[remote "origin"]', '[remote "fork"]')), null) + assert.equal(githubFromGitCheckout(SHA, config.replace('github.com', 'gitlab.com')), null) + assert.equal(githubFromGitCheckout(SHA, config.replace('intents\n', `intents?rev=${LATER}\n`)), null) +}) + +test('only the same repository and commit count as the same source', () => { + assert.equal(sameSource(verified, { owner: 'Near', repo: 'Intents', sha: SHA.toUpperCase() }), true) + assert.equal(sameSource(verified, { ...verified, sha: LATER }), false) + // A fork has the same commit but is not the recorded repository. + assert.equal(sameSource(verified, { ...verified, owner: 'someone' }), false) + + assert.equal(liveRelation(known(verified), deployedSame), 'same') + assert.equal(liveRelation(known(verified), deployedLater), 'different') + for (const recorded of [{ status: 'none' }, { status: 'unknown' }, { status: 'loading' }]) assert.equal(liveRelation(recorded, deployedLater), null) + assert.equal(liveRelation(known(verified), { status: 'unknown' }), null) +}) + +test('after a redeploy, the tree opens the snapshot root and only offers the folder from the current metadata', () => { + const root = chooseSourceRoot(known(verified), deployedLater, null, false) + assert.deepEqual(root, { rootPath: '/', basis: 'snapshot_root', hint: { status: 'offered', dir: 'contracts/defuse' }, verifiedDir: null }) + + // The reader opens it, or follows a link to a file inside it: labelled, never "verified". + for (const [requested, open] of [[null, true], ['contracts/defuse/src/lib.rs', false]]) + assert.deepEqual(chooseSourceRoot(known(verified), deployedLater, requested, open), { + rootPath: 'contracts/defuse', + basis: 'hint', + hint: { status: 'offered', dir: 'contracts/defuse' }, + verifiedDir: null, + }) + assert.equal(chooseSourceRoot(known(verified), deployedLater, 'contracts/defuse-old/src/lib.rs', false).rootPath, '/') +}) + +test('current metadata naming the recorded commit opens the verified crate folder', () => { + for (const origin of ['record', 'snapshot']) + assert.deepEqual(chooseSourceRoot(known(verified, origin), deployedSame, null, false), { + rootPath: 'contracts/defuse', + basis: 'verified', + hint: { status: 'none' }, + verifiedDir: 'contracts/defuse', + }) + const atRoot = live({ source_code_snapshot: `git+https://github.com/near/intents?rev=${SHA}` }) + assert.deepEqual(chooseSourceRoot(known(verified), atRoot, null, false), { rootPath: '/', basis: 'verified', hint: { status: 'none' }, verifiedDir: '' }) +}) + +test('without a recorded repository, nothing from the current metadata is treated as verified', () => { + for (const recorded of [{ status: 'none' }, { status: 'unknown' }]) { + const root = chooseSourceRoot(recorded, deployedSame, null, false) + assert.equal(root.basis, 'snapshot_root') + assert.equal(root.rootPath, '/') + assert.equal(root.verifiedDir, null) + assert.deepEqual(root.hint, { status: 'offered', dir: 'contracts/defuse' }) + } + // Still deciding: no folder is opened yet. + assert.equal(chooseSourceRoot({ status: 'loading' }, deployedSame, null, false).rootPath, null) + assert.equal(chooseSourceRoot(known(verified), { status: 'loading' }, null, false).rootPath, null) +}) + +test('a failed metadata read leaves the folder unknown, with no claim about the snapshot', () => { + const root = chooseSourceRoot(known(verified), liveSource({ status: 'unknown' }, null), 'contracts/defuse/src/lib.rs', true) + assert.deepEqual(root, { rootPath: '/', basis: 'snapshot_root', hint: { status: 'unknown' }, verifiedDir: null }) +}) + +test('no metadata, no build info or an unusable contract path offers nothing', () => { + for (const load of [ + { status: 'absent', reason: 'no_method' }, + { status: 'absent', reason: 'no_code' }, + { status: 'invalid' }, + metadataLoadFromValue({ version: '1.0.0' }), + ]) + assert.deepEqual(liveSource(load, null), { status: 'absent' }) + + const unusable = live({ source_code_snapshot: `git+https://github.com/near/intents?rev=${SHA}`, contract_path: '../outside' }) + assert.deepEqual(unusable, { status: 'ready', github: verified, contractDir: null }) + for (const current of [unusable, { status: 'absent' }]) + assert.deepEqual(chooseSourceRoot(known(verified), current, null, true), { rootPath: '/', basis: 'snapshot_root', hint: { status: 'none' }, verifiedDir: null }) +}) diff --git a/tests/metadata.test.cjs b/tests/metadata.test.cjs new file mode 100644 index 0000000..6979c5d --- /dev/null +++ b/tests/metadata.test.cjs @@ -0,0 +1,169 @@ +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { + contractDir, + isCacheableMetadata, + metadataLoadFromError, + metadataLoadFromValue, + parseSourceMetadata, +} = require('../utils/contractMetadata.ts') +const { viewFunction } = require('../utils/near/view.ts') + +const snapshot = 'git+https://github.com/near/example?rev=0123456789abcdef0123456789abcdef01234567' + +test('well-formed NEP-330 metadata is kept exactly as published', () => { + const metadata = parseSourceMetadata({ + version: '1.0.0', + link: 'https://github.com/near/example', + standards: [{ standard: 'nep330', version: '1.2.0' }, { standard: 'nep141', version: '1.0.0' }], + build_info: { + build_environment: 'sourcescan/cargo-near:0.13.4-rust-1.85.0@sha256:abc', + build_command: ['cargo', 'near', 'build', 'non-reproducible-wasm'], + contract_path: 'contracts/ft', + source_code_snapshot: snapshot, + }, + }) + assert.deepEqual(metadata, { + version: '1.0.0', + link: 'https://github.com/near/example', + standards: [{ standard: 'nep330', version: '1.2.0' }, { standard: 'nep141', version: '1.0.0' }], + buildInfo: { + buildEnvironment: 'sourcescan/cargo-near:0.13.4-rust-1.85.0@sha256:abc', + buildCommand: ['cargo', 'near', 'build', 'non-reproducible-wasm'], + contractPath: 'contracts/ft', + contractDir: 'contracts/ft', + sourceCodeSnapshot: snapshot, + }, + invalid: [], + }) +}) + +test('fields with the wrong type are dropped and flagged instead of rendered', () => { + const metadata = parseSourceMetadata({ + version: {}, + link: 5, + standards: [null, 'nep141', { standard: 'nep171', version: 1 }, { standard: 'nep330', version: '1.2.0' }], + build_info: { + build_environment: ['image'], + build_command: ['cargo', 3], + contract_path: { path: 'x' }, + source_code_snapshot: false, + }, + }) + assert.equal(metadata.version, null) + assert.equal(metadata.link, null) + assert.deepEqual(metadata.standards, [{ standard: 'nep330', version: '1.2.0' }]) + assert.deepEqual(metadata.buildInfo, { + buildEnvironment: null, + buildCommand: null, + contractPath: null, + contractDir: null, + sourceCodeSnapshot: null, + }) + assert.deepEqual( + [...metadata.invalid].sort(), + ['build_command', 'build_environment', 'contract_path', 'link', 'source_code_snapshot', 'standards', 'version'].sort() + ) + + assert.deepEqual(parseSourceMetadata({ standards: 'nep141', build_info: 'cargo near' }).invalid, ['standards', 'build_info']) + assert.equal(parseSourceMetadata({ build_info: [] }).buildInfo, null) +}) + +test('missing and null fields are "not specified", not invalid', () => { + const metadata = parseSourceMetadata({ version: null, standards: null, build_info: { contract_path: null } }) + assert.deepEqual(metadata.invalid, []) + assert.deepEqual(metadata.standards, []) + // NEP-330: an omitted contract_path is the repository root. + assert.equal(metadata.buildInfo.contractDir, '') + assert.equal(parseSourceMetadata({}).buildInfo, null) +}) + +test('duplicate standards collapse to one entry, so list keys stay unique', () => { + const metadata = parseSourceMetadata({ + standards: [ + { standard: 'nep141', version: '1.0.0' }, + { standard: 'nep141', version: '1.0.0' }, + { standard: 'nep141', version: '1.1.0' }, + ], + }) + assert.deepEqual(metadata.standards, [{ standard: 'nep141', version: '1.0.0' }, { standard: 'nep141', version: '1.1.0' }]) + assert.deepEqual(metadata.invalid, []) +}) + +test('contract_path becomes a folder inside the snapshot only when it is a plain relative path', () => { + for (const [path, dir] of [ + ['', ''], + ['.', ''], + ['./', ''], + ['/', ''], + ['contracts/ft', 'contracts/ft'], + ['./contracts/ft/', 'contracts/ft'], + ['/contracts/ft', 'contracts/ft'], + ['../outside', null], + ['contracts/../../outside', null], + ['contracts//ft', null], + ['contracts\\ft', null], + ['contracts/\nft', null], + ]) + assert.equal(contractDir(path), dir, JSON.stringify(path)) + + const metadata = parseSourceMetadata({ build_info: { contract_path: '../outside' } }) + assert.equal(metadata.buildInfo.contractPath, '../outside') + assert.equal(metadata.buildInfo.contractDir, null) + assert.deepEqual(metadata.invalid, ['contract_path']) +}) + +test('the method result maps to ready, absent or invalid', () => { + assert.deepEqual(metadataLoadFromValue(null), { status: 'absent', reason: 'null' }) + for (const value of [[], 'metadata', 1, true]) assert.deepEqual(metadataLoadFromValue(value), { status: 'invalid' }) + const load = metadataLoadFromValue({ version: {} }) + assert.equal(load.status, 'ready') + assert.deepEqual(load.metadata.invalid, ['version']) +}) + +function viewFunctionResult(value) { + return { result: { result: Array.from(Buffer.from(JSON.stringify(value), 'utf8')) } } +} + +test('only a missing method, code or account means "no metadata"; any failed read is unknown', async (t) => { + let response + t.mock.method(globalThis, 'fetch', async () => response()) + const load = () => + viewFunction('mainnet', 'example.near', 'contract_source_metadata', undefined, new AbortController().signal).then( + metadataLoadFromValue, + metadataLoadFromError + ) + const legacy = (error) => () => Response.json({ result: { error, block_height: 1 } }) + + response = legacy('wasm execution failed with error: MethodResolveError(MethodNotFound)') + assert.deepEqual(await load(), { status: 'absent', reason: 'no_method' }) + response = legacy('wasm execution failed with error: CompilationError(CodeDoesNotExist { account_id: "example.near" })') + assert.deepEqual(await load(), { status: 'absent', reason: 'no_code' }) + response = () => Response.json({ error: { cause: { name: 'UNKNOWN_ACCOUNT' }, data: 'account example.near does not exist while viewing' } }) + assert.deepEqual(await load(), { status: 'absent', reason: 'no_account' }) + + // A panic inside contract_source_metadata is not "doesn't expose it". + response = legacy('wasm execution failed with error: HostError(GuestPanic { panic_msg: "panicked at src/lib.rs" })') + assert.deepEqual(await load(), { status: 'unknown' }) + response = () => new Response(null, { status: 503 }) + assert.deepEqual(await load(), { status: 'unknown' }) + response = () => { + throw new TypeError('Failed to fetch') + } + assert.deepEqual(await load(), { status: 'unknown' }) + response = () => Response.json({ error: { cause: { name: 'UNKNOWN_BLOCK' } } }) + assert.deepEqual(await load(), { status: 'unknown' }) + response = () => Response.json({ result: { result: Array.from(Buffer.from('{not json')) } }) + assert.deepEqual(await load(), { status: 'unknown' }) + + response = () => Response.json(viewFunctionResult({ version: '1.0.0' })) + assert.equal((await load()).status, 'ready') +}) + +test('failed reads are never cached, answers from the chain are', () => { + assert.equal(isCacheableMetadata({ status: 'unknown' }), false) + assert.equal(isCacheableMetadata({ status: 'loading' }), false) + assert.equal(isCacheableMetadata({ status: 'absent', reason: 'no_method' }), true) + assert.equal(isCacheableMetadata({ status: 'invalid' }), true) + assert.equal(isCacheableMetadata(metadataLoadFromValue({})), true) +}) diff --git a/tests/registry.test.cjs b/tests/registry.test.cjs index 4286e75..e3e1396 100644 --- a/tests/registry.test.cjs +++ b/tests/registry.test.cjs @@ -178,7 +178,13 @@ test('view calls preserve query errors and reject malformed results', async (t) payload = { error: { cause: { name: 'UNKNOWN_ACCOUNT' } } } await assert.rejects(read(), { kind: 'unknown_account' }) - payload = { result: { error: 'Function call returned an error: MethodNotFound' } } + payload = { result: { error: 'wasm execution failed with error: MethodResolveError(MethodNotFound)' } } + await assert.rejects(read(), { kind: 'method_not_found' }) + payload = { error: { cause: { name: 'CONTRACT_EXECUTION_ERROR', info: { vm_error: 'MethodResolveError(MethodNotFound)' } }, data: 'Function call returned an error' } } + await assert.rejects(read(), { kind: 'method_not_found' }) + payload = { result: { error: 'wasm execution failed with error: CompilationError(CodeDoesNotExist { account_id: "example.testnet" })' } } + await assert.rejects(read(), { kind: 'no_contract_code' }) + payload = { result: { error: 'wasm execution failed with error: HostError(GuestPanic { panic_msg: "panicked at lib.rs" })' } } await assert.rejects(read(), { kind: 'execution_error' }) payload = { error: { cause: { name: 'UNKNOWN_BLOCK' } } } await assert.rejects(read(), { kind: 'unavailable' }) diff --git a/utils/contractMetadata.ts b/utils/contractMetadata.ts new file mode 100644 index 0000000..aa8a4f6 --- /dev/null +++ b/utils/contractMetadata.ts @@ -0,0 +1,164 @@ +import type { RpcErrorKind } from '@/utils/near/view' + +/* + * NEP-330 `contract_source_metadata`, parsed once into a typed shape. + * + * The value comes from the contract, so any field can have any JSON type. + * Fields with the wrong type are dropped and listed in `invalid`, so the UI + * can flag them instead of rendering (or crashing on) whatever was returned. + * Strings are kept exactly as published. + */ + +export type MetadataField = + | 'version' + | 'link' + | 'standards' + | 'build_info' + | 'build_environment' + | 'build_command' + | 'contract_path' + | 'source_code_snapshot' + +export interface Standard { + standard: string + version: string +} + +export interface BuildInfo { + buildEnvironment: string | null + buildCommand: string[] | null + /** `contract_path` exactly as published. */ + contractPath: string | null + /** + * `contract_path` as a folder inside the source snapshot ('' is the root), + * or null when it is absent or isn't a plain relative path. + */ + contractDir: string | null + sourceCodeSnapshot: string | null +} + +export interface SourceMetadata { + version: string | null + link: string | null + /** Unique by standard + version, in published order. */ + standards: Standard[] + buildInfo: BuildInfo | null + /** Fields that were present with the wrong type (or, for standards, had invalid entries). */ + invalid: MetadataField[] +} + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value) + +/** + * A relative folder of plain path segments ('' for the root). Leading "./", + * leading and trailing slashes are tolerated; "..", "." segments, backslashes + * and control characters are not. + */ +export function contractDir(path: string): string | null { + const trimmed = path.trim().replace(/^(\.\/)+/, '').replace(/^\/+|\/+$/g, '') + if (trimmed === '' || trimmed === '.') return '' + // eslint-disable-next-line no-control-regex + if (/[\\\u0000-\u001f\u007f]/.test(trimmed)) return null + const segments = trimmed.split('/') + return segments.every((s) => s !== '' && s !== '.' && s !== '..') ? segments.join('/') : null +} + +export function parseSourceMetadata(value: Record): SourceMetadata { + const invalid: MetadataField[] = [] + const text = (from: Record, key: MetadataField): string | null => { + const v = from[key] + if (v === undefined || v === null) return null + if (typeof v === 'string') return v + invalid.push(key) + return null + } + + const standards: Standard[] = [] + const rawStandards = value.standards + if (Array.isArray(rawStandards)) { + const seen = new Set() + let skipped = false + for (const s of rawStandards) { + if (!isRecord(s) || typeof s.standard !== 'string' || typeof s.version !== 'string') { + skipped = true + continue + } + const key = JSON.stringify([s.standard, s.version]) + if (seen.has(key)) continue + seen.add(key) + standards.push({ standard: s.standard, version: s.version }) + } + if (skipped) invalid.push('standards') + } else if (rawStandards !== undefined && rawStandards !== null) { + invalid.push('standards') + } + + let buildInfo: BuildInfo | null = null + const rawBuild = value.build_info + if (isRecord(rawBuild)) { + const command = rawBuild.build_command + let buildCommand: string[] | null = null + if (Array.isArray(command) && command.every((part) => typeof part === 'string')) buildCommand = command + else if (command !== undefined && command !== null) invalid.push('build_command') + // NEP-330: an omitted contract_path means the crate is at the root. + const rawPath = rawBuild.contract_path + let contractPath: string | null = null + let dir: string | null = '' + if (typeof rawPath === 'string') { + contractPath = rawPath + dir = contractDir(rawPath) + if (dir === null) invalid.push('contract_path') + } else if (rawPath !== undefined && rawPath !== null) { + dir = null + invalid.push('contract_path') + } + buildInfo = { + buildEnvironment: text(rawBuild, 'build_environment'), + buildCommand, + contractPath, + contractDir: dir, + sourceCodeSnapshot: text(rawBuild, 'source_code_snapshot'), + } + } else if (rawBuild !== undefined && rawBuild !== null) { + invalid.push('build_info') + } + + return { version: text(value, 'version'), link: text(value, 'link'), standards, buildInfo, invalid } +} + +/* ------------------------------------------------------------ load states */ + +export type MetadataLoad = + | { status: 'loading' } + | { status: 'ready'; metadata: SourceMetadata } + /** Facts read at the latest final block: nothing to show. */ + | { status: 'absent'; reason: 'no_method' | 'no_code' | 'no_account' | 'null' } + /** The method returned JSON that isn't a metadata object. */ + | { status: 'invalid' } + /** The read failed (RPC failure or the call itself errored): unknown, retry. */ + | { status: 'unknown' } + +/** A successful `contract_source_metadata` call, as a load state. */ +export function metadataLoadFromValue(value: unknown): MetadataLoad { + if (value === null) return { status: 'absent', reason: 'null' } + if (!isRecord(value)) return { status: 'invalid' } + return { status: 'ready', metadata: parseSourceMetadata(value) } +} + +/** + * A failed call, as a load state. Only errors that state a fact about the + * account or its code mean "no metadata"; a panic inside the method, a + * provider error or a malformed response leaves the metadata unknown. + */ +export function metadataLoadFromError(error: unknown): MetadataLoad { + const kind = (error as { kind?: RpcErrorKind } | null)?.kind + if (kind === 'method_not_found') return { status: 'absent', reason: 'no_method' } + if (kind === 'no_contract_code') return { status: 'absent', reason: 'no_code' } + if (kind === 'unknown_account') return { status: 'absent', reason: 'no_account' } + return { status: 'unknown' } +} + +/** Only answers read from the chain are cached; failures are retried on the next visit. */ +export const isCacheableMetadata = (load: MetadataLoad) => + load.status === 'ready' || load.status === 'absent' || load.status === 'invalid' diff --git a/utils/evidence.ts b/utils/evidence.ts new file mode 100644 index 0000000..8fd8d89 --- /dev/null +++ b/utils/evidence.ts @@ -0,0 +1,100 @@ +import type { GithubDto } from '@/Interfaces/github/github.dto' +import type { MetadataLoad } from '@/utils/contractMetadata' + +/* + * Which source a verification record refers to, and when the contract's + * current NEP-330 metadata may stand in for it. + * + * The registry records the IPFS snapshot (cid), the code hash and the block; + * it does not record a repository or contract path. The metadata read now + * describes whatever is deployed today, which can be a later build. So it is + * applied to the recorded snapshot only when it names the same repository and + * commit as the record itself; otherwise it is only shown labelled as current + * metadata, or offered as a folder the reader can choose to open. + */ + +/** Repository and commit of the recorded snapshot. */ +export type RecordedSource = + | { status: 'loading' } + /** From the registry record, or from the git checkout stored in the recorded snapshot. */ + | { status: 'known'; github: GithubDto; origin: 'record' | 'snapshot' } + /** Neither the record nor the snapshot names one. */ + | { status: 'none' } + /** The snapshot couldn't be read, so it is unknown. */ + | { status: 'unknown' } + +/** The contract's current NEP-330 build source, read at the latest final block. */ +export type LiveSource = + | { status: 'loading' } + /** + * `contractDir`: folder inside the source ('' = root), or null when the + * metadata has no usable contract path. + */ + | { status: 'ready'; github: GithubDto | null; contractDir: string | null } + /** No metadata, or no build info, at the latest final block. */ + | { status: 'absent' } + /** The metadata read failed. */ + | { status: 'unknown' } + +/** `github` is the repository parsed from the metadata's `source_code_snapshot`, if any. */ +export function liveSource(load: MetadataLoad, github: GithubDto | null): LiveSource { + if (load.status === 'loading' || load.status === 'unknown') return { status: load.status } + if (load.status !== 'ready' || !load.metadata.buildInfo) return { status: 'absent' } + return { status: 'ready', github, contractDir: load.metadata.buildInfo.contractDir } +} + +/** Same repository (GitHub names are case-insensitive) at the same commit. */ +export const sameSource = (a: GithubDto, b: GithubDto) => + a.owner.toLowerCase() === b.owner.toLowerCase() && + a.repo.toLowerCase() === b.repo.toLowerCase() && + a.sha.toLowerCase() === b.sha.toLowerCase() + +/** How the current metadata relates to the recorded snapshot, when that is known. */ +export function liveRelation(recorded: RecordedSource, live: LiveSource): 'same' | 'different' | null { + if (recorded.status !== 'known' || live.status !== 'ready' || !live.github) return null + return sameSource(recorded.github, live.github) ? 'same' : 'different' +} + +export type FolderHint = + | { status: 'none' } + /** The current metadata names this folder, but nothing ties it to the recorded snapshot. */ + | { status: 'offered'; dir: string } + /** The metadata read failed, so whether it names a folder is unknown. */ + | { status: 'unknown' } + +export interface SourceRoot { + /** Snapshot folder to list ('/' = snapshot root); null while it can't be decided yet. */ + rootPath: string | null + /** + * verified: the crate folder of the recorded source (the metadata names the same commit) + * snapshot_root: the root of the snapshot, because no folder is tied to the record + * hint: the folder the current metadata names, opened by the reader or by a link into it + */ + basis: 'pending' | 'verified' | 'snapshot_root' | 'hint' + hint: FolderHint + /** Crate folder of the recorded source ('' = root), when it is known. */ + verifiedDir: string | null +} + +const inDir = (file: string | null, dir: string) => !!file && file.startsWith(`${dir}/`) + +/** + * Picks the snapshot folder the source tree opens at. + * `requested` is the `?file=` path; `openHint` is the reader's choice to open the offered folder. + */ +export function chooseSourceRoot(recorded: RecordedSource, live: LiveSource, requested: string | null, openHint: boolean): SourceRoot { + const atRoot = (hint: FolderHint): SourceRoot => ({ rootPath: '/', basis: 'snapshot_root', hint, verifiedDir: null }) + if (live.status === 'loading') return { rootPath: null, basis: 'pending', hint: { status: 'none' }, verifiedDir: null } + if (live.status === 'unknown') return atRoot({ status: 'unknown' }) + if (live.status === 'absent' || live.contractDir === null) return atRoot({ status: 'none' }) + + const dir = live.contractDir + if (liveRelation(recorded, live) === 'same') + return { rootPath: dir || '/', basis: 'verified', hint: { status: 'none' }, verifiedDir: dir } + // A root crate path opens the root either way; nothing to offer. + if (dir === '') return atRoot({ status: 'none' }) + // Wait for the snapshot before deciding, so the tree doesn't open one folder and jump to another. + if (recorded.status === 'loading') return { rootPath: null, basis: 'pending', hint: { status: 'none' }, verifiedDir: null } + const hint: FolderHint = { status: 'offered', dir } + return openHint || inDir(requested, dir) ? { rootPath: dir, basis: 'hint', hint, verifiedDir: null } : atRoot(hint) +} diff --git a/utils/extractGithub.ts b/utils/extractGithub.ts index 631b285..108e707 100644 --- a/utils/extractGithub.ts +++ b/utils/extractGithub.ts @@ -1,3 +1,5 @@ +import type { GithubDto } from '@/Interfaces/github/github.dto' + function extractGitHubDetails(url: string) { if (typeof url !== 'string' || !url.startsWith('git+')) { throw new Error('Source snapshot must use git+ URL format') @@ -93,4 +95,54 @@ function getGithubPath(repoUrl: string): string { return new URL(repoUrl).pathname } -export { extractGitHubDetails } +// GitHub's own limits: owner 1-39 of [A-Za-z0-9-], repository 1-100 of [A-Za-z0-9._-]. +const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/ +const REPO = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/ +const SHA = /^[0-9a-f]{40}$/i + +/** A repository and full commit SHA that are safe to put into github.com links. */ +function isGithubDto(value: unknown): value is GithubDto { + const g = value as GithubDto | null + return ( + typeof g === 'object' && g !== null && + typeof g.owner === 'string' && OWNER.test(g.owner) && + typeof g.repo === 'string' && REPO.test(g.repo) && + typeof g.sha === 'string' && SHA.test(g.sha) + ) +} + +/** The GitHub repository and commit a NEP-330 `source_code_snapshot` names, or null. */ +function githubFromSnapshot(snapshot: unknown): GithubDto | null { + if (typeof snapshot !== 'string') return null + try { + const github = extractGitHubDetails(snapshot) + return isGithubDto(github) ? github : null + } catch { + return null + } +} + +/** + * The repository and commit of a git checkout, from its `.git/HEAD` (a + * detached commit) and the `origin` remote in `.git/config`. Null unless both + * name a GitHub repository and a full commit SHA. + */ +function githubFromGitCheckout(head: string, config: string): GithubDto | null { + const sha = head.trim() + if (!SHA.test(sha)) return null + let section = '' + let url: string | null = null + for (const raw of config.split(/\r?\n/)) { + const line = raw.trim() + if (line.startsWith('[')) { + section = line.replace(/\s+/g, ' ').toLowerCase() + continue + } + const m = section === '[remote "origin"]' ? /^url\s*=\s*(.+)$/i.exec(line) : null + if (m) url = m[1].trim() + } + if (!url || /[?#\s]/.test(url)) return null + return githubFromSnapshot(`git+${url}#${sha}`) +} + +export { extractGitHubDetails, githubFromGitCheckout, githubFromSnapshot, isGithubDto } diff --git a/utils/near/view.ts b/utils/near/view.ts index 935e7ac..deeef04 100644 --- a/utils/near/view.ts +++ b/utils/near/view.ts @@ -5,7 +5,7 @@ const RPC_URLS: Record = { testnet: 'https://near-testnet.drpc.org', } -type RpcErrorKind = 'unknown_account' | 'no_contract_code' | 'execution_error' | 'unavailable' +export type RpcErrorKind = 'unknown_account' | 'no_contract_code' | 'method_not_found' | 'execution_error' | 'unavailable' interface RpcFailure extends Error { kind: RpcErrorKind @@ -13,7 +13,7 @@ interface RpcFailure extends Error { } interface QueryError { - cause?: { name?: unknown; info?: { block_height?: unknown } } + cause?: { name?: unknown; info?: { block_height?: unknown; vm_error?: unknown } } data?: unknown message?: unknown } @@ -40,13 +40,22 @@ export const isNearCodeHash = (value: unknown): value is string => const classify = (error: QueryError, legacyBlockHeight?: unknown): RpcFailure => { const cause = String(error?.cause?.name ?? '') const detail = String(error?.data ?? error?.message ?? '') + // Structured errors carry the VM error separately; legacy ones only in `data`. + const vmError = `${detail} ${String(error?.cause?.info?.vm_error ?? '')}` const blockHeight = readBlockHeight(error?.cause?.info?.block_height ?? legacyBlockHeight) if (cause === 'UNKNOWN_ACCOUNT' || (!cause && /account \S+ does not exist while viewing/i.test(detail))) return failure('unknown_account', detail, blockHeight) - if (cause === 'NO_CONTRACT_CODE' || (!cause && /Contract code for contract ID \S+ has never been observed on the node/i.test(detail))) + if ( + cause === 'NO_CONTRACT_CODE' || + (!cause && /Contract code for contract ID \S+ has never been observed on the node/i.test(detail)) || + /CompilationError\(CodeDoesNotExist\b/.test(vmError) + ) return failure('no_contract_code', detail, blockHeight) - if (cause === 'CONTRACT_EXECUTION_ERROR' || /wasm execution failed|Function call returned an error/i.test(detail)) + if (cause === 'CONTRACT_EXECUTION_ERROR' || /wasm execution failed|Function call returned an error/i.test(detail)) { + // The contract has code but no such method: a fact about the code, not a failed call. + if (/\bMethodNotFound\b/.test(vmError)) return failure('method_not_found', detail) return failure('execution_error', detail) + } return failure('unavailable', detail || 'RPC request failed') } diff --git a/utils/sourceFiles.ts b/utils/sourceFiles.ts index bf9518a..0fc2bd0 100644 --- a/utils/sourceFiles.ts +++ b/utils/sourceFiles.ts @@ -147,6 +147,31 @@ export async function fetchSource(network: NetworkType, cid: string, path: strin return text } +const checkoutCache = new Map() + +/** + * `.git/HEAD` and `.git/config` of the git checkout stored at the snapshot + * root, or null when the snapshot has no `.git` folder (older SourceScan + * snapshots don't keep one). Throws when the snapshot can't be read. A + * snapshot is content-addressed, so a successful answer is kept. + */ +export async function readSnapshotCheckout(network: NetworkType, cid: string) { + const key = `${network}:${cid}` + const hit = checkoutCache.get(key) + if (hit !== undefined) return hit + const root = await structure(network, cid, '/') + let checkout: { head: string; config: string } | null = null + if (root.some((entry) => entry.type === 'dir' && entry.name === '.git')) { + const [head, config] = await Promise.all([ + fetchSourceFile(network, cid, '.git/HEAD'), + fetchSourceFile(network, cid, '.git/config'), + ]) + checkout = { head, config } + } + checkoutCache.set(key, checkout) + return checkout +} + /** lib.rs for Rust contracts, otherwise the first path (same rule as before). */ export const entryPath = (paths: string[], lang?: string) => (lang === 'rust' && paths.find((p) => p === 'src/lib.rs' || p.endsWith('/lib.rs') || p === 'lib.rs')) || paths[0] From 366668aa413018412a5a27f8a8fce5868bc443f6 Mon Sep 17 00:00:00 2001 From: Andrey Gruzdev Date: Sat, 28 Nov 2026 16:26:53 +0100 Subject: [PATCH 3/7] fix(rpc): classify call failures by error type, not message text The classifier searched the whole error text for MethodNotFound and CodeDoesNotExist, so a panic whose message mentioned either became a cacheable "doesn't expose contract_source_metadata". Structured errors are now classified by their cause name, and a contract execution error by the top-level FunctionCallError variant in vm_error (or after the legacy message prefix), matched as a whole. Legacy messages are matched whole, never as fragments. Anything else is a failed call: unknown, with a retry. Co-Authored-By: Claude Opus 5.5 --- tests/metadata.test.cjs | 23 ++++++++++++++++++-- utils/near/view.ts | 47 +++++++++++++++++++++++++++-------------- 2 files changed, 52 insertions(+), 18 deletions(-) diff --git a/tests/metadata.test.cjs b/tests/metadata.test.cjs index 6979c5d..444cf2e 100644 --- a/tests/metadata.test.cjs +++ b/tests/metadata.test.cjs @@ -142,8 +142,27 @@ test('only a missing method, code or account means "no metadata"; any failed rea response = () => Response.json({ error: { cause: { name: 'UNKNOWN_ACCOUNT' }, data: 'account example.near does not exist while viewing' } }) assert.deepEqual(await load(), { status: 'absent', reason: 'no_account' }) - // A panic inside contract_source_metadata is not "doesn't expose it". - response = legacy('wasm execution failed with error: HostError(GuestPanic { panic_msg: "panicked at src/lib.rs" })') + response = () => + Response.json({ error: { name: 'HANDLER_ERROR', cause: { name: 'CONTRACT_EXECUTION_ERROR', info: { vm_error: 'MethodResolveError(MethodNotFound)' } } } }) + assert.deepEqual(await load(), { status: 'absent', reason: 'no_method' }) + response = () => Response.json({ error: { cause: { name: 'NO_CONTRACT_CODE', info: {} }, data: 'Contract code for contract ID #example.near has never been observed on the node' } }) + assert.deepEqual(await load(), { status: 'absent', reason: 'no_code' }) + + // A panic inside contract_source_metadata is not "doesn't expose it", whatever its message says. + for (const panic of [ + 'HostError(GuestPanic { panic_msg: "panicked at src/lib.rs" })', + 'HostError(GuestPanic { panic_msg: "Unexpected MethodNotFound from lookup" })', + 'HostError(GuestPanic { panic_msg: "MethodResolveError(MethodNotFound)" })', + 'HostError(GuestPanic { panic_msg: "CompilationError(CodeDoesNotExist { account_id: x })" })', + 'MethodResolveError(MethodEmptyName)', + ]) { + response = legacy(`wasm execution failed with error: ${panic}`) + assert.deepEqual(await load(), { status: 'unknown' }, `legacy ${panic}`) + response = () => Response.json({ error: { cause: { name: 'CONTRACT_EXECUTION_ERROR', info: { vm_error: panic } }, data: `Function call returned an error: ${panic}` } }) + assert.deepEqual(await load(), { status: 'unknown' }, `structured ${panic}`) + } + // A message that merely mentions MethodNotFound, outside an execution error, is a provider failure. + response = legacy('provider error: MethodResolveError(MethodNotFound)') assert.deepEqual(await load(), { status: 'unknown' }) response = () => new Response(null, { status: 503 }) assert.deepEqual(await load(), { status: 'unknown' }) diff --git a/utils/near/view.ts b/utils/near/view.ts index deeef04..788d92c 100644 --- a/utils/near/view.ts +++ b/utils/near/view.ts @@ -37,25 +37,40 @@ const readBlockHeight = (value: unknown): number | undefined => export const isNearCodeHash = (value: unknown): value is string => typeof value === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(value) +/** + * The outcome of a failed contract call, from nearcore's FunctionCallError + * (its Debug form, as `vm_error` or after the legacy message prefix). Only + * the top-level variant is read, so text inside a panic message can never + * turn a failed call into a statement about the contract. + */ +const executionFailure = (vmError: string, detail: string): RpcFailure => { + if (/^MethodResolveError\(MethodNotFound\)$/.test(vmError)) return failure('method_not_found', detail) + if (/^CompilationError\(CodeDoesNotExist \{/.test(vmError)) return failure('no_contract_code', detail) + return failure('execution_error', detail) +} + +const LEGACY_EXECUTION = /^(?:Function call returned an error: )?wasm execution failed with error: ([\s\S]*)$/ + const classify = (error: QueryError, legacyBlockHeight?: unknown): RpcFailure => { - const cause = String(error?.cause?.name ?? '') - const detail = String(error?.data ?? error?.message ?? '') - // Structured errors carry the VM error separately; legacy ones only in `data`. - const vmError = `${detail} ${String(error?.cause?.info?.vm_error ?? '')}` + const cause = typeof error?.cause?.name === 'string' ? error.cause.name : '' + const detail = String(error?.data ?? error?.message ?? '').trim() const blockHeight = readBlockHeight(error?.cause?.info?.block_height ?? legacyBlockHeight) - if (cause === 'UNKNOWN_ACCOUNT' || (!cause && /account \S+ does not exist while viewing/i.test(detail))) - return failure('unknown_account', detail, blockHeight) - if ( - cause === 'NO_CONTRACT_CODE' || - (!cause && /Contract code for contract ID \S+ has never been observed on the node/i.test(detail)) || - /CompilationError\(CodeDoesNotExist\b/.test(vmError) - ) - return failure('no_contract_code', detail, blockHeight) - if (cause === 'CONTRACT_EXECUTION_ERROR' || /wasm execution failed|Function call returned an error/i.test(detail)) { - // The contract has code but no such method: a fact about the code, not a failed call. - if (/\bMethodNotFound\b/.test(vmError)) return failure('method_not_found', detail) - return failure('execution_error', detail) + // Structured errors: the cause name is the error type. + if (cause) { + if (cause === 'UNKNOWN_ACCOUNT') return failure('unknown_account', detail, blockHeight) + if (cause === 'NO_CONTRACT_CODE') return failure('no_contract_code', detail, blockHeight) + if (cause === 'CONTRACT_EXECUTION_ERROR') { + const vmError = error?.cause?.info?.vm_error + return executionFailure(typeof vmError === 'string' ? vmError.trim() : LEGACY_EXECUTION.exec(detail)?.[1] ?? '', detail) + } + return failure('unavailable', detail || 'RPC request failed') } + // Legacy errors are only a message: match nearcore's whole message, never a fragment of it. + if (/^account \S+ does not exist while viewing$/.test(detail)) return failure('unknown_account', detail, blockHeight) + if (/^Contract code for contract ID #?\S+ has never been observed on the node$/.test(detail)) + return failure('no_contract_code', detail, blockHeight) + const execution = LEGACY_EXECUTION.exec(detail) + if (execution) return executionFailure(execution[1], detail) return failure('unavailable', detail || 'RPC request failed') } From 5c66f383be94f78a382636474313cfd15dbc808f Mon Sep 17 00:00:00 2001 From: Andrey Gruzdev Date: Sat, 28 Nov 2026 16:26:53 +0100 Subject: [PATCH 4/7] fix(contract): never present the current contract path as the verified crate Review of #13 found that the same repository and commit don't identify the crate: one commit can hold several, and the registry records none. The source tree now opens the folder from the contract's current metadata only under a "current metadata" label, even when the commit matches, and Evidence no longer links an entry file. - The folder choice depends only on the current metadata, the ?file= link and the reader's choice. A link opens its own folder without waiting for the metadata, and a linked file that the listing doesn't show is opened directly; failing that, the tree says it couldn't open it rather than that it is absent. - The snapshot's git checkout is read only for the Evidence and Build tabs, with a 10 s timeout, and parsed strictly: one exact [remote "origin"] with one plain GitHub repository URL and a detached HEAD, else "Not recorded" with the reason. - A folder listing that isn't a listing is unreadable (unknown, retried), not an empty folder; failed and partial listings are never cached. Each folder is listed once and shared, and .git is never listed. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- components/Workspace/BuildPane.tsx | 12 +++ components/Workspace/EvidencePane.tsx | 17 +--- components/Workspace/SourcePane.tsx | 132 +++++++++++++++++-------- hooks/useRecordedSource.ts | 20 ++-- pages/contract/[slug].tsx | 30 +++--- tests/evidence.test.cjs | 133 +++++++++++++++++--------- tests/sourceFiles.test.cjs | 100 +++++++++++++++++++ utils/evidence.ts | 98 ++++++++++++------- utils/extractGithub.ts | 55 ++++++++--- utils/sourceFiles.ts | 122 +++++++++++++++-------- 11 files changed, 512 insertions(+), 209 deletions(-) create mode 100644 tests/sourceFiles.test.cjs diff --git a/README.md b/README.md index 144c6d0..4254f33 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ The registry rows show recorded verifications. The contract workspace checks dep Registry totals come from the REST API configured by `NEXT_PUBLIC_API_HOST`. IPFS source snapshots use the app's `/api/proxy-ipfs` route. -The Evidence tab names the repository and commit of the recorded snapshot: the record's own `github`, or the git checkout stored in the snapshot. The contract's NEP-330 metadata, read at the latest final block, is shown on the Build tab as current metadata. It picks the source tree's folder only when it names that same repository and commit. +The Evidence tab names the repository and commit of the recorded snapshot: the record's own `github`, or the git checkout stored in the snapshot. The contract's NEP-330 metadata, read at the latest final block, is shown on the Build tab as current metadata. The source tree opens the folder it names, labelled as current metadata: the registry doesn't record which crate was built. The snapshot's git checkout is read only when the Evidence or Build tab is open. ## Learn More diff --git a/components/Workspace/BuildPane.tsx b/components/Workspace/BuildPane.tsx index c88f69f..49e96a1 100644 --- a/components/Workspace/BuildPane.tsx +++ b/components/Workspace/BuildPane.tsx @@ -2,9 +2,11 @@ import CopyButton from '@/components/Common/CopyButton' import ExternalTextLink from '@/components/Common/ExternalTextLink' import GithubLink from '@/components/Common/GithubLink' import { Field, Fields, Panel } from '@/components/Common/Panel' +import type { GithubDto } from '@/Interfaces/github/github.dto' import { parseImageRef, registryPage } from '@/utils/buildImage' import type { MetadataField, MetadataLoad } from '@/utils/contractMetadata' import { liveRelation, LiveSource, RecordedSource } from '@/utils/evidence' +import { githubTreeUrl } from '@/utils/urls' import { Badge, Box, Button, Code, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react' import { ReactNode } from 'react' @@ -56,6 +58,9 @@ function BuildImage(props: { value: string }) { const TITLE = 'Current build metadata (NEP-330)' +const githubFolderUrl = (g: GithubDto, dir: string) => + `${githubTreeUrl(g)}/${dir.split('/').map(encodeURIComponent).join('/')}` + const ABSENT: Record['reason'], string> = { no_method: 'The deployed contract doesn’t expose contract_source_metadata, so no build metadata is published on-chain.', no_code: 'No contract code is deployed on this account at the latest final block, so there is no build metadata.', @@ -152,6 +157,13 @@ export default function BuildPane(props: { metadata: MetadataLoad; onRetry: () = {build.contractPath} {bad('contract_path') && Not a relative folder inside the source, so it isn’t used to open the source.} + {liveGithub && build.contractDir && ( + + + This folder on GitHub at the current metadata’s commit + + + )} ) : bad('contract_path') ? ( wrongType diff --git a/components/Workspace/EvidencePane.tsx b/components/Workspace/EvidencePane.tsx index ac576da..32a5113 100644 --- a/components/Workspace/EvidencePane.tsx +++ b/components/Workspace/EvidencePane.tsx @@ -58,8 +58,11 @@ function RecordedRepository(props: { recorded: RecordedSource; onRetry: () => vo ) return ( - Not recorded. The registry stores the snapshot above, not a repository, and the snapshot has no git checkout that names one. The Build tab shows the - repository named in the contract’s current metadata, which may describe a later deployment. + Not recorded. The registry stores the snapshot above, not a repository, and{' '} + {recorded.reason === 'no_checkout' + ? 'the snapshot has no git checkout.' + : 'the git checkout in the snapshot doesn’t name exactly one GitHub repository and commit.'}{' '} + The Build tab shows the repository named in the contract’s current metadata, which may describe a later deployment. ) } @@ -71,9 +74,6 @@ export default function EvidencePane(props: { check: HashCheck recorded: RecordedSource onRetryRecorded: () => void - /** Entry file on GitHub, only when the recorded source and its crate folder are both known. */ - entryFileUrl: string | null - entryFile: string }) { const { accountId, network, data, check } = props return ( @@ -118,13 +118,6 @@ export default function EvidencePane(props: { - {props.entryFileUrl && ( - - - {props.entryFile || 'Repository root'} - - - )} {NETWORKS[network].contract} diff --git a/components/Workspace/SourcePane.tsx b/components/Workspace/SourcePane.tsx index 2659486..295bf3e 100644 --- a/components/Workspace/SourcePane.tsx +++ b/components/Workspace/SourcePane.tsx @@ -4,7 +4,7 @@ import { verdictTone } from '@/components/Contracts/Verdict' import type { NetworkType } from '@/contexts/NetworkContext' import type { HashCheck } from '@/hooks/useCodeHashCheck' import type { ContractData } from '@/utils/contracts' -import type { SourceRoot } from '@/utils/evidence' +import { FolderChoice, isSnapshotFilePath, SourceRoot } from '@/utils/evidence' import { cachedSource, cachedSourcePaths, entryPath, fetchSource, listSourcePaths } from '@/utils/sourceFiles' import { HEADER_H } from '@/utils/theme' import { ipfsFileUrl } from '@/utils/urls' @@ -42,18 +42,20 @@ const STRIPE: Record = { unavailable: 'The deployed code could not be checked.', } -type Files = { key: string; status: 'loading' | 'error' | 'ready'; paths: string[] } +type Files = { key: string; status: 'loading' | 'error' | 'ready'; paths: string[]; partial: boolean } type Content = { key: string; status: 'loading' | 'error' | 'ready'; text: string } /** - * Says where the tree is opened when the record doesn't prove the folder: - * the folder the current metadata names is only offered, labelled as such. + * Says which folder the tree shows and where that came from. The registry + * doesn't record which crate was built, so a folder taken from the current + * metadata is always labelled as such, even when it names the recorded commit. */ -function FolderNotice(props: { root: SourceRoot; onOpenHint: (_open: boolean) => void; onRetryMetadata: () => void }) { +function FolderNotice(props: { root: SourceRoot; onChooseFolder: (_choice: FolderChoice) => void; onRetryMetadata: () => void }) { const { root } = props const hint = root.hint if (hint.status === 'none') return null const warn = hint.status === 'unknown' + const where = root.basis === 'link' ? <>Showing {root.rootPath}/, the folder of the linked file. : <>Showing the snapshot root. return ( > {hint.status === 'unknown' ? ( - <>Couldn’t read the contract’s current metadata, so it’s unknown which folder of this snapshot holds the contract. Showing the snapshot root. - ) : root.basis === 'hint' ? ( + <>Couldn’t read the contract’s current metadata, so it’s unknown which folder of this snapshot holds the contract. {where} + ) : root.basis === 'current_metadata' ? ( <> - Showing {hint.dir}, the folder named in the contract’s current metadata. The verification record doesn’t name a folder, so - this may not be the crate that was verified. + Showing {hint.dir}/, the folder named in the contract’s current metadata. The verification record doesn’t name the crate + that was built, so this may not be the verified crate. ) : ( <> - The verification record doesn’t name the contract’s folder in this snapshot. The contract’s current metadata names{' '} - {hint.dir}, which may describe a later deployment. + The contract’s current metadata names {hint.dir}/. The verification record doesn’t name the crate that was built. )} @@ -90,12 +91,12 @@ function FolderNotice(props: { root: SourceRoot; onOpenHint: (_open: boolean) => - ) : root.basis === 'hint' ? ( - ) : ( - )} @@ -107,20 +108,18 @@ export default function SourcePane(props: { network: NetworkType data: ContractData root: SourceRoot - onOpenHint: (_open: boolean) => void + onChooseFolder: (_choice: FolderChoice) => void onRetryMetadata: () => void - /** Also re-reads the snapshot's git checkout when the snapshot couldn't be opened. */ - onRetrySnapshot: () => void /** `?file=` from the URL. */ requested: string | null hrefFor: (_file: string) => string onSelect: (_file: string) => void check: HashCheck }) { - const { root, onOpenHint, onRetryMetadata, ...tree } = props + const { root, onChooseFolder, onRetryMetadata, ...tree } = props return ( <> - + ) @@ -131,7 +130,6 @@ function SourceTree(props: { data: ContractData /** Snapshot folder to list ('/' = root); null while it is still being decided. */ rootPath: string | null - onRetrySnapshot: () => void /** `?file=` from the URL. */ requested: string | null hrefFor: (_file: string) => string @@ -149,18 +147,18 @@ function SourceTree(props: { const filesKey = `${network}:${data.cid}:${rootPath}` const [files, setFiles] = useState(() => { const hit = rootPath !== null ? cachedSourcePaths(network, data.cid, rootPath) : undefined - return { key: filesKey, status: hit ? 'ready' : 'loading', paths: hit ?? [] } + return { key: filesKey, status: hit ? 'ready' : 'loading', paths: hit ?? [], partial: false } }) useEffect(() => { if (rootPath === null) return const hit = cachedSourcePaths(network, data.cid, rootPath) - if (hit) return setFiles({ key: filesKey, status: 'ready', paths: hit }) + if (hit) return setFiles({ key: filesKey, status: 'ready', paths: hit, partial: false }) let active = true - setFiles({ key: filesKey, status: 'loading', paths: [] }) + setFiles({ key: filesKey, status: 'loading', paths: [], partial: false }) listSourcePaths(network, data.cid, rootPath) - .then((paths) => active && setFiles({ key: filesKey, status: 'ready', paths })) - .catch(() => active && setFiles({ key: filesKey, status: 'error', paths: [] })) + .then(({ paths, partial }) => active && setFiles({ key: filesKey, status: 'ready', paths, partial })) + .catch(() => active && setFiles({ key: filesKey, status: 'error', paths: [], partial: false })) return () => { active = false } @@ -168,8 +166,22 @@ function SourceTree(props: { const ready = files.key === filesKey && files.status === 'ready' const paths = useMemo(() => (ready ? files.paths : []), [ready, files.paths]) - const missing = ready && !!props.requested && !paths.includes(props.requested) - const active = ready ? (props.requested && paths.includes(props.requested) ? props.requested : entryPath(paths, data.lang)) : props.requested + const partial = ready && files.partial + // A linked file opens even when the listing doesn't show it (it can sit + // deeper than one folder below the root). Only when reading it fails does + // the tree fall back to its entry file, without claiming the file is absent. + const requested = props.requested && isSnapshotFilePath(props.requested) ? props.requested : null + const listed = !!requested && paths.includes(requested) + const linkKey = requested ? `${data.cid}:${requested}` : null + const [linkFailed, setLinkFailed] = useState(null) + const openLink = !!requested && (listed || linkFailed !== linkKey) + const active = ready ? (openLink ? requested : entryPath(paths, data.lang)) : props.requested + const unlistedLink = ready && openLink && !listed + const linkFallback = ready && !!props.requested && !openLink + const retryLink = () => { + setLinkFailed(null) + setContentAttempt((n) => n + 1) + } const contentKey = `${data.cid}:${active}` const [content, setContent] = useState(() => { @@ -185,11 +197,15 @@ function SourceTree(props: { setContent({ key: contentKey, status: 'loading', text: '' }) fetchSource(network, data.cid, active) .then((text) => active_ && setContent({ key: contentKey, status: 'ready', text })) - .catch(() => active_ && setContent({ key: contentKey, status: 'error', text: '' })) + .catch(() => { + if (!active_) return + if (active === requested && !listed) setLinkFailed(linkKey) + else setContent({ key: contentKey, status: 'error', text: '' }) + }) return () => { active_ = false } - }, [ready, active, network, data.cid, contentKey, contentAttempt]) + }, [ready, active, network, data.cid, contentKey, contentAttempt, requested, listed, linkKey]) // Only ever show the content that belongs to the file named in the header. const shown: Content = content.key === contentKey ? content : { key: contentKey, status: 'loading', text: '' } @@ -262,24 +278,35 @@ function SourceTree(props: { Couldn’t open the IPFS snapshot The verified source for this record could not be read from IPFS right now. - ) - if (ready && paths.length === 0) + if (ready && paths.length === 0 && !openLink) return (
- The snapshot has no .rs or .toml files at {rootPath === '/' ? 'its root' : rootPath} or one folder below it. + + {linkFallback && Couldn’t open {props.requested} from this snapshot.} + + No .rs or .toml files at {rootPath === '/' ? 'the snapshot root' : `${rootPath}/`} or one folder below it + {partial ? ', but some of those folders couldn’t be read.' : '.'} + + {(partial || (linkFallback && requested)) && ( + + )} +
) @@ -346,6 +373,14 @@ function SourceTree(props: {
)}
+ {partial && ( + + Some folders couldn’t be read. + + + )} {ready ? `Rust and TOML files: ${paths.length}` : 'Reading snapshot…'} @@ -358,6 +393,7 @@ function SourceTree(props: {