Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Members-only content in public repositories, Environments and the secret scan. P
- **A partial clone's lazy blob fetch reads only the packs that hold the blobs** it needs, instead of downloading the whole repository again for each checkout, `git log -p` or blame.
- **Issue and PR lists say when the repository's label definitions were not read completely**, instead of presenting the first page as all of them.
- **A removed member's sealed author events on their own issues and PRs follow the late-content rule**, so they can no longer keep writing readable values under an old key.
- **Trending loads in a fresh tab on testnet.** A new connection learns the network's protocol version before the first page query. Before, the SDK started at protocol 13 and refused Trending's time-range read with "requires protocol version 14+" until you clicked Try again.

## [0.1.0] - 2026-10-04

Expand Down
7 changes: 6 additions & 1 deletion forge-web/e2e/v2-explore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ test('x1. explore lists recent repos, trending, most starred and most forked, an
await expect(recent.locator('a[href*="/repo"]').first()).toBeVisible({ timeout: 60_000 })
// Trending and Most starred are proved ranked reads (C-1); no "needs an indexer" note.
await expect(page.getByTestId('trending-note')).toHaveCount(0)
await expect(page.getByTestId('explore-trending').getByRole('heading', { name: /Trending (this week|today)/ })).toBeVisible()
const trending = page.getByTestId('explore-trending')
await expect(trending.getByRole('heading', { name: /Trending (this week|today)/ })).toBeVisible()
// Its time-range read lands in a fresh tab, though it can be the page's first query: the SDK
// learns the protocol version (14 or more for `timeRange`) before the page queries.
await expect(trending.getByTestId('ranked-row').first().or(trending.getByText(/^No repo has \d+ new stars/))).toBeVisible({ timeout: 60_000 })
await expect(trending.getByText('That read did not land')).toHaveCount(0)
await expect(page.getByTestId('explore-most-starred').getByRole('heading', { name: 'Most starred' })).toBeVisible()
// Most forked (ranked repo.forkOf, fresh core): the repos that are not forks form the index's
// null group, which is never shown as a row.
Expand Down
84 changes: 80 additions & 4 deletions forge-web/lib/sdk/service-addresses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const recorded = vi.hoisted(() => ({
snapshots: vi.fn(async () => ({})),
emptyTestnet: false,
gate: vi.fn(),
version: 14,
latest: vi.fn(async (_q: { contractIds: string[] }) => new Map()),
}))
vi.mock('./budget', () => ({ installDapiFetchGate: recorded.gate, dapiBudget: { retryAfterMs: () => 0 } }))
vi.mock('./wasm-fetch', () => ({ compileWasm: () => Promise.resolve({}), onWasmProgress: () => () => undefined }))
Expand All @@ -30,28 +32,31 @@ vi.mock('../constants', async (importOriginal) => {
})
vi.mock('@dashevo/evo-sdk', () => ({
ensureInitialized: async () => undefined,
DataContract: { fromBase64: () => ({}) },
EvoSDK: class {
constructor(options: EvoSDKOptions) { recorded.options.push(options) }
connect = async () => undefined
contracts = { fetch: recorded.fetch, getLatestVersions: async () => new Map() }
contracts = { fetch: recorded.fetch, getLatestVersions: recorded.latest, addKnown: async () => true }
wasm = { free: recorded.free }
version = () => 14
version = () => recorded.version
},
}))

import testnetDeployment from '../../../forge-contracts/deployments/testnet.json'
import { NETWORKS, type Network } from '../constants'
import { EvoSdkService } from './service'
import { EvoSdkService, LEARN_VERSION_MS } from './service'

const services: EvoSdkService[] = []
beforeEach(() => {
vi.useFakeTimers()
recorded.options.length = 0
recorded.emptyTestnet = false
recorded.fetch.mockReset().mockResolvedValue({})
recorded.snapshots.mockClear()
recorded.snapshots.mockReset().mockResolvedValue({})
recorded.free.mockClear()
recorded.gate.mockClear()
recorded.version = 14
recorded.latest.mockReset().mockResolvedValue(new Map())
})
afterEach(() => {
services.splice(0).forEach((service) => service.cleanup())
Expand Down Expand Up @@ -112,3 +117,74 @@ describe('trusted SDK endpoint selection', () => {
expect(recorded.gate).toHaveBeenCalledWith(NETWORKS.devnet.dapiAddresses)
})
})

describe('the protocol version before the first query', () => {
const CORE = 'D2ZLdgghZTKGpES35a3KVDp5necSfZqqRHLSknjRPAV9'
beforeEach(() => {
recorded.snapshots.mockResolvedValue({ [CORE]: { version: 1, platformVersion: 14, bytes: '' } })
})

/**
* Connect, noting each `getLatestVersions`: its ids, and whether a connection was live then.
* (No localStorage here, so the seeded-snapshot check after going live is always due.)
*/
async function connectNoting(network: Network): Promise<{ ids: string[]; live: boolean }[]> {
const service = new EvoSdkService()
services.push(service)
const calls: { ids: string[]; live: boolean }[] = []
recorded.latest.mockImplementation(async ({ contractIds }) => {
calls.push({ ids: contractIds, live: service.generation > 0 })
recorded.version = 14
return new Map([[CORE, { version: 1 }]])
})
await service.initialize({ network, contractIds: [] })
await vi.advanceTimersByTimeAsync(0)
return calls
}

it('a new SDK below the snapshots\' version learns it from one proved read before going live', async () => {
// rc.8 starts a testnet SDK at 13; with every contract seeded, nothing else would teach it 14.
// The read asks the seeded-snapshot check's question, so that check sends nothing of its own.
recorded.version = 13
expect(await connectNoting('testnet')).toEqual([{ ids: [CORE], live: false }])
})

it('an SDK already at that version, or with no snapshots, sends nothing before going live', async () => {
// Only the seeded-snapshot check, after going live.
expect(await connectNoting('testnet')).toEqual([{ ids: [CORE], live: true }])

recorded.version = 13
recorded.snapshots.mockResolvedValue({})
expect(await connectNoting('testnet')).toEqual([])
})

it('a read that fails or does not answer does not hold up the connect', async () => {
recorded.version = 13
recorded.latest.mockRejectedValue(new Error('no available addresses'))
const failed = new EvoSdkService()
services.push(failed)
await failed.initialize({ network: 'testnet', contractIds: [] })
expect(failed.getStatus().phase).toBe('ready')

let answer!: () => void
const late = new Promise<Map<string, unknown>>((resolve) => (answer = () => resolve(new Map())))
// Only the warm-up's read hangs (the seeded-snapshot check after going live is tracked anyway).
recorded.latest.mockReset().mockReturnValueOnce(late).mockResolvedValue(new Map())
const hung = new EvoSdkService()
const connecting = hung.initialize({ network: 'testnet', contractIds: [] })
await vi.waitFor(() => expect(recorded.latest).toHaveBeenCalledWith({ contractIds: [CORE] }))
expect(hung.getStatus().phase).not.toBe('ready')
await vi.advanceTimersByTimeAsync(LEARN_VERSION_MS)
await connecting
expect(hung.getStatus().phase).toBe('ready')

// The read it stopped waiting for still borrows the SDK: retiring the connection frees it
// only once that read settles (a wasm `free()` under a running call traps).
recorded.free.mockClear()
hung.cleanup()
await vi.advanceTimersByTimeAsync(0)
expect(recorded.free).not.toHaveBeenCalled()
answer()
await vi.waitFor(() => expect(recorded.free).toHaveBeenCalledTimes(1))
})
})
93 changes: 82 additions & 11 deletions forge-web/lib/sdk/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@
* failure never falls back to unverified reads.
*
* What a new connection takes over from the one it replaces:
* - the protocol version: wasm-sdk already seeds each new SDK at the version the last one
* learned (`protocol_version_store`, mainnet/testnet; a devnet's floor is current), and the
* handle's `version()` never reports lower than a version a connection proved;
* - the protocol version: wasm-sdk seeds each new SDK at the version the last one learned
* (`protocol_version_store`, in localStorage, mainnet/testnet; a devnet's floor is current),
* the handle's `version()` never reports lower than a version a connection proved, and a
* connection below the deployment's version learns it before it goes live (without a
* store every connection starts at the built-in floor; {@link learnVersion});
* - which bundled contract snapshots turned out outdated: those are fetched, not seeded
* again. It preloads only the contracts pages used recently, not every id ever named.
* A refreshed connection is installed only while no write is running and the last one ended
Expand Down Expand Up @@ -88,8 +90,15 @@ export interface EvoSdkConfig {
export interface Connection {
readonly sdk: EvoSDK
readonly seeded: Map<string, number>
/** The warm-up's version read, when it was still running as the connection went live ({@link learnVersion}). */
readonly warming?: Promise<unknown>
/** The seeded contracts' latest versions, when the warm-up read them ({@link revalidateSeeded} uses them). */
readonly latest?: LatestVersions
}

/** What `getDataContractsLatestVersions` answers: each contract's current version. */
type LatestVersions = Awaited<ReturnType<EvoSDK['contracts']['getLatestVersions']>>

/** What a new connection takes over from the one it replaces. */
export interface Carry {
/**
Expand Down Expand Up @@ -228,6 +237,11 @@ function versionOf(sdk: EvoSDK): number | undefined {
* frees a retired connection once its last call returned, {@link EvoSdkService.retire}).
*/
function dispose(connection: Connection): void {
// The warm-up's read still borrows the SDK: free it once that read settles.
if (connection.warming !== undefined) {
void connection.warming.then(() => dispose({ sdk: connection.sdk, seeded: connection.seeded }))
return
}
try {
;(connection.sdk.wasm as unknown as { free?: () => void }).free?.()
} catch {
Expand Down Expand Up @@ -1050,13 +1064,16 @@ async function preload(sdk: EvoSDK, contractIds: readonly string[]): Promise<voi
* Add the deployment's contract snapshots (`contract-seed.ts`) to the SDK's contract cache,
* so no page spends a `getDataContract` request on them. `outdated` snapshots (an earlier
* connection found the network had moved on) and any that fail to decode are skipped:
* {@link preload} fetches those.
* {@link preload} fetches those. Also returns the protocol version the snapshots were
* serialized at, the one the deployment needs (deploy-v2 registers only on a network at it):
* the network runs at least that one ({@link learnVersion}).
*/
async function seed(sdk: EvoSDK, deploymentKey: string, outdated: ReadonlySet<string>): Promise<Map<string, number>> {
async function seed(sdk: EvoSDK, deploymentKey: string, outdated: ReadonlySet<string>): Promise<{ seeded: Map<string, number>; floor: number }> {
const seeded = new Map<string, number>()
const snapshots = await loadContractSnapshots(deploymentKey).catch(() => ({}))
const floor = Math.max(0, ...Object.values(snapshots).map((s) => s.platformVersion))
const entries = Object.entries(snapshots).filter(([id]) => !outdated.has(id))
if (entries.length === 0) return seeded
if (entries.length === 0) return { seeded, floor }
const { DataContract } = await import('@dashevo/evo-sdk')
for (const [id, snapshot] of entries) {
try {
Expand All @@ -1066,15 +1083,62 @@ async function seed(sdk: EvoSDK, deploymentKey: string, outdated: ReadonlySet<st
// Fall back to fetching this one.
}
}
return seeded
return { seeded, floor }
}

/** How long the warm-up waits for {@link learnVersion}'s request before going live without it. */
export const LEARN_VERSION_MS = 5_000

/**
* Make sure `sdk` knows the network's protocol version before any page queries. A new SDK
* starts at its built-in floor (rc.8: 13 on testnet) unless wasm-sdk's store in localStorage
* has a learned one, and learns the real one from the first proved response. With every
* contract seeded, connecting sends none, so a page's first query is built at the floor, and
* one the floor does not support (a `timeRange` query below 14) is refused before it is sent.
* One proved request, only when the SDK is below `floor`, teaches it: the seeded contracts'
* latest versions, the question {@link revalidateSeeded} asks next, so it is not asked twice
* (DPNS's, which every network has, when nothing was seeded). A failure, or no answer within
* {@link LEARN_VERSION_MS}, is left to the reads, which learn the version too: the connect never
* waits on it longer. Returns the answer, or the read when it is still running then, so the SDK
* is not freed under it ({@link dispose}).
*/
async function learnVersion(
sdk: EvoSDK,
floor: number,
contractIds: readonly string[],
): Promise<{ readonly latest?: LatestVersions; readonly running?: Promise<unknown> }> {
if ((versionOf(sdk) ?? 0) >= floor) return {}
let settled = false
let latest: LatestVersions | undefined
const read = sdk.contracts
.getLatestVersions({ contractIds: [...contractIds] })
.then((answer) => {
latest = answer
})
.catch(() => undefined)
.finally(() => {
settled = true
})
let timer: ReturnType<typeof setTimeout> | undefined
await Promise.race([
read,
new Promise<void>((resolve) => {
timer = setTimeout(resolve, LEARN_VERSION_MS)
}),
])
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
clearTimeout(timer)
// (Wrapped: an async function returning the promise itself would wait for it.)
if (!settled) return { running: read }
return latest !== undefined ? { latest } : {}
}

/**
* Compare the seeded contracts with the network's current versions (one request,
* `getDataContractsLatestVersions`) and refetch any that moved on, e.g. forge-collab after a
* contract update. The SDK also refetches on its own once a document carries a newer
* `$contractVersion`; this catches the update before any such document is read. Runs at
* most once per {@link SEED_CHECK_MS} per profile while the versions keep matching.
* most once per {@link SEED_CHECK_MS} per profile while the versions keep matching, and asks
* nothing when the warm-up already read the versions ({@link learnVersion}).
*
* Each refetch is a stale-contract refresh ({@link refreshStale}): the page's first reads run
* alongside this check, and one that fails on the old contract meanwhile joins the refetch in
Expand All @@ -1086,7 +1150,7 @@ export async function revalidateSeeded(connection: Connection, deploymentKey: st
const versions = JSON.stringify([...seeded].sort())
if (Date.now() - lastSeedCheck(deploymentKey, versions) < SEED_CHECK_MS) return
try {
const latest = await sdk.contracts.getLatestVersions({ contractIds: [...seeded.keys()] })
const latest = connection.latest ?? (await sdk.contracts.getLatestVersions({ contractIds: [...seeded.keys()] }))
let current = true
for (const [id, version] of [...seeded]) {
const now = latest.get(id)?.version
Expand Down Expand Up @@ -1326,11 +1390,18 @@ async function connectAndWarm(
step(signal, sdk)
// Seed the bundled contracts, then preload what is still missing, BEFORE the connection goes
// live so callers never see an unwarmed SDK.
const seeded = await seed(sdk, NETWORKS[config.network].key, carry.outdated)
const { seeded, floor } = await seed(sdk, NETWORKS[config.network].key, carry.outdated)
step(signal, sdk)
await preload(sdk, config.contractIds.filter((id) => !seeded.has(id)))
step(signal, sdk)
return { sdk, seeded }
const ids = seeded.size > 0 ? [...seeded.keys()] : [NETWORKS[config.network].dpnsContractId]
const { latest, running } = await learnVersion(sdk, floor, ids)
const connection: Connection = { sdk, seeded, ...(running !== undefined ? { warming: running } : {}), ...(latest !== undefined ? { latest } : {}) }
if (signal.aborted) {
dispose(connection)
throw new Error('the connect was abandoned')
}
return connection
}

/** The process-wide evo-sdk service singleton. */
Expand Down
Loading