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/README.md b/README.md
index f6d865d..4254f33 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. 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
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..675f83a 100644
--- a/components/Workspace/BuildPane.tsx
+++ b/components/Workspace/BuildPane.tsx
@@ -1,9 +1,13 @@
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 type { GithubDto } from '@/Interfaces/github/github.dto'
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 { githubTreeUrl } from '@/utils/urls'
+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 +16,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 +56,152 @@ function BuildImage(props: { value: string }) {
)
}
-export default function BuildPane(props: { metadata: MetadataLoad }) {
+const TITLE = 'Current build metadata (NEP-330)'
+
+/** The folder on GitHub, or null when the path can't be put into a URL. */
+function githubFolderUrl(g: GithubDto, dir: string): string | null {
+ try {
+ return `${githubTreeUrl(g)}/${dir.split('/').map(encodeURIComponent).join('/')}`
+ } catch {
+ return null
+ }
+}
+
+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.
+
+ Try again
+
+
+
+ )
+ 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
+ const folderUrl = liveGithub && build?.contractDir ? githubFolderUrl(liveGithub, build.contractDir) : 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. }
+ {folderUrl && (
+
+
+ This folder on GitHub at the current metadata’s commit
+
+
+ )}
+
+ ) : 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..32a5113 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,14 +18,62 @@ 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.
+
+
+ Try again
+
+
+ )
+ return (
+
+ 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.
+
+ )
+}
+
export default function EvidencePane(props: {
accountId: string
network: NetworkType
data: ContractData
check: HashCheck
- github: GithubDto | null
- entryFileUrl: string | null
- entryFile: string
+ recorded: RecordedSource
+ onRetryRecorded: () => void
}) {
const { accountId, network, data, check } = props
return (
@@ -67,14 +115,9 @@ export default function EvidencePane(props: {
- {props.github ? : Not published }
- {props.github && props.entryFileUrl && (
-
-
- {props.entryFile || 'Repository root'}
-
-
- )}
+
+
+
{NETWORKS[network].contract}
diff --git a/components/Workspace/SourcePane.tsx b/components/Workspace/SourcePane.tsx
index 3e2ae08..6862aab 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 { FolderChoice, folderUnknown, 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'
@@ -11,7 +12,9 @@ import {
Box,
Button,
Center,
+ Code,
Flex,
+ HStack,
Icon,
Input,
InputGroup,
@@ -40,14 +43,102 @@ 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 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; onChooseFolder: (_choice: FolderChoice) => void; onRetryMetadata: () => void }) {
+ const { root } = props
+ const hint = root.hint
+ const atLink = root.basis === 'link'
+ if (hint.status === 'none' && !atLink) return null
+ const warn = hint.status === 'unknown'
+ const linkFolder = (
+ <>
+ Showing {root.rootPath}/, the folder of the linked file.
+ >
+ )
+ const button = (label: string, onClick: () => void, mono = false) => (
+
+ {label}
+
+ )
+ return (
+
+
+ {hint.status === 'unknown' ? (
+ <>Couldn’t read the contract’s current metadata, so it’s unknown which folder of this snapshot holds the contract. {atLink ? linkFolder : 'Showing the snapshot root.'}>
+ ) : root.basis === 'current_metadata' && hint.status === 'offered' ? (
+ <>
+ 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.
+ >
+ ) : hint.status === 'offered' ? (
+ <>
+ {atLink && <>{linkFolder} >}The contract’s current metadata names {hint.dir}/. The verification record doesn’t name the
+ crate that was built.
+ >
+ ) : (
+ linkFolder
+ )}
+
+
+ {hint.status === 'unknown' && button('Try again', props.onRetryMetadata)}
+ {hint.status === 'offered' && root.basis !== 'current_metadata' && button(`Open ${hint.dir}/`, () => props.onChooseFolder('metadata'), true)}
+ {(root.basis === 'current_metadata' || atLink) && button('Show snapshot root', () => props.onChooseFolder('root'))}
+
+
+ )
+}
+
export default function SourcePane(props: {
network: NetworkType
data: ContractData
- /** NEP-330 contract_path, '/' when absent; null while metadata is still loading. */
+ root: SourceRoot
+ onChooseFolder: (_choice: FolderChoice) => void
+ onRetryMetadata: () => void
+ /** `?file=` from the URL. */
+ requested: string | null
+ hrefFor: (_file: string) => string
+ onSelect: (_file: string) => void
+ check: HashCheck
+}) {
+ const { root, onChooseFolder, 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
+ /** The metadata read failed, so which folder holds the contract is unknown. */
+ folderUnknown: boolean
+ onRetryMetadata: () => void
/** `?file=` from the URL. */
requested: string | null
hrefFor: (_file: string) => string
@@ -65,18 +156,18 @@ export default function SourcePane(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
}
@@ -84,8 +175,22 @@ export default function SourcePane(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(() => {
@@ -101,11 +206,15 @@ export default function SourcePane(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: '' }
@@ -185,10 +294,51 @@ export default function SourcePane(props: {
)
- if (ready && paths.length === 0)
+ // With the folder unknown, an empty listing only means the contract wasn't
+ // found there, not that the snapshot has no source.
+ if (ready && paths.length === 0 && !openLink && props.folderUnknown)
+ return (
+
+
+ {linkFallback && Couldn’t open {props.requested} from this snapshot. }
+ The contract’s source folder is unknown until its current metadata can be read.
+ {
+ props.onRetryMetadata()
+ setFilesAttempt((n) => n + 1)
+ retryLink()
+ }}
+ >
+ Try again
+
+
+
+ )
+
+ 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)) && (
+ {
+ setFilesAttempt((n) => n + 1)
+ retryLink()
+ }}
+ >
+ Try again
+
+ )}
+
)
@@ -255,6 +405,14 @@ export default function SourcePane(props: {
)}
+ {partial && (
+
+ Some folders couldn’t be read.
+ setFilesAttempt((n) => n + 1)}>
+ Try again
+
+
+ )}
{ready ? `Rust and TOML files: ${paths.length}` : 'Reading snapshot…'}
@@ -267,6 +425,7 @@ export default function SourcePane(props: {
choose(e.target.value)} isDisabled={!ready} fontFamily="mono" fontSize="13px" rounded="md" borderColor="ruleStrong" bg="surface">
{!ready && {active ?? 'Reading snapshot…'} }
+ {unlistedLink && active && {active} }
{groups.map((g) =>
g.dir === '' ? (
g.files.map((p) => (
@@ -300,11 +459,23 @@ export default function SourcePane(props: {
{STRIPE[props.check.status]}
- {missing && (
-
- {props.requested} isn’t in this snapshot; showing {active}.
+ {unlistedLink && (
+
+ Opened from the link; {requested} isn’t among the files listed from {rootPath === '/' ? 'the snapshot root' : `${rootPath}/`}.
)}
+ {linkFallback && (
+
+
+ Couldn’t open {props.requested} from this snapshot; showing {active}.
+
+ {requested && (
+
+ Try again
+
+ )}
+
+ )}
{shown.status === 'ready' && active ? (
()
-/** 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..ec654ca
--- /dev/null
+++ b/hooks/useRecordedSource.ts
@@ -0,0 +1,50 @@
+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. The
+ * snapshot is read only once `enabled` (a tab that shows it is open), and a
+ * read that fails or times out is `unknown` with a retry.
+ */
+export function useRecordedSource(network: NetworkType, data: ContractData | null, enabled: boolean) {
+ 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)
+ // Once a tab has asked for it, keep the read going across tab switches.
+ const [wanted, setWanted] = useState(enabled)
+ useEffect(() => {
+ if (enabled) setWanted(true)
+ }, [enabled])
+
+ useEffect(() => {
+ if (!cid || recorded || !wanted) return
+ let active = true
+ setState({ key, source: { status: 'loading' } })
+ readSnapshotCheckout(network, cid)
+ .then((checkout): RecordedSource => {
+ if (!checkout) return { status: 'none', reason: 'no_checkout' }
+ const github = githubFromGitCheckout(checkout.head, checkout.config)
+ return github ? { status: 'known', github, origin: 'snapshot' } : { status: 'none', reason: 'unidentified' }
+ })
+ .catch((): RecordedSource => ({ status: 'unknown' }))
+ .then((source) => active && setState({ key, source }))
+ return () => {
+ active = false
+ }
+ }, [network, cid, key, recorded, wanted, 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/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",
diff --git a/pages/contract/[slug].tsx b/pages/contract/[slug].tsx
index 734b877..dc5bc4c 100644
--- a/pages/contract/[slug].tsx
+++ b/pages/contract/[slug].tsx
@@ -6,16 +6,17 @@ 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, FolderChoice, liveSource, OpenedWith, openedWithFor } 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'
import { Badge, Box, Button, Container, Flex, Heading, HStack, Icon, Link, VisuallyHidden } from '@chakra-ui/react'
import NextLink from 'next/link'
@@ -29,6 +30,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 +52,8 @@ 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)
+ // The recorded source is read only for the tabs that show it.
+ const recorded = useRecordedSource(network, data, tab !== 'source')
const { check, retry: retryHashCheck } = useCodeHashCheck(network, accountId, data?.code_hash)
const headingRef = useRef(null)
@@ -63,23 +67,28 @@ 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 is never presented
+ // as the recorded source: its folder opens the tree only under its own label.
+ const live = useMemo(() => {
+ const load = metadata.load
+ const snapshot = load.status === 'ready' ? load.metadata.buildInfo?.sourceCodeSnapshot : null
+ return liveSource(load, githubFromSnapshot(snapshot))
+ }, [metadata.load])
+ // State about one record view is keyed by it, so a network switch for the
+ // same account (same workspace) starts fresh.
+ const view = `${network}:${accountId}`
+ const settled = router.isReady && netState === 'ready'
+ // The reader's choice between the current metadata's folder and the snapshot root, per view and snapshot.
+ const [folderChoice, setFolderChoice] = useState<{ key: string; choice: FolderChoice } | null>(null)
+ const choice: FolderChoice = data && folderChoice?.key === `${view}:${data.cid}` ? folderChoice.choice : 'metadata'
+ // Only the ?file= link this view was opened with may choose the tree's
+ // folder. Picking a file in the tree updates ?file= too, but never moves it.
+ const [storedOpenedWith, setOpenedWith] = useState(null)
+ const openedWith = openedWithFor(storedOpenedWith, view, requestedFile)
+ useEffect(() => {
+ if (settled && storedOpenedWith?.view !== view) setOpenedWith({ view, file: requestedFile })
+ }, [settled, storedOpenedWith, view, requestedFile])
+ const sourceRoot = chooseSourceRoot(live, settled ? openedWith.file : null, choice)
const linkNetwork = detectNetworkFromAddress(accountId) ? undefined : network
const hrefFor = (opts: { tab?: Tab; file?: string | null }) => {
@@ -198,12 +207,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.
+ setFolderChoice({ key: `${view}:${data.cid}`, choice: next })
+ setOpenedWith({ view, file: null })
+ replaceQuery({ file: null })
+ }}
+ onRetryMetadata={metadata.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..92c04de
--- /dev/null
+++ b/tests/evidence.test.cjs
@@ -0,0 +1,195 @@
+const assert = require('node:assert/strict')
+const { test } = require('node:test')
+const { metadataLoadFromValue } = require('../utils/contractMetadata.ts')
+const { chooseSourceRoot, folderUnknown, isSnapshotFilePath, linkedDir, liveRelation, liveSource, openedWithFor, 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)
+})
+
+const CLONE_CONFIG = [
+ '[core]',
+ '\trepositoryformatversion = 0',
+ '\tfilemode = true',
+ '\tbare = false',
+ '\tlogallrefupdates = true',
+ '[remote "origin"]',
+ '\turl = https://github.com/near/intents',
+ '\tfetch = +refs/heads/*:refs/remotes/origin/*',
+ '[branch "main"]',
+ '\tremote = origin',
+ '\tmerge = refs/heads/main',
+ '',
+].join('\n')
+
+test('the git checkout stored in a snapshot names its repository and commit', () => {
+ assert.deepEqual(githubFromGitCheckout(`${SHA}\n`, CLONE_CONFIG), verified)
+ for (const url of ['https://github.com/near/intents.git', 'https://github.com/near/intents/', 'git@github.com:near/intents.git', 'ssh://git@github.com/near/intents.git'])
+ assert.deepEqual(githubFromGitCheckout(SHA, CLONE_CONFIG.replace('https://github.com/near/intents', url)), verified, url)
+})
+
+test('a git checkout that is ambiguous or not a plain GitHub clone names nothing', () => {
+ const variants = {
+ 'branch HEAD': ['ref: refs/heads/main\n', CLONE_CONFIG],
+ 'uppercase HEAD': [`${SHA.toUpperCase()}\n`, CLONE_CONFIG],
+ 'HEAD with extra lines': [`${SHA}\n${LATER}\n`, CLONE_CONFIG],
+ 'no origin': [SHA, CLONE_CONFIG.replace('[remote "origin"]', '[remote "fork"]')],
+ 'origin and Origin': [SHA, `${CLONE_CONFIG}[remote "Origin"]\n\turl = https://github.com/someone/intents\n`],
+ 'two origin sections': [SHA, `${CLONE_CONFIG}[remote "origin"]\n\turl = https://github.com/someone/intents\n`],
+ 'two origin urls': [SHA, CLONE_CONFIG.replace('\tfetch =', '\turl = https://github.com/someone/intents\n\tfetch =')],
+ 'old [remote.origin] syntax': [SHA, CLONE_CONFIG.replace('[remote "origin"]', '[remote.origin]')],
+ 'url rewrite': [SHA, `${CLONE_CONFIG}[url "https://github.com/someone/"]\n\tinsteadOf = https://github.com/near/\n`],
+ include: [SHA, `[include]\n\tpath = other\n${CLONE_CONFIG}`],
+ 'quoted url': [SHA, CLONE_CONFIG.replace('url = https://github.com/near/intents', 'url = "https://github.com/near/intents"')],
+ 'url with comment': [SHA, CLONE_CONFIG.replace('near/intents', 'near/intents ; fork')],
+ 'web path': [SHA, CLONE_CONFIG.replace('near/intents', 'near/intents/tree/main')],
+ 'extra path segment': [SHA, CLONE_CONFIG.replace('near/intents', 'near/intents/extra')],
+ credentials: [SHA, CLONE_CONFIG.replace('https://github.com', 'https://user@github.com')],
+ query: [SHA, CLONE_CONFIG.replace('near/intents', `near/intents?rev=${LATER}`)],
+ 'other host': [SHA, CLONE_CONFIG.replace('github.com', 'gitlab.com')],
+ 'key before any section': [SHA, `url = https://github.com/near/intents\n${CLONE_CONFIG}`],
+ }
+ for (const [name, [head, config]] of Object.entries(variants)) assert.equal(githubFromGitCheckout(head, config), null, name)
+})
+
+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('the folder from the current metadata is always labelled, never the verified crate', () => {
+ // Same repository and commit as the record, two crates in that tree: the path still only comes from current metadata.
+ for (const dir of ['contracts/ft', 'contracts/nft']) {
+ const current = live({ source_code_snapshot: `git+https://github.com/near/intents?rev=${SHA}`, contract_path: dir })
+ assert.equal(liveRelation(known(verified), current), 'same')
+ assert.deepEqual(chooseSourceRoot(current, null, 'metadata'), { rootPath: dir, basis: 'current_metadata', hint: { status: 'offered', dir } })
+ }
+ // A later commit is treated the same way: labelled, with the snapshot root one click away.
+ assert.deepEqual(chooseSourceRoot(deployedLater, null, 'metadata'), { rootPath: 'contracts/defuse', basis: 'current_metadata', hint: { status: 'offered', dir: 'contracts/defuse' } })
+ assert.deepEqual(chooseSourceRoot(deployedLater, null, 'root'), { rootPath: '/', basis: 'snapshot_root', hint: { status: 'offered', dir: 'contracts/defuse' } })
+ // The choice never depends on the recorded source, so its read can't hold up the tree.
+ assert.equal(chooseSourceRoot.length, 3)
+})
+
+test('a ?file= link opens its own folder, without waiting for the metadata', () => {
+ const link = 'contracts/ft/src/lib.rs'
+ for (const current of [{ status: 'loading' }, { status: 'unknown' }, { status: 'absent' }])
+ assert.equal(chooseSourceRoot(current, link, 'metadata').rootPath, 'contracts/ft', current.status)
+ assert.deepEqual(chooseSourceRoot({ status: 'unknown' }, link, 'metadata'), { rootPath: 'contracts/ft', basis: 'link', hint: { status: 'unknown' } })
+ // Inside the current metadata's folder, that folder opens (labelled); elsewhere, the link's own folder.
+ assert.equal(chooseSourceRoot(deployedLater, 'contracts/defuse/src/a/b.rs', 'metadata').basis, 'current_metadata')
+ assert.deepEqual(chooseSourceRoot(deployedLater, link, 'metadata'), { rootPath: 'contracts/ft', basis: 'link', hint: { status: 'offered', dir: 'contracts/defuse' } })
+ // The reader chose the snapshot root: a file listed there keeps it.
+ assert.equal(chooseSourceRoot(deployedLater, 'contracts/Cargo.toml', 'root').rootPath, '/')
+ assert.equal(chooseSourceRoot(deployedLater, 'Cargo.toml', 'metadata').rootPath, '/')
+ // Without a link, the tree waits for the metadata.
+ assert.deepEqual(chooseSourceRoot({ status: 'loading' }, null, 'metadata'), { rootPath: null, basis: 'pending', hint: { status: 'none' } })
+ // A path that could leave the snapshot is ignored.
+ assert.equal(chooseSourceRoot({ status: 'absent' }, '../x/src/lib.rs', 'metadata').rootPath, '/')
+})
+
+test('a file the current folder lists never moves the tree', () => {
+ // No metadata: the root lists contracts/example.rs, so picking it (or reloading with it) keeps the root.
+ for (const file of ['Cargo.toml', 'contracts/example.rs'])
+ assert.deepEqual(chooseSourceRoot({ status: 'absent' }, file, 'metadata'), { rootPath: '/', basis: 'snapshot_root', hint: { status: 'none' } }, file)
+ // In the metadata folder, its files and one folder below stay there.
+ for (const file of ['contracts/defuse/Cargo.toml', 'contracts/defuse/tests/flow.rs', 'contracts/defuse/src/lib.rs'])
+ assert.equal(chooseSourceRoot(deployedLater, file, 'metadata').rootPath, 'contracts/defuse', file)
+ // After choosing the snapshot root, files listed there keep it.
+ assert.equal(chooseSourceRoot(deployedLater, 'contracts/Cargo.toml', 'root').rootPath, '/')
+ // Only a link the default folder doesn't list moves it.
+ assert.equal(chooseSourceRoot({ status: 'absent' }, 'contracts/ft/src/lib.rs', 'metadata').rootPath, 'contracts/ft')
+})
+
+test('the opened-with link belongs to one network and account; a network switch starts fresh', () => {
+ const link = 'contracts/ft/src/lib.rs'
+ const opened = openedWithFor(null, 'mainnet:9873182a', link)
+ assert.deepEqual(opened, { view: 'mainnet:9873182a', file: link })
+ // Picking another file in the same view keeps the link the view was opened with.
+ assert.equal(openedWithFor(opened, 'mainnet:9873182a', 'Cargo.toml'), opened)
+ // "Check Testnet" for the same account: the Mainnet link no longer applies.
+ assert.deepEqual(openedWithFor(opened, 'testnet:9873182a', null), { view: 'testnet:9873182a', file: null })
+ const tree = (o) => chooseSourceRoot({ status: 'absent' }, o.file, 'metadata').rootPath
+ assert.equal(tree(opened), 'contracts/ft')
+ assert.equal(tree(openedWithFor(opened, 'testnet:9873182a', null)), '/')
+ // Back to Mainnet with the link in the address opens it again.
+ assert.deepEqual(openedWithFor({ view: 'testnet:9873182a', file: null }, 'mainnet:9873182a', link), opened)
+})
+
+test('an empty listing while the folder is unknown is not a statement about the snapshot', () => {
+ assert.equal(folderUnknown(chooseSourceRoot({ status: 'unknown' }, null, 'metadata')), true)
+ assert.equal(folderUnknown(chooseSourceRoot({ status: 'unknown' }, 'contracts/ft/src/lib.rs', 'metadata')), true)
+ assert.equal(folderUnknown(chooseSourceRoot({ status: 'absent' }, null, 'metadata')), false)
+ assert.equal(folderUnknown(chooseSourceRoot(deployedLater, null, 'root')), false)
+})
+
+test('linked files map to their crate folder; unsafe paths are not snapshot paths', () => {
+ for (const [file, dir] of [
+ ['src/lib.rs', ''],
+ ['Cargo.toml', ''],
+ ['contracts/ft/src/lib.rs', 'contracts/ft'],
+ ['contracts/ft/src/a/src/b.rs', 'contracts/ft'],
+ ['contracts/ft/Cargo.toml', 'contracts/ft'],
+ ['a/b/c.rs', 'a/b'],
+ ])
+ assert.equal(linkedDir(file), dir, file)
+ for (const path of ['src/lib.rs', 'a/b.toml']) assert.equal(isSnapshotFilePath(path), true, path)
+ for (const path of ['', '/src/lib.rs', 'a//b.rs', '../a.rs', 'a/./b.rs', 'a\\b.rs', 'a/\nb.rs']) assert.equal(isSnapshotFilePath(path), false, JSON.stringify(path))
+})
+
+test('a failed metadata read leaves the folder unknown, with no claim about the snapshot', () => {
+ assert.deepEqual(chooseSourceRoot(liveSource({ status: 'unknown' }, null), null, 'metadata'), { rootPath: '/', basis: 'snapshot_root', hint: { status: 'unknown' } })
+})
+
+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 })
+ const atRoot = live({ source_code_snapshot: `git+https://github.com/near/intents?rev=${SHA}` })
+ for (const current of [unusable, atRoot, { status: 'absent' }])
+ assert.deepEqual(chooseSourceRoot(current, null, 'metadata'), { rootPath: '/', basis: 'snapshot_root', hint: { status: 'none' } })
+})
diff --git a/tests/metadata.test.cjs b/tests/metadata.test.cjs
new file mode 100644
index 0000000..84b6039
--- /dev/null
+++ b/tests/metadata.test.cjs
@@ -0,0 +1,195 @@
+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],
+ // A lone surrogate can't be put into a URL; a surrogate pair is ordinary text.
+ ['contracts/\ud800', null],
+ ['\udc00contracts', null],
+ ['contracts/\ud800x', null],
+ ['contracts/\ud83d\ude00', 'contracts/\ud83d\ude00'],
+ ])
+ assert.equal(contractDir(path), dir, JSON.stringify(path))
+
+ for (const path of ['../outside', JSON.parse('"contracts/\\ud800"')]) {
+ const metadata = parseSourceMetadata({ build_info: { contract_path: path } })
+ assert.equal(metadata.buildInfo.contractPath, path)
+ 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' })
+
+ 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' })
+ 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/tests/sourceFiles.test.cjs b/tests/sourceFiles.test.cjs
new file mode 100644
index 0000000..a4e4290
--- /dev/null
+++ b/tests/sourceFiles.test.cjs
@@ -0,0 +1,152 @@
+const assert = require('node:assert/strict')
+const { before, test } = require('node:test')
+
+const SHA = 'a2dd140892b68140bf7e70814604d3ba074d656c'
+const CONFIG = '[remote "origin"]\n\turl = https://github.com/near/intents\n'
+const dir = (Name) => ({ Name, Hash: 'h', Size: 0, Type: 1 })
+const file = (Name) => ({ Name, Hash: 'h', Size: 1, Type: 2 })
+
+// sourceFiles.ts imports axios as ESM, so mock that same instance.
+let axios, sf
+before(async () => {
+ axios = (await import('axios')).default
+ sf = require('../utils/sourceFiles.ts')
+})
+
+/** Mocks the proxy: `replies` maps "structure:" / "file:" to a reply (or a function returning one). */
+function proxy(t, replies) {
+ const calls = []
+ t.mock.method(axios, 'get', async (url, config) => {
+ assert.equal(url, '/api/proxy-ipfs')
+ const { endpoint, path } = config.params
+ const key = `${endpoint}:${path}`
+ calls.push(key)
+ const reply = typeof replies[key] === 'function' ? await replies[key]() : replies[key]
+ if (reply === undefined) throw new Error(`unexpected ${key}`)
+ if (reply instanceof Error) throw reply
+ return { data: reply }
+ })
+ return calls
+}
+
+test('a confirmed empty listing means no checkout, and that answer is kept', async (t) => {
+ const calls = proxy(t, { 'structure:/': { cid: 'cid-empty', structure: [] } })
+ assert.equal(await sf.readSnapshotCheckout('mainnet', 'cid-empty'), null)
+ assert.equal(await sf.readSnapshotCheckout('mainnet', 'cid-empty'), null)
+ assert.deepEqual(calls, ['structure:/'])
+})
+
+test('a malformed listing is unreadable, not an empty folder, and is asked again', async (t) => {
+ let reply = { status: 'temporarily unavailable' }
+ const calls = proxy(t, {
+ 'structure:/': () => reply,
+ 'file:.git/HEAD': `${SHA}\n`,
+ 'file:.git/config': CONFIG,
+ })
+ for (const malformed of [{ status: 'temporarily unavailable' }, { structure: 'none' }, { structure: ['.git'] }, { structure: [{ Hash: 'h' }] }, null, 'text']) {
+ reply = malformed
+ await assert.rejects(sf.readSnapshotCheckout('mainnet', 'cid-malformed'), /Unreadable folder listing/, JSON.stringify(malformed))
+ }
+ reply = { structure: [dir('.git'), file('Cargo.toml')] }
+ assert.deepEqual(await sf.readSnapshotCheckout('mainnet', 'cid-malformed'), { head: `${SHA}\n`, config: CONFIG })
+ assert.equal(calls.filter((c) => c === 'structure:/').length, 7)
+})
+
+test('a checkout file that is not text is unreadable and not kept', async (t) => {
+ let head = { status: 'temporarily unavailable' }
+ proxy(t, { 'structure:/': { structure: [dir('.git')] }, 'file:.git/HEAD': () => head, 'file:.git/config': CONFIG })
+ await assert.rejects(sf.readSnapshotCheckout('mainnet', 'cid-object'), /Unreadable \.git\/HEAD/)
+ head = `${SHA}\n`
+ assert.deepEqual(await sf.readSnapshotCheckout('mainnet', 'cid-object'), { head, config: CONFIG })
+})
+
+test('a checkout read that never answers times out instead of waiting', async (t) => {
+ proxy(t, { 'structure:/': { structure: [dir('.git')] }, 'file:.git/HEAD': () => new Promise(() => {}), 'file:.git/config': CONFIG })
+ const started = Date.now()
+ await assert.rejects(sf.readSnapshotCheckout('mainnet', 'cid-slow', 50), /Timed out after 50 ms/)
+ assert.ok(Date.now() - started < 2000)
+ assert.equal(sf.CHECKOUT_TIMEOUT_MS, 10000)
+})
+
+test('a root listing that never answered is not reused when the checkout read is retried', async (t) => {
+ let stall = true
+ const calls = proxy(t, {
+ 'structure:/': () => (stall ? new Promise(() => {}) : { structure: [dir('.git')] }),
+ 'file:.git/HEAD': `${SHA}\n`,
+ 'file:.git/config': CONFIG,
+ })
+ await assert.rejects(sf.readSnapshotCheckout('mainnet', 'cid-stalled-root', 50), /Timed out after 50 ms/)
+ stall = false
+ assert.deepEqual(await sf.readSnapshotCheckout('mainnet', 'cid-stalled-root', 50), { head: `${SHA}\n`, config: CONFIG })
+ assert.equal(calls.filter((c) => c === 'structure:/').length, 2)
+})
+
+test('a root listing that did answer is kept when only a .git file timed out', async (t) => {
+ let stall = true
+ const calls = proxy(t, {
+ 'structure:/': { structure: [dir('.git')] },
+ 'file:.git/HEAD': () => (stall ? new Promise(() => {}) : `${SHA}\n`),
+ 'file:.git/config': CONFIG,
+ })
+ await assert.rejects(sf.readSnapshotCheckout('mainnet', 'cid-stalled-head', 50), /Timed out/)
+ stall = false
+ assert.equal((await sf.readSnapshotCheckout('mainnet', 'cid-stalled-head', 50)).head, `${SHA}\n`)
+ assert.equal(calls.filter((c) => c === 'structure:/').length, 1)
+})
+
+test('a listing with any malformed entry is unreadable, never a cached absence', async (t) => {
+ let entries
+ proxy(t, { 'structure:/': () => ({ structure: entries }), 'file:.git/HEAD': `${SHA}\n`, 'file:.git/config': CONFIG })
+ for (const bad of [
+ [{ Name: '.git', Hash: 'unused' }],
+ [{ Name: '.git', Hash: 'h', Type: '1' }],
+ [{ Name: '.git', Hash: 'h', Type: 9 }],
+ [{ Name: '.git', Hash: 'h', Type: 1.5 }],
+ [{ Name: 7, Type: 1 }],
+ [{ Name: '\ud800', Type: 2 }],
+ [file('Cargo.toml'), { name: '.git' }],
+ [{ name: '.git', type: 'dir', path: 5 }],
+ [{ Hash: 'h', Type: 1 }],
+ ]) {
+ entries = bad
+ await assert.rejects(sf.readSnapshotCheckout('mainnet', 'cid-bad-entry'), /Unreadable folder listing/, JSON.stringify(bad))
+ }
+ // Well-formed entries of other types, or with names that can't be shown, are skipped.
+ entries = [{ Name: 'link', Hash: 'h', Size: 0, Type: 4 }, { Name: '..', Hash: 'h', Size: 0, Type: 1 }, file('Cargo.toml')]
+ assert.equal(await sf.readSnapshotCheckout('mainnet', 'cid-bad-entry'), null)
+})
+
+test('githubEntryPath is gone', () => {
+ assert.equal(sf.githubEntryPath, undefined)
+})
+
+test('the root listing is shared, and .git itself is never listed', async (t) => {
+ const calls = proxy(t, {
+ 'structure:/': { structure: [dir('.git'), dir('src'), dir('.github'), file('Cargo.toml')] },
+ 'structure:src': { structure: [file('lib.rs'), file('notes.md')] },
+ 'structure:.github': { structure: [] },
+ 'file:.git/HEAD': `${SHA}\n`,
+ 'file:.git/config': CONFIG,
+ })
+ const [checkout, listing] = await Promise.all([sf.readSnapshotCheckout('testnet', 'cid-shared'), sf.listSourcePaths('testnet', 'cid-shared', '/')])
+ assert.equal(checkout.head, `${SHA}\n`)
+ assert.deepEqual(listing, { paths: ['Cargo.toml', 'src/lib.rs'], partial: false })
+ assert.deepEqual(calls.filter((c) => c.startsWith('structure:')).sort(), ['structure:.github', 'structure:/', 'structure:src'])
+ assert.ok(!calls.some((c) => c.startsWith('structure:.git') && c !== 'structure:.github'))
+})
+
+test('a sub-folder that cannot be read makes the listing partial, and a partial listing is not kept', async (t) => {
+ let src = new Error('503')
+ proxy(t, { 'structure:contracts/ft': { structure: [file('Cargo.toml'), dir('src')] }, 'structure:contracts/ft/src': () => src })
+ assert.deepEqual(await sf.listSourcePaths('mainnet', 'cid-partial', 'contracts/ft'), { paths: ['contracts/ft/Cargo.toml'], partial: true })
+ assert.equal(sf.cachedSourcePaths('mainnet', 'cid-partial', 'contracts/ft'), undefined)
+ src = { structure: [file('lib.rs')] }
+ const full = { paths: ['contracts/ft/Cargo.toml', 'contracts/ft/src/lib.rs'], partial: false }
+ assert.deepEqual(await sf.listSourcePaths('mainnet', 'cid-partial', 'contracts/ft'), full)
+ assert.deepEqual(sf.cachedSourcePaths('mainnet', 'cid-partial', 'contracts/ft'), full.paths)
+})
+
+test('an unreadable root listing fails the whole listing', async (t) => {
+ proxy(t, { 'structure:/': { status: 'temporarily unavailable' } })
+ await assert.rejects(sf.listSourcePaths('mainnet', 'cid-root-bad', '/'), /Unreadable folder listing/)
+})
diff --git a/utils/contractMetadata.ts b/utils/contractMetadata.ts
new file mode 100644
index 0000000..74bb249
--- /dev/null
+++ b/utils/contractMetadata.ts
@@ -0,0 +1,167 @@
+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 lone UTF-16 surrogate isn't text: it can't be put into a URL (encodeURIComponent throws).
+const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/
+
+/**
+ * A relative folder of plain path segments ('' for the root). Leading "./",
+ * leading and trailing slashes are tolerated; "..", "." segments, backslashes,
+ * control characters and lone surrogates 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) || LONE_SURROGATE.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..0f95bbb
--- /dev/null
+++ b/utils/evidence.ts
@@ -0,0 +1,152 @@
+import type { GithubDto } from '@/Interfaces/github/github.dto'
+import type { MetadataLoad } from '@/utils/contractMetadata'
+
+/*
+ * Which source a verification record refers to, and how the contract's
+ * current NEP-330 metadata may be used next to it.
+ *
+ * The registry records the IPFS snapshot (cid), the code hash and the block;
+ * it records neither a repository nor the crate that was built. The metadata
+ * read now describes whatever is deployed today, which can be a later build.
+ * So the recorded repository and commit come only from the record or from the
+ * git checkout inside its snapshot, and anything taken from the current
+ * metadata (its commit, its contract path) is shown labelled as such. Even
+ * when it names the recorded commit, its contract path is not the verified
+ * crate: one commit can hold several crates.
+ */
+
+/** 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' }
+ /**
+ * Not recorded: the snapshot has no git checkout (`no_checkout`), or its
+ * checkout doesn't name exactly one GitHub repository and commit (`unidentified`).
+ */
+ | { status: 'none'; reason: 'no_checkout' | 'unidentified' }
+ /** The snapshot couldn't be read (or didn't answer in time), 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; nothing ties it to the verified crate. */
+ | { status: 'offered'; dir: string }
+ /** The metadata read failed, so whether it names a folder is unknown. */
+ | { status: 'unknown' }
+
+/** The reader's choice for the current metadata's folder: follow it (default) or show the snapshot root. */
+export type FolderChoice = 'metadata' | 'root'
+
+export interface SourceRoot {
+ /** Snapshot folder to list ('/' = snapshot root); null while it can't be decided yet. */
+ rootPath: string | null
+ /**
+ * current_metadata: the folder named in the contract's current metadata (always labelled)
+ * link: the folder of the file a `?file=` link names
+ * snapshot_root: the root of the snapshot
+ */
+ basis: 'pending' | 'current_metadata' | 'link' | 'snapshot_root'
+ hint: FolderHint
+}
+
+/** A file path inside the snapshot: plain segments, no "." or "..", no backslashes or control characters. */
+export const isSnapshotFilePath = (path: string) =>
+ // eslint-disable-next-line no-control-regex
+ !/[\\\u0000-\u001f\u007f]/.test(path) && path.split('/').every((s) => s !== '' && s !== '.' && s !== '..')
+
+/** The crate folder a linked file sits in: the part before its first `src/`, else its folder ('' = root). */
+export function linkedDir(file: string): string {
+ const crate = /^(?:(.*?)\/)?src\//.exec(file)
+ if (crate) return crate[1] ?? ''
+ return file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : ''
+}
+
+/** Whether listing `dir` (its files and one folder below) shows `file`. */
+const covers = (dir: string, file: string) => {
+ const rest = dir === '' ? file : file.startsWith(`${dir}/`) ? file.slice(dir.length + 1) : null
+ return rest !== null && rest.split('/').length <= 2
+}
+
+/**
+ * Picks the snapshot folder the source tree opens at.
+ *
+ * The default is the reader's choice: the current metadata's folder (labelled
+ * as such) or the snapshot root. `link` is the `?file=` the workspace was
+ * opened with, and only a link may move the tree, and only when the default
+ * folder's listing wouldn't show it: then it opens the metadata folder, if the
+ * file is inside it, or else the file's own folder. So a file picked in the
+ * tree, which is listed by definition, never moves it, even after a reload.
+ *
+ * It depends only on the current metadata, the link and the reader's choice,
+ * never on the recorded-source read, so that read can't hold up browsing. A
+ * link opens at once, without waiting for the metadata.
+ */
+export function chooseSourceRoot(live: LiveSource, requested: string | null, choice: FolderChoice): SourceRoot {
+ const link = requested && isSnapshotFilePath(requested) ? requested : null
+ const hint: FolderHint =
+ live.status === 'unknown'
+ ? { status: 'unknown' }
+ : live.status === 'ready' && live.contractDir
+ ? { status: 'offered', dir: live.contractDir }
+ : { status: 'none' }
+ const metaDir = hint.status === 'offered' ? hint.dir : null
+ const at = (dir: string, basis: SourceRoot['basis']): SourceRoot =>
+ dir ? { rootPath: dir, basis, hint } : { rootPath: '/', basis: 'snapshot_root', hint }
+ const preferred = choice === 'root' || metaDir === null ? '' : metaDir
+ const atPreferred = () => at(preferred, preferred === metaDir ? 'current_metadata' : 'snapshot_root')
+
+ if (live.status === 'loading') return link ? at(linkedDir(link), 'link') : { rootPath: null, basis: 'pending', hint }
+ if (!link || covers(preferred, link)) return atPreferred()
+ if (metaDir !== null && choice !== 'root' && link.startsWith(`${metaDir}/`)) return at(metaDir, 'current_metadata')
+ return at(linkedDir(link), 'link')
+}
+
+/** The folder is unknown (the metadata read failed), so an empty listing says nothing about the snapshot. */
+export const folderUnknown = (root: SourceRoot) => root.hint.status === 'unknown'
+
+/**
+ * The `?file=` link a workspace was opened with. It belongs to one record
+ * view (network + account): the same view keeps it while the reader picks
+ * files, and another view (a network switch for the same account) starts
+ * fresh from the address it opened with.
+ */
+export interface OpenedWith {
+ view: string
+ file: string | null
+}
+
+export const openedWithFor = (stored: OpenedWith | null, view: string, current: string | null): OpenedWith =>
+ stored && stored.view === view ? stored : { view, file: current }
diff --git a/utils/extractGithub.ts b/utils/extractGithub.ts
index 631b285..b371dab 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,87 @@ 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
+ }
+}
+
+/**
+ * Owner and repository of a GitHub clone URL that names exactly a
+ * repository: https://github.com/o/r, git@github.com:o/r or
+ * ssh://git@github.com/o/r, each with an optional ".git". Anything else
+ * (credentials, ports, queries, web paths such as /o/r/tree/main) is null.
+ */
+function githubRepoFromRemote(url: string): { owner: string; repo: string } | null {
+ const m =
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(url) ??
+ /^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/.exec(url) ??
+ /^ssh:\/\/git@github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(url)
+ return m && OWNER.test(m[1]) && REPO.test(m[2]) ? { owner: m[1], repo: m[2] } : null
+}
+
+/**
+ * The repository and commit of a git checkout, from its `.git/HEAD` and
+ * `.git/config`, as written by `git clone` followed by `git checkout `:
+ * a detached HEAD and one `[remote "origin"]` with one plain `url`.
+ * Anything that would make the answer depend on interpretation is null:
+ * another HEAD form, no origin or several, a remote that differs from
+ * "origin" only in case, a second url, quoted or escaped values, url
+ * rewrites (`[url ...]`), includes, or the old `[remote.origin]` syntax.
+ */
+function githubFromGitCheckout(head: string, config: string): GithubDto | null {
+ if (!/^[0-9a-f]{40}\n?$/.test(head)) return null
+ const sha = head.trim()
+ let section: string | null = null
+ let originSections = 0
+ const urls: string[] = []
+ for (const raw of config.split(/\r?\n/)) {
+ const line = raw.trim()
+ if (line === '' || line.startsWith('#') || line.startsWith(';')) continue
+ if (line.startsWith('[')) {
+ const sub = /^\[([A-Za-z0-9.-]+) "([^"\\]*)"\]$/.exec(line)
+ const plain = /^\[([A-Za-z0-9-]+)\]$/.exec(line)
+ if (!sub && !plain) return null
+ const name = (sub ?? plain)![1].toLowerCase()
+ if (name === 'include' || name === 'includeif' || name === 'url' || name.startsWith('remote.')) return null
+ if (sub && name === 'remote' && sub[2] !== 'origin' && sub[2].toLowerCase() === 'origin') return null
+ section = sub && name === 'remote' && sub[2] === 'origin' ? 'origin' : 'other'
+ if (section === 'origin') originSections++
+ continue
+ }
+ if (section === null) return null
+ if (section !== 'origin') continue
+ const kv = /^([A-Za-z][A-Za-z0-9-]*)\s*=\s*(.*)$/.exec(line)
+ if (!kv) return null
+ if (kv[1].toLowerCase() !== 'url') continue
+ if (/["\\;#]/.test(kv[2])) return null
+ urls.push(kv[2].trim())
+ }
+ if (originSections !== 1 || urls.length !== 1) return null
+ const repo = githubRepoFromRemote(urls[0])
+ return repo ? { ...repo, sha } : null
+}
+
+export { extractGitHubDetails, githubFromGitCheckout, githubFromSnapshot, isGithubDto }
diff --git a/utils/near/view.ts b/utils/near/view.ts
index 935e7ac..788d92c 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
}
@@ -37,16 +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 ?? '')
+ 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)))
+ // 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)
- if (cause === 'CONTRACT_EXECUTION_ERROR' || /wasm execution failed|Function call returned an error/i.test(detail))
- return failure('execution_error', detail)
+ const execution = LEGACY_EXECUTION.exec(detail)
+ if (execution) return executionFailure(execution[1], detail)
return failure('unavailable', detail || 'RPC request failed')
}
diff --git a/utils/sourceFiles.ts b/utils/sourceFiles.ts
index bf9518a..1d40152 100644
--- a/utils/sourceFiles.ts
+++ b/utils/sourceFiles.ts
@@ -18,31 +18,44 @@ export interface SourceFile {
displayName?: string
}
-const asList = (data: any): any[] => {
- if (data?.structure)
- return Array.isArray(data.structure) ? data.structure : [data.structure]
+/**
+ * Entries of a folder listing: `{ structure: [...] }` from the SourceScan API,
+ * or a bare array. Any other reply is unreadable, never an empty folder.
+ */
+function listingEntries(data: unknown): unknown[] {
+ const structure = (data as { structure?: unknown } | null)?.structure
+ if (Array.isArray(structure)) return structure
if (Array.isArray(data)) return data
- return data && typeof data === 'object' ? [data] : []
+ throw new Error('Unreadable folder listing')
}
const joinPath = (dir: string, name: string) =>
[dir.replace(/^\/+|\/+$/g, ''), name].filter(Boolean).join('/')
// One path segment: no separators and no "." / ".." that could leave the snapshot.
-const safeName = (name: unknown): name is string =>
- typeof name === 'string' && name.length > 0 && name !== '.' && name !== '..' && !/[\\/]/.test(name)
+const safeName = (name: string) => name.length > 0 && name !== '.' && name !== '..' && !/[\\/]/.test(name)
+// A lone UTF-16 surrogate can't come from a real (UTF-8) listing and can't be put into a URL.
+const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/
+const unreadable = () => new Error('Unreadable folder listing')
/**
* The SourceScan API returns IPFS `ls` links ({ Name, Hash, Size, Type } with
- * Type 1 = directory, 2 = file). The older { name, path, type: 'file' | 'dir' }
- * shape is accepted too. Anything else is ignored.
+ * the UnixFS type 0-5: 1 = directory, 2 = file). The older
+ * { name, path, type: 'file' | 'dir' } shape is accepted too. Any entry that
+ * isn't one of these, in full, makes the reply unreadable: a folder that
+ * might hold `.git` is never reported as one that doesn't. Well-formed
+ * entries of other types (symlinks) or with unsafe names are skipped.
*/
function toEntry(item: any, dir: string): SourceFile | null {
- if (!item || typeof item !== 'object') return null
- if (safeName(item.Name) && (item.Type === 1 || item.Type === 2))
+ if (!item || typeof item !== 'object') throw unreadable()
+ if ('Name' in item) {
+ if (typeof item.Name !== 'string' || LONE_SURROGATE.test(item.Name) || !Number.isInteger(item.Type) || item.Type < 0 || item.Type > 5) throw unreadable()
+ if (!safeName(item.Name) || (item.Type !== 1 && item.Type !== 2)) return null
return { name: item.Name, path: joinPath(dir, item.Name), type: item.Type === 1 ? 'dir' : 'file' }
- if (safeName(item.name) && (item.type === 'file' || item.type === 'dir'))
- return { name: item.name, path: typeof item.path === 'string' ? item.path : joinPath(dir, item.name), type: item.type }
- return null
+ }
+ if (typeof item.name !== 'string' || LONE_SURROGATE.test(item.name) || (item.type !== 'file' && item.type !== 'dir')) throw unreadable()
+ if (item.path !== undefined && (typeof item.path !== 'string' || LONE_SURROGATE.test(item.path))) throw unreadable()
+ if (!safeName(item.name)) return null
+ return { name: item.name, path: item.path ?? joinPath(dir, item.name), type: item.type }
}
const isSource = (item: any): item is SourceFile =>
@@ -51,39 +64,73 @@ const isSource = (item: any): item is SourceFile =>
typeof item.path === 'string' &&
(item.name.endsWith('.rs') || item.name.endsWith('.toml'))
-async function structure(network: NetworkType, cid: string, path: string): Promise {
- const res = await axios.get('/api/proxy-ipfs', {
- params: { endpoint: 'structure', cid, path },
- headers: { 'X-Network': network },
- })
- const dir = relativePath(cid, path)
- return asList(res.data)
- .map((item) => toEntry(item, dir))
- .filter((entry): entry is SourceFile => entry !== null)
+const dirKey = (cid: string, path: string) => relativePath(cid, path).replace(/^\/+|\/+$/g, '')
+const listingKey = (network: NetworkType, cid: string, path: string) => `${network}:${cid}:${dirKey(cid, path)}`
+const listings = new Map>()
+const answered = new WeakSet>()
+
+/**
+ * One folder of the snapshot. Every caller shares one request per folder; a
+ * snapshot is content-addressed, so a listing that was read is kept, and a
+ * failed one is dropped so the next call asks again.
+ */
+function structure(network: NetworkType, cid: string, path: string): Promise {
+ const dir = dirKey(cid, path)
+ const key = listingKey(network, cid, path)
+ const hit = listings.get(key)
+ if (hit) return hit
+ const request = axios
+ .get('/api/proxy-ipfs', {
+ params: { endpoint: 'structure', cid, path: dir || '/' },
+ headers: { 'X-Network': network },
+ })
+ .then((res) => listingEntries(res.data).map((item) => toEntry(item, dir)).filter((entry): entry is SourceFile => entry !== null))
+ listings.set(key, request)
+ request.then(
+ () => answered.add(request),
+ () => {
+ answered.add(request)
+ if (listings.get(key) === request) listings.delete(key)
+ }
+ )
+ return request
+}
+
+/** Forgets a listing request that is still unanswered, so the next call sends a new one. */
+function expireUnanswered(network: NetworkType, cid: string, path: string) {
+ const key = listingKey(network, cid, path)
+ const pending = listings.get(key)
+ if (pending && !answered.has(pending)) listings.delete(key)
}
-/** Throws when the snapshot root cannot be read; unreadable sub-folders are skipped. */
+/**
+ * .rs/.toml files at `rootPath` and one folder below it (never inside `.git`).
+ * Throws when `rootPath` can't be read; `partial` is set when a sub-folder couldn't.
+ */
export async function listSourceFiles(
network: NetworkType,
cid: string,
rootPath: string
-): Promise {
+): Promise<{ files: SourceFile[]; partial: boolean }> {
const root = await structure(network, cid, rootPath)
+ let partial = false
const nested = await Promise.all(
root
- .filter((item) => item.type === 'dir')
+ .filter((item) => item.type === 'dir' && item.name !== '.git')
.map((dir) =>
structure(network, cid, dir.path)
.then((items) =>
items.filter(isSource).map((file) => ({ ...file, displayName: `${dir.name}/${file.name}` }))
)
- .catch(() => [] as SourceFile[])
+ .catch(() => {
+ partial = true
+ return [] as SourceFile[]
+ })
)
)
- return root.filter(isSource).concat(...nested)
+ return { files: root.filter(isSource).concat(...nested), partial }
}
-
export async function fetchSourceFile(
network: NetworkType,
cid: string,
@@ -105,32 +152,25 @@ export async function fetchSourceFile(
export const entryFile = (files: SourceFile[], lang?: string) =>
(lang === 'rust' && files.find((f) => f.name === 'lib.rs')) || files[0]
-/** GitHub path of the entry file, derived from NEP-330 contract_path (as before). */
-export function githubEntryPath(contractPath: string | undefined, lang?: string) {
- let path = (contractPath ?? '').toString()
- if (path.endsWith('/')) path = path.slice(0, -1)
- if (lang !== 'rust') return path
- if (path.endsWith('src')) return `${path}/lib.rs`
- if (path.includes('/src/')) return `${path.split('/src/')[0]}/src/lib.rs`
- return path ? `${path}/src/lib.rs` : 'src/lib.rs'
-}
-
/* ------------------------------------------------ workspace caches/helpers */
const listCache = new Map()
const contentCache = new Map()
-/** Snapshot-relative paths ("src/lib.rs"), cached per network + snapshot + root. */
+/**
+ * Snapshot-relative paths ("src/lib.rs") per network + snapshot + root. Only a
+ * complete listing is cached; a partial one is returned with `partial` set.
+ */
export async function listSourcePaths(network: NetworkType, cid: string, rootPath: string) {
const key = `${network}:${cid}:${rootPath}`
const hit = listCache.get(key)
- if (hit) return hit
- const files = await listSourceFiles(network, cid, rootPath)
+ if (hit) return { paths: hit, partial: false }
+ const { files, partial } = await listSourceFiles(network, cid, rootPath)
const paths = Array.from(new Set(files.map((f) => relativePath(cid, f.path).replace(/^\/+/, '')))).sort(
(a, b) => Number(a.includes('/')) - Number(b.includes('/')) || a.localeCompare(b)
)
- listCache.set(key, paths)
- return paths
+ if (!partial) listCache.set(key, paths)
+ return { paths, partial }
}
export const cachedSourcePaths = (network: NetworkType, cid: string, rootPath: string) =>
@@ -147,6 +187,56 @@ export async function fetchSource(network: NetworkType, cid: string, path: strin
return text
}
+const checkoutCache = new Map()
+
+/** A text file as the gateway returned it; any other reply is unreadable. */
+async function readSnapshotText(network: NetworkType, cid: string, path: string): Promise {
+ const res = await axios.get('/api/proxy-ipfs', {
+ params: { endpoint: 'file', cid, path },
+ headers: { 'X-Network': network },
+ })
+ if (typeof res.data !== 'string') throw new Error(`Unreadable ${path}`)
+ return res.data
+}
+
+function withTimeout(promise: Promise, ms: number): Promise {
+ let timer: ReturnType | undefined
+ const timeout = new Promise((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms)
+ })
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
+}
+
+export const CHECKOUT_TIMEOUT_MS = 10_000
+
+/**
+ * `.git/HEAD` and `.git/config` of the git checkout stored at the snapshot
+ * root, or null when the root listing has no `.git` folder (older SourceScan
+ * snapshots don't keep one). Throws when the snapshot can't be read or
+ * doesn't answer within `timeoutMs`. Only an answer that was read is kept.
+ */
+export async function readSnapshotCheckout(network: NetworkType, cid: string, timeoutMs = CHECKOUT_TIMEOUT_MS) {
+ const key = `${network}:${cid}`
+ const hit = checkoutCache.get(key)
+ if (hit !== undefined) return hit
+ const read = async () => {
+ const root = await structure(network, cid, '/')
+ if (!root.some((entry) => entry.type === 'dir' && entry.name === '.git')) return null
+ const [head, config] = await Promise.all([readSnapshotText(network, cid, '.git/HEAD'), readSnapshotText(network, cid, '.git/config')])
+ return { head, config }
+ }
+ let checkout: { head: string; config: string } | null
+ try {
+ checkout = await withTimeout(read(), timeoutMs)
+ } catch (error) {
+ // A root listing that never answered must not be reused by the retry.
+ expireUnanswered(network, cid, '/')
+ throw error
+ }
+ 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]