From 95deea1748aa460d105fc61342eceb5d2f5bfb58 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 10:17:05 -0500 Subject: [PATCH 1/9] wip(web): forge-v2 write library, calibrated costs, spend ledger createDocumentIdempotent waits for the consensus verdict (ConsensusRefusal with its code), measures the balance change and reports it to a spend hook; deletes go through the SDK builder so star/follow use the index-only delete. writes.ts gains the v2 paths: resumable repo creation, owner-only membership, allocateNumber issue numbering with retry on 40105, event/authorEvent routing, reviews, releases, v2 star/follow. Browser v1 repo creation is removed. UI call sites follow in the next commit. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/lib/idb.ts | 112 ++ forge-web/lib/repo/index.ts | 35 +- forge-web/lib/repo/writes.ts | 921 +++++++++----- forge-web/lib/sdk/contract-create.ts | 214 ---- forge-web/lib/sdk/cost.ts | 124 ++ forge-web/lib/sdk/index.ts | 35 +- forge-web/lib/sdk/repo-v1-template.json | 1492 ----------------------- forge-web/lib/sdk/write.test.ts | 127 +- forge-web/lib/sdk/write.ts | 369 ++++-- forge-web/lib/spend.ts | 116 ++ 10 files changed, 1313 insertions(+), 2232 deletions(-) create mode 100644 forge-web/lib/idb.ts delete mode 100644 forge-web/lib/sdk/contract-create.ts create mode 100644 forge-web/lib/sdk/cost.ts delete mode 100644 forge-web/lib/sdk/repo-v1-template.json create mode 100644 forge-web/lib/spend.ts diff --git a/forge-web/lib/idb.ts b/forge-web/lib/idb.ts new file mode 100644 index 000000000..b9b93a87c --- /dev/null +++ b/forge-web/lib/idb.ts @@ -0,0 +1,112 @@ +/** + * A minimal IndexedDB key-value layer: one database, a few object stores, promise-shaped. + * + * Holds the browser's local state that must survive a reload but never leaves the device: + * the spend ledger, write journals (a repo creation interrupted half-way), and the key vault. + * Every call is browser-only; outside a browser (SSR, vitest) the stores are in-memory maps, + * so the modules built on this stay testable without a fake IndexedDB. + */ + +export type StoreName = 'spend' | 'journal' | 'vault' + +const DB_NAME = 'dash-forge' +const DB_VERSION = 1 +const STORES: readonly StoreName[] = ['spend', 'journal', 'vault'] + +let dbPromise: Promise | null = null +const memory = new Map>() + +function hasIndexedDb(): boolean { + return typeof indexedDB !== 'undefined' +} + +function open(): Promise { + if (dbPromise) return dbPromise + dbPromise = new Promise((resolve, reject) => { + const req = indexedDB.open(DB_NAME, DB_VERSION) + req.onupgradeneeded = () => { + for (const name of STORES) { + if (!req.result.objectStoreNames.contains(name)) req.result.createObjectStore(name) + } + } + req.onsuccess = () => resolve(req.result) + req.onerror = () => reject(req.error ?? new Error('IndexedDB open failed')) + }) + dbPromise.catch(() => { + dbPromise = null + }) + return dbPromise +} + +function mem(store: StoreName): Map { + let m = memory.get(store) + if (!m) { + m = new Map() + memory.set(store, m) + } + return m +} + +async function run(store: StoreName, mode: IDBTransactionMode, op: (s: IDBObjectStore) => IDBRequest): Promise { + const db = await open() + return new Promise((resolve, reject) => { + const tx = db.transaction(store, mode) + const req = op(tx.objectStore(store)) + tx.oncomplete = () => resolve(req.result) + tx.onerror = () => reject(tx.error ?? req.error ?? new Error('IndexedDB transaction failed')) + tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted')) + }) +} + +/** Read one value, or undefined. */ +export async function idbGet(store: StoreName, key: string): Promise { + if (!hasIndexedDb()) return structuredClone(mem(store).get(key)) as T | undefined + return (await run(store, 'readonly', (s) => s.get(key))) as T | undefined +} + +/** Write one value (structured-cloned; Uint8Arrays stay binary). */ +export async function idbPut(store: StoreName, key: string, value: T): Promise { + if (!hasIndexedDb()) { + mem(store).set(key, structuredClone(value)) + return + } + await run(store, 'readwrite', (s) => s.put(value, key)) +} + +/** Delete one value (no-op when absent). */ +export async function idbDelete(store: StoreName, key: string): Promise { + if (!hasIndexedDb()) { + mem(store).delete(key) + return + } + await run(store, 'readwrite', (s) => s.delete(key)) +} + +/** Every `[key, value]` in a store whose key starts with `prefix`. */ +export async function idbEntries(store: StoreName, prefix = ''): Promise<[string, T][]> { + if (!hasIndexedDb()) { + return [...mem(store).entries()] + .filter(([k]) => k.startsWith(prefix)) + .map(([k, v]) => [k, structuredClone(v) as T]) + } + const range = prefix === '' ? undefined : IDBKeyRange.bound(prefix, `${prefix}￿`) + const db = await open() + return new Promise((resolve, reject) => { + const out: [string, T][] = [] + const tx = db.transaction(store, 'readonly') + const req = tx.objectStore(store).openCursor(range) + req.onsuccess = () => { + const cursor = req.result + if (!cursor) return + out.push([String(cursor.key), cursor.value as T]) + cursor.continue() + } + tx.oncomplete = () => resolve(out) + tx.onerror = () => reject(tx.error ?? new Error('IndexedDB cursor failed')) + }) +} + +/** Test hook: forget the in-memory fallback stores. */ +export function resetMemoryStores(): void { + memory.clear() +} diff --git a/forge-web/lib/repo/index.ts b/forge-web/lib/repo/index.ts index 00935c4b5..aa07b9e64 100644 --- a/forge-web/lib/repo/index.ts +++ b/forge-web/lib/repo/index.ts @@ -7,8 +7,9 @@ * and derive the collaborators (v2 membership documents, v1 token balances). Every query is * built by a {@link RepoSource}, the one place the two data models differ. * - * WRITE paths (issues, comments, events, stars, follows, releases, collaborator token admin, - * repo creation, minimal ref push) sign + broadcast via the `./writes` WriteEngine. + * WRITE paths (forge-v2 repo creation and membership, issues, comments, events, author events, + * reviews, releases, stars, follows; v1 issue/comment/event/star/follow and token admin) sign + * + broadcast via the `./writes` WriteEngine. */ export { @@ -134,30 +135,44 @@ export { type Stargazer, } from './collab' export { - WriteNotImplementedError, + VERDICT_INT, + addAuthorEvent, addEvent, - closeTarget, createComment, createIssue, - createLabel, createRelease, - createRepo, + createRepoV2, + createReview, + discardRepoCreation, followIdentity, + followIdentityV2, grantCollaborator, + grantMember, hasStarred, + hasStarredV2, isFollowing, - labelTarget, + isFollowingV2, + nextNumberV2, normalizeRepoName, - pushRefUpdate, - reopenTarget, + pendingRepoCreations, revokeCollaborator, + revokeMember, + setTargetState, starRepo, + starRepoV2, + stateEventRoute, suspendCollaborator, unfollowIdentity, + unfollowIdentityV2, unstarRepo, + unstarRepoV2, type CreateIssueResult, - type CreateRepoOptions, + type CreateRepoInput, type CreateRepoResult, + type CreateRepoStep, type EventKindName, type ReleaseAsset, + type RepoCreationJournal, + type VerdictInput, + type WriteTarget, } from './writes' diff --git a/forge-web/lib/repo/writes.ts b/forge-web/lib/repo/writes.ts index 27f6e8f8b..3f7bdbc5c 100644 --- a/forge-web/lib/repo/writes.ts +++ b/forge-web/lib/repo/writes.ts @@ -1,53 +1,55 @@ /** - * Write paths — the browser signing surface (M3 writes implemented). + * Write paths — the browser signing surface, for forge-v2 repos and (where still cheap) v1. * - * Every write builds a document whose on-chain encoding matches forge-core byte-for-byte + * Every write builds a document whose on-chain encoding matches forge-core byte for byte * (identifier fields as raw 32-byte values, `refNameHash = sha256(refName)`, event `kind` - * integers, JSON-in-string list fields), signs it with the acting identity's key via the - * {@link createDocumentIdempotent} WriteEngine, and returns a cost preview for the confirm UI. + * integers), signs it through the {@link createDocumentIdempotent} WriteEngine, and returns + * the estimate shown before signing plus the balance change it caused. * - * Implemented: createIssue, createComment, addEvent (+ close/reopen/label), starRepo/unstar, - * follow/unfollow, createRelease (MAINTAIN), grant/suspend collaborator (token mint/freeze, - * CRITICAL key), createRepo (contract instantiation), pushRefUpdate (minimal). All are - * idempotent — a duplicate-unique collision (re-star, re-follow) resolves as success. + * forge-v2 (`docs/contracts/forge-v2.md`): a repo is three documents in forge-core (`repo`, + * the owner's `maintainer`, the first `config`), created resumably; members are `maintainer` / + * `writer` documents the owner creates and deletes; issues, comments, reviews, `event` + * (members) and `authorEvent` (the author's close/reopen) live in forge-collab, and consensus + * enforces every gate. `star` and `follow` are `indexOnly`: a delete carries the document's + * values (the SDK's index-only delete). Issue numbers follow the `allocateNumber` rule (§6). + * + * v1 (testnet): issue, comment, event, review, release, star, follow and the collaborator + * token admin keep working for existing repos. Creating a v1 repo from the browser is gone: + * new repos are forge-v2 (a v1 repo was a ~1.18 DASH contract). */ import type { EvoSDK } from '@dashevo/evo-sdk' -import { sha256 } from '@noble/hashes/sha2.js' import { hexToBytes } from '@noble/hashes/utils.js' import { requireRegistryContractId, type Network } from '../constants' -import { isLegalRefName } from '../rules' +import type { ForgeIds } from '../deployments' import { decodeIdentifier } from '../auth/base58' -import { errorMessage } from '../utils' +import { idbDelete, idbEntries, idbPut } from '../idb' +import { allocateNumber, numberCeiling, normalizeRepoName as normalizeV2RepoName, type Role } from '../rules/v2' import { + ConsensusRefusal, + DUPLICATE_UNIQUE_CODE, + TOKEN_ADMIN_CREDITS, + countDocuments, createDocumentIdempotent, - createRepoContract, deleteDocumentIdempotent, grantRole, previewCredits, - previewDocumentCreate, queryAllDocuments, queryDocumentsWithProof, - suspendRole, revokeRole, - COST_ESTIMATE_CREDITS, - SECURITY_LEVEL, + suspendRole, type CostPreview, + type DeleteResult, type WriteAuth, type WriteResult, } from '../sdk' -import { DOC, REGISTRY_DOC, type V1RepoRef } from './contract' +import { DOC, REGISTRY_DOC, V2_DOC, asIdentifierString, num, str, type RepoRef, type V1RepoRef, type V2RepoRef } from './contract' +import { invalidateMembers } from './members' +import { invalidateRepoFeed } from './issues' +import { repoSource } from './source' import { invalidateAuthz } from './tokens' -/** Raised only by paths that remain out of scope for M3 (browser push internals). */ -export class WriteNotImplementedError extends Error { - constructor(op: string) { - super(`${op}: not implemented in M3 (advanced browser push — issues/collab/stars are the priorities)`) - this.name = 'WriteNotImplementedError' - } -} - // --------------------------------------------------------------------------- // event kind name → integer (parity with forge-core `event_kind_to_u64`) // --------------------------------------------------------------------------- @@ -77,36 +79,122 @@ const EVENT_KIND_INT: Readonly> = { ready: 10, } +/** Review verdicts (`review.verdict`). */ +export const VERDICT_INT = { approve: 1, requestChanges: 2, comment: 3 } as const +export type VerdictInput = keyof typeof VERDICT_INT + +/** An issue or PR a write refers to: its document id and number. */ +export interface WriteTarget { + readonly id: string + readonly number: number +} + // --------------------------------------------------------------------------- // helpers // --------------------------------------------------------------------------- +function isDuplicate(e: unknown): boolean { + return e instanceof ConsensusRefusal && e.code === DUPLICATE_UNIQUE_CODE +} + +/** The contract a forge-v2 document type lives in (forge-core or forge-collab). */ +function v2ContractFor(repo: V2RepoRef, documentType: string): string { + return repoSource(repo).repoQuery(documentType).dataContractId +} -/** A unique-index collision — for star/follow/issue-number this means "already there". */ -function isDuplicateUniqueError(e: unknown): boolean { - const m = errorMessage(e).toLowerCase() - return m.includes('duplicate') || m.includes('unique index') || m.includes('already exists') +/** The contract a write of `documentType` targets, for either data model. */ +function contractFor(repo: RepoRef, documentType: string): string { + return repo.kind === 'v1' ? repo.contractId : v2ContractFor(repo, documentType) } -function registryId(auth: WriteAuth): string { - return requireRegistryContractId(auth.network) +/** `data` plus, on forge-v2, the `repoId` every repo-scoped type carries. */ +function scoped(repo: RepoRef, data: Record): Record { + return repo.kind === 'v1' ? data : { repoId: decodeIdentifier(repo.repoId), ...data } +} + +/** Drop the caches a write to `repo` invalidates, so the next read shows it. */ +function afterWrite(repo: RepoRef, network: Network): void { + if (repo.kind === 'v2') { + invalidateRepoFeed(repo) + invalidateMembers(repo, network) + } +} + +// --------------------------------------------------------------------------- +// Issue numbering (forge-v2.md §6 `allocate_number`; v1 keeps max + 1) +// --------------------------------------------------------------------------- + +/** The `number` field of a result row, or null. */ +function numberOf(doc: Record): number | null { + const n = num(doc, 'number') + return n > 0 ? n : null +} + +/** + * The number the allocation rule gives the next issue (or PR) of a forge-v2 repo: + * `n` = the provable count, `base` = the largest taken number at or below the ceiling, then + * — only when `base` sits at the ceiling — the contiguous run of taken numbers above it, + * paged to its end. Null when nothing is left to allocate. + */ +export async function nextNumberV2(sdk: EvoSDK, repo: V2RepoRef, type: 'issue' | 'patch'): Promise { + const source = repoSource(repo) + const count = await countDocuments(sdk, source.repoQuery(DOC[type])) + const ceiling = numberCeiling(count) + const { documents } = await queryDocumentsWithProof( + sdk, + source.repoQuery(DOC[type], { + where: [['number', '<=', ceiling]], + orderBy: [['number', 'desc']], + limit: 1, + }), + ) + const base = documents[0] ? numberOf(documents[0]) ?? 0 : 0 + const taken: number[] = base > 0 ? [base] : [] + if (base === ceiling) { + // Squatters may sit right above the ceiling: walk the run to its first gap. + let expect = base + 1 + let startAfter: string | undefined + for (;;) { + const page = await queryDocumentsWithProof( + sdk, + source.repoQuery(DOC[type], { + where: [['number', '>', base]], + orderBy: [['number', 'asc']], + limit: 100, + ...(startAfter ? { startAfter } : {}), + }), + ) + let gap = false + for (const d of page.documents) { + const n = numberOf(d) + if (n !== expect) { + gap = true + break + } + taken.push(n) + expect += 1 + } + const last = page.documents[page.documents.length - 1] + if (gap || page.documents.length < 100 || last === undefined) break + startAfter = str(last, '$id') + } + } + return allocateNumber(count, taken.sort((a, b) => b - a)) } -async function nextIssueNumber(sdk: EvoSDK, repo: V1RepoRef): Promise { +/** v1: the newest number + 1 (a v1 repo contract has no numbering rule beyond uniqueness). */ +async function nextNumberV1(sdk: EvoSDK, repo: V1RepoRef): Promise { const { documents } = await queryDocumentsWithProof(sdk, { dataContractId: repo.contractId, documentTypeName: DOC.issue, orderBy: [['number', 'desc']], limit: 1, }) - // Content integer fields come back as bigint (only system fields are normalized to number). - const top = documents[0]?.['number'] - const max = typeof top === 'bigint' ? Number(top) : typeof top === 'number' ? top : 0 - return max + 1 + return (documents[0] ? numberOf(documents[0]) ?? 0 : 0) + 1 } // --------------------------------------------------------------------------- -// Issues / comments / events +// Issues / comments / events / reviews // --------------------------------------------------------------------------- /** A created issue: the write result plus the allocated issue number. */ @@ -115,122 +203,172 @@ export interface CreateIssueResult extends WriteResult { } /** - * Create an `issue` (ungated create; author-owned). The number is optimistically `max+1`, - * retried on a unique-index collision (a concurrent create took it). Returns the write result - * and final number. + * Create an `issue` (ungated; anyone). The number comes from the repo's numbering rule; when + * consensus refuses it as taken (someone claimed it between the read and the write), the + * allocation runs again — the squatted number is now `base` — and `onRetry` is told, so the + * UI can say "Someone claimed #42 a moment ago; retrying as #43" (`ux-dx-spec.md` §1d). */ export async function createIssue( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, + repo: RepoRef, input: { title: string; body: string }, + onRetry?: (taken: number, next: number) => void, ): Promise { - let number = await nextIssueNumber(sdk, repo) - for (let attempt = 0; attempt < 5; attempt++) { + let number = repo.kind === 'v2' ? await nextNumberV2(sdk, repo, 'issue') : await nextNumberV1(sdk, repo) + for (let attempt = 0; attempt < 4; attempt++) { + if (number === null) throw new Error('this repo has no issue numbers left to allocate') const data: Record = { number, title: input.title } if (input.body.length > 0) data['body'] = input.body try { const result = await createDocumentIdempotent(sdk, auth, { - contractId: repo.contractId, + contractId: contractFor(repo, DOC.issue), documentType: DOC.issue, - data, + data: scoped(repo, data), }) + afterWrite(repo, auth.network) return { ...result, number } } catch (e) { - if (isDuplicateUniqueError(e)) { - number += 1 - continue - } - throw e + if (!isDuplicate(e)) throw e + const taken: number = number + number = repo.kind === 'v2' ? await nextNumberV2(sdk, repo, 'issue') : taken + 1 + if (number !== null && number <= taken) number = taken + 1 + if (number !== null) onRetry?.(taken, number) } } - throw new Error('exhausted issue-number allocation attempts') + throw new Error('could not claim an issue number after several attempts; try again') } -/** Create a `comment` on an issue/PR (ungated; author-owned). */ +/** Create a `comment` on an issue or PR (ungated; author-owned). */ export async function createComment( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, + repo: RepoRef, input: { targetId: string; body: string; replyTo?: string }, ): Promise { - const data: Record = { - targetId: decodeIdentifier(input.targetId), - body: input.body, - } + const data: Record = { targetId: decodeIdentifier(input.targetId), body: input.body } if (input.replyTo) data['replyTo'] = decodeIdentifier(input.replyTo) - return createDocumentIdempotent(sdk, auth, { - contractId: repo.contractId, + const result = await createDocumentIdempotent(sdk, auth, { + contractId: contractFor(repo, DOC.comment), documentType: DOC.comment, - data, + data: scoped(repo, data), }) + afterWrite(repo, auth.network) + return result +} + +/** The document data of a state event on `target`. */ +function eventData( + repo: RepoRef, + target: WriteTarget, + kind: EventKindName, + extra: { value?: string; oidHex?: string } = {}, +): Record { + const data: Record = { targetId: decodeIdentifier(target.id), kind: EVENT_KIND_INT[kind] } + if (repo.kind === 'v2') data['targetNumber'] = target.number + if (extra.value !== undefined && extra.value.length > 0) data['value'] = extra.value + if (extra.oidHex !== undefined && extra.oidHex.length > 0) data['oid'] = hexToBytes(extra.oidHex) + return scoped(repo, data) } /** - * Append an `event` (close/reopen/label/assign/…) to the append-only state log. The event is - * authoritative only if the fold deems the actor authorized as-of its `$createdAt`; a - * non-holder's event lands but is inert. `oidHex` (a git object id) is optional. + * Append a member `event` (close / reopen / label / assign / merge mark, …). On forge-v2 + * consensus admits it only from a current maintainer or writer (40120 otherwise); on v1 it + * lands for anyone and the fold decides whether it counts. */ export async function addEvent( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, - input: { targetId: string; kind: EventKindName; value?: string; oidHex?: string }, + repo: RepoRef, + input: { target: WriteTarget; kind: EventKindName; value?: string; oidHex?: string }, ): Promise { - const data: Record = { - targetId: decodeIdentifier(input.targetId), - kind: EVENT_KIND_INT[input.kind], - } - if (input.value !== undefined && input.value.length > 0) data['value'] = input.value - if (input.oidHex !== undefined && input.oidHex.length > 0) data['oid'] = hexToBytes(input.oidHex) - return createDocumentIdempotent(sdk, auth, { - contractId: repo.contractId, + const result = await createDocumentIdempotent(sdk, auth, { + contractId: contractFor(repo, DOC.event), documentType: DOC.event, - data, + data: eventData(repo, input.target, input.kind, input), }) + afterWrite(repo, auth.network) + return result } -/** Convenience: close an issue/PR. */ -export function closeTarget( +/** + * The issue or PR author's own close / reopen. forge-v2 has a type for it (`authorEvent`, + * gated to the target's author, `forge-v2.md` §3); v1 folds the author's plain `event`. + */ +export async function addAuthorEvent( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, - targetId: string, + repo: RepoRef, + input: { target: WriteTarget; kind: 'close' | 'reopen' }, ): Promise { - return addEvent(sdk, auth, repo, { targetId, kind: 'close' }) + if (repo.kind === 'v1') return addEvent(sdk, auth, repo, input) + const result = await createDocumentIdempotent(sdk, auth, { + contractId: v2ContractFor(repo, V2_DOC.authorEvent), + documentType: V2_DOC.authorEvent, + data: eventData(repo, input.target, input.kind), + }) + afterWrite(repo, auth.network) + return result } -/** Convenience: reopen an issue/PR. */ -export function reopenTarget( +/** Which state-event type a close/reopen by the viewer should be. */ +export function stateEventRoute(params: { + readonly viewer: string + readonly author: string + readonly isMember: boolean +}): 'event' | 'authorEvent' | null { + // A member's event is cheaper and needs no authorship; the author path needs no membership. + if (params.isMember) return 'event' + return params.viewer === params.author ? 'authorEvent' : null +} + +/** Close or reopen an issue/PR by whichever route the viewer holds. */ +export async function setTargetState( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, - targetId: string, + repo: RepoRef, + input: { target: WriteTarget; kind: 'close' | 'reopen'; author: string; isMember: boolean }, ): Promise { - return addEvent(sdk, auth, repo, { targetId, kind: 'reopen' }) + const route = stateEventRoute({ viewer: auth.identityId, author: input.author, isMember: input.isMember }) + if (route === null) throw new Error('only the author or a maintainer or writer can do that') + if (route === 'authorEvent') return addAuthorEvent(sdk, auth, repo, input) + try { + return await addEvent(sdk, auth, repo, input) + } catch (e) { + // The membership read was stale (revoked meanwhile): the author path still holds. + const gateRefused = e instanceof ConsensusRefusal && e.code === 40120 + if (gateRefused && auth.identityId === input.author) return addAuthorEvent(sdk, auth, repo, input) + throw e + } } -/** Convenience: add or remove a label (MAINTAIN-authoritative via the fold). */ -export function labelTarget( +/** Submit a PR review: a verdict on `commitOid` (the head it was made against). */ +export async function createReview( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, - targetId: string, - label: string, - remove = false, + repo: RepoRef, + input: { patchId: string; verdict: VerdictInput; commitOid: string; body?: string }, ): Promise { - return addEvent(sdk, auth, repo, { - targetId, - kind: remove ? 'labelRemove' : 'labelAdd', - value: label, + const data: Record = { + patchId: decodeIdentifier(input.patchId), + verdict: VERDICT_INT[input.verdict], + commitOid: hexToBytes(input.commitOid), + } + if (input.body && input.body.length > 0) data['body'] = input.body + const result = await createDocumentIdempotent(sdk, auth, { + contractId: contractFor(repo, DOC.review), + documentType: DOC.review, + data: scoped(repo, data), }) + afterWrite(repo, auth.network) + return result } // --------------------------------------------------------------------------- -// Releases (MAINTAIN-gated) + labels +// Releases (maintainer-only on v2; MAINTAIN-gated on v1) // --------------------------------------------------------------------------- -/** A release asset (hash-verified download; stored JSON-in-string, D1). */ +/** A release asset (hash-verified download; stored as a JSON string). */ export interface ReleaseAsset { readonly name: string readonly sha256: string @@ -238,146 +376,140 @@ export interface ReleaseAsset { readonly uri: string } -/** Create a `release` (MAINTAIN-gated). Assets are JSON-encoded (v12: no native arrays). */ +/** Create a `release`: newest per tag wins. Maintainers only (consensus on v2). */ export async function createRelease( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, - input: { - tagName: string - name?: string - notes?: string - yanked?: boolean - assets?: readonly ReleaseAsset[] - }, + repo: RepoRef, + input: { tagName: string; name?: string; notes?: string; yanked?: boolean; assets?: readonly ReleaseAsset[] }, ): Promise { const data: Record = { tagName: input.tagName, yanked: input.yanked ?? false } if (input.name && input.name.length > 0) data['name'] = input.name if (input.notes && input.notes.length > 0) data['notes'] = input.notes if (input.assets && input.assets.length > 0) data['assets'] = JSON.stringify(input.assets) return createDocumentIdempotent(sdk, auth, { - contractId: repo.contractId, + contractId: contractFor(repo, DOC.release), documentType: DOC.release, - data, + data: scoped(repo, data), }) } -/** Create (or supersede) a `label` definition (MAINTAIN-gated; newest doc per name wins). */ -export async function createLabel( +// --------------------------------------------------------------------------- +// forge-v2 social: star / follow (indexOnly) +// --------------------------------------------------------------------------- + +interface RawDocumentsFacade { + query(q: unknown): Promise> +} + +/** + * The viewer's own `star` / `follow` document for `targetId` as the wasm `Document` the query + * returned — an index-only delete needs its values, not just an id. Null when there is none. + * The `byOwner` index ends in the target, so `($ownerId, target)` selects at most one. + */ +async function findOwnIndexOnly( sdk: EvoSDK, - auth: WriteAuth, - repo: V1RepoRef, - input: { name: string; color?: string; description?: string; retired?: boolean }, -): Promise { - const data: Record = { name: input.name, retired: input.retired ?? false } - if (input.color && input.color.length > 0) data['color'] = input.color - if (input.description && input.description.length > 0) data['description'] = input.description - return createDocumentIdempotent(sdk, auth, { - contractId: repo.contractId, - documentType: DOC.label, - data, + forge: ForgeIds, + type: 'star' | 'follow', + ownerId: string, + targetId: string, +): Promise { + const field = type === 'star' ? 'repoId' : 'identityId' + const rows = await (sdk as unknown as { documents: RawDocumentsFacade }).documents.query({ + dataContractId: forge.collab, + documentTypeName: type, + where: [ + ['$ownerId', '==', ownerId], + [field, '==', targetId], + ], + orderBy: [['$ownerId', 'asc']], + limit: 1, }) + for (const doc of rows.values()) if (doc) return doc + return null } -// --------------------------------------------------------------------------- -// Social (registry) — stars + follows -// --------------------------------------------------------------------------- +/** Whether `viewer` has starred the forge-v2 repo. Throws on a read failure. */ +export async function hasStarredV2(sdk: EvoSDK, repo: V2RepoRef, viewer: string): Promise { + return (await findOwnIndexOnly(sdk, repo.forge, 'star', viewer, repo.repoId)) !== null +} -/** Star a repo listing (`star` create in the registry). Idempotent: a re-star is a success. */ -export async function starRepo( - sdk: EvoSDK, - auth: WriteAuth, - listingId: string, -): Promise { - const contractId = registryId(auth) +/** Star a forge-v2 repo. Idempotent: a second star is refused as a duplicate, which is success. */ +export async function starRepoV2(sdk: EvoSDK, auth: WriteAuth, repo: V2RepoRef): Promise { + const probe = (): Promise => hasStarredV2(sdk, repo, auth.identityId) try { return await createDocumentIdempotent(sdk, auth, { - contractId, - documentType: REGISTRY_DOC.star, - data: { listingId: decodeIdentifier(listingId) }, + contractId: repo.forge.collab, + documentType: V2_DOC.star, + data: { repoId: decodeIdentifier(repo.repoId) }, + probe, }) } catch (e) { - if (isDuplicateUniqueError(e)) { - const existing = await findOwnRegistryDoc(sdk, auth.network, auth.identityId, REGISTRY_DOC.star, 'listingId', listingId) - return { - documentId: existing ?? '', - confirmed: true, - cost: previewDocumentCreate(REGISTRY_DOC.star), - } - } + if (isDuplicate(e)) return { documentId: '', confirmed: true, cost: previewCredits(0), actualCredits: 0 } throw e } } -/** Unstar a repo (delete the caller's own `star` for `listingId`). No-op if not starred. */ -export async function unstarRepo( - sdk: EvoSDK, - auth: WriteAuth, - listingId: string, -): Promise<{ deleted: boolean }> { - const contractId = registryId(auth) - const existing = await findOwnRegistryDoc(sdk, auth.network, auth.identityId, REGISTRY_DOC.star, 'listingId', listingId) - if (!existing) return { deleted: true } +/** Unstar a forge-v2 repo: an index-only delete carrying the star's values. */ +export async function unstarRepoV2(sdk: EvoSDK, auth: WriteAuth, repo: V2RepoRef): Promise { + const own = await findOwnIndexOnly(sdk, repo.forge, 'star', auth.identityId, repo.repoId) + if (own === null) return { deleted: true, actualCredits: 0 } return deleteDocumentIdempotent(sdk, auth, { - contractId, - documentType: REGISTRY_DOC.star, - documentId: existing, + contractId: repo.forge.collab, + documentType: V2_DOC.star, + documentId: repo.repoId, + document: own, + probeGone: async () => !(await hasStarredV2(sdk, repo, auth.identityId)), }) } -/** Follow an identity (`follow` create in the registry). Idempotent. */ -export async function followIdentity( - sdk: EvoSDK, - auth: WriteAuth, - identityId: string, -): Promise { - const contractId = registryId(auth) +/** Whether `viewer` follows `target` (forge-collab `follow`). Throws on a read failure. */ +export async function isFollowingV2(sdk: EvoSDK, forge: ForgeIds, viewer: string, target: string): Promise { + return (await findOwnIndexOnly(sdk, forge, 'follow', viewer, target)) !== null +} + +/** Follow an identity on forge-v2. Idempotent. */ +export async function followIdentityV2(sdk: EvoSDK, auth: WriteAuth, forge: ForgeIds, target: string): Promise { try { return await createDocumentIdempotent(sdk, auth, { - contractId, - documentType: REGISTRY_DOC.follow, - data: { identityId: decodeIdentifier(identityId) }, + contractId: forge.collab, + documentType: V2_DOC.follow, + data: { identityId: decodeIdentifier(target) }, + probe: () => isFollowingV2(sdk, forge, auth.identityId, target), }) } catch (e) { - if (isDuplicateUniqueError(e)) { - const existing = await findOwnRegistryDoc( - sdk, - auth.network, - auth.identityId, - REGISTRY_DOC.follow, - 'identityId', - identityId, - ) - return { - documentId: existing ?? '', - confirmed: true, - cost: previewDocumentCreate(REGISTRY_DOC.follow), - } - } + if (isDuplicate(e)) return { documentId: '', confirmed: true, cost: previewCredits(0), actualCredits: 0 } throw e } } -/** Unfollow an identity (delete the caller's own `follow`). No-op if not following. */ -export async function unfollowIdentity( +/** Unfollow on forge-v2: an index-only delete carrying the follow's values. */ +export async function unfollowIdentityV2( sdk: EvoSDK, auth: WriteAuth, - identityId: string, -): Promise<{ deleted: boolean }> { - const contractId = registryId(auth) - const existing = await findOwnRegistryDoc(sdk, auth.network, auth.identityId, REGISTRY_DOC.follow, 'identityId', identityId) - if (!existing) return { deleted: true } + forge: ForgeIds, + target: string, +): Promise { + const own = await findOwnIndexOnly(sdk, forge, 'follow', auth.identityId, target) + if (own === null) return { deleted: true, actualCredits: 0 } return deleteDocumentIdempotent(sdk, auth, { - contractId, - documentType: REGISTRY_DOC.follow, - documentId: existing, + contractId: forge.collab, + documentType: V2_DOC.follow, + documentId: target, + document: own, + probeGone: async () => !(await isFollowingV2(sdk, forge, auth.identityId, target)), }) } +// --------------------------------------------------------------------------- +// v1 social (registry) — stars + follows on existing v1 networks +// --------------------------------------------------------------------------- + /** * Resolve `ownerId`'s own registry doc (star/follow) whose `field` equals `targetId`, via the * `$ownerId` index (filtered client-side by field — the single-field owner query matches the - * deployed registry index, mirroring forge-core `find_own`). + * deployed registry index, mirroring forge-core `find_own`). Complete: a user past 100 stars + * could otherwise not remove an older one. */ async function findOwnRegistryDoc( sdk: EvoSDK, @@ -387,20 +519,14 @@ async function findOwnRegistryDoc( field: string, targetId: string, ): Promise { - const contractId = requireRegistryContractId(network) - // Complete, matching forge-core `find_own`: this backs un-star / un-follow, and a user - // past 100 stars could otherwise not remove an older one — while the call still reported - // success, since "not found" and "not looked at" are indistinguishable here. const documents = await queryAllDocuments(sdk, { - dataContractId: contractId, + dataContractId: requireRegistryContractId(network), documentTypeName: documentType, where: [['$ownerId', '==', ownerId]], orderBy: [['$ownerId', 'asc'], ['$createdAt', 'desc']], }) for (const doc of documents) { - const v = doc[field] - // Identifier fields come back base58 from the SDK's toObject(); compare directly. - if (typeof v === 'string' && v === targetId) { + if (asIdentifierString(doc[field]) === targetId) { const id = doc['$id'] if (typeof id === 'string') return id } @@ -408,34 +534,142 @@ async function findOwnRegistryDoc( return null } -/** - * Whether `identityId` has starred `listingId` — the viewer's initial star state. Throws on a - * read failure: a star button that silently read "not starred" would offer the wrong action. - */ -export async function hasStarred( +async function createRegistryRelation( sdk: EvoSDK, - network: Network, - identityId: string, - listingId: string, -): Promise { - return (await findOwnRegistryDoc(sdk, network, identityId, REGISTRY_DOC.star, 'listingId', listingId)) !== null + auth: WriteAuth, + documentType: string, + field: string, + targetId: string, +): Promise { + try { + return await createDocumentIdempotent(sdk, auth, { + contractId: requireRegistryContractId(auth.network), + documentType, + data: { [field]: decodeIdentifier(targetId) }, + }) + } catch (e) { + if (!isDuplicate(e)) throw e + const existing = await findOwnRegistryDoc(sdk, auth.network, auth.identityId, documentType, field, targetId) + return { documentId: existing ?? '', confirmed: true, cost: previewCredits(0), actualCredits: 0 } + } } -/** Whether `identityId` follows `targetId` — the viewer's initial follow state. Throws on failure. */ -export async function isFollowing( +async function deleteRegistryRelation( sdk: EvoSDK, - network: Network, - identityId: string, + auth: WriteAuth, + documentType: string, + field: string, targetId: string, -): Promise { +): Promise { + const existing = await findOwnRegistryDoc(sdk, auth.network, auth.identityId, documentType, field, targetId) + if (!existing) return { deleted: true, actualCredits: 0 } + return deleteDocumentIdempotent(sdk, auth, { + contractId: requireRegistryContractId(auth.network), + documentType, + documentId: existing, + }) +} + +/** Star a v1 repo listing. Idempotent. */ +export function starRepo(sdk: EvoSDK, auth: WriteAuth, listingId: string): Promise { + return createRegistryRelation(sdk, auth, REGISTRY_DOC.star, 'listingId', listingId) +} + +/** Unstar a v1 repo listing. No-op if not starred. */ +export function unstarRepo(sdk: EvoSDK, auth: WriteAuth, listingId: string): Promise { + return deleteRegistryRelation(sdk, auth, REGISTRY_DOC.star, 'listingId', listingId) +} + +/** Follow an identity in the v1 registry. Idempotent. */ +export function followIdentity(sdk: EvoSDK, auth: WriteAuth, identityId: string): Promise { + return createRegistryRelation(sdk, auth, REGISTRY_DOC.follow, 'identityId', identityId) +} + +/** Unfollow an identity in the v1 registry. No-op if not following. */ +export function unfollowIdentity(sdk: EvoSDK, auth: WriteAuth, identityId: string): Promise { + return deleteRegistryRelation(sdk, auth, REGISTRY_DOC.follow, 'identityId', identityId) +} + +/** Whether `identityId` has starred v1 `listingId`. Throws on a read failure. */ +export async function hasStarred(sdk: EvoSDK, network: Network, identityId: string, listingId: string): Promise { + return (await findOwnRegistryDoc(sdk, network, identityId, REGISTRY_DOC.star, 'listingId', listingId)) !== null +} + +/** Whether `identityId` follows `targetId` in the v1 registry. Throws on a read failure. */ +export async function isFollowing(sdk: EvoSDK, network: Network, identityId: string, targetId: string): Promise { return (await findOwnRegistryDoc(sdk, network, identityId, REGISTRY_DOC.follow, 'identityId', targetId)) !== null } // --------------------------------------------------------------------------- -// Collaborators (token admin — CRITICAL key) +// forge-v2 membership (owner-only) // --------------------------------------------------------------------------- -/** Grant a collaborator WRITE (`maintain=false`) or MAINTAIN (`maintain=true`) — token mint. */ +const ROLE_DOC: Readonly> = { maintainer: V2_DOC.maintainer, writer: V2_DOC.writer } + +/** The membership document `(repoId, memberId)` of `role`, or null. */ +async function findMembership(sdk: EvoSDK, repo: V2RepoRef, role: Role, memberId: string): Promise { + const { documents } = await queryDocumentsWithProof( + sdk, + repoSource(repo).repoQuery(ROLE_DOC[role], { where: [['memberId', '==', memberId]], limit: 1 }), + ) + const id = documents[0]?.['$id'] + return typeof id === 'string' ? id : null +} + +/** + * Grant `memberId` a role on a forge-v2 repo: the owner creates a `maintainer` or `writer` + * document (consensus refuses anyone else). Idempotent: an existing membership is success. + */ +export async function grantMember( + sdk: EvoSDK, + auth: WriteAuth, + repo: V2RepoRef, + memberId: string, + role: Role, +): Promise { + if (auth.identityId !== repo.ownerId) throw new Error('only the repo owner can add members') + decodeIdentifier(memberId) + try { + const result = await createDocumentIdempotent(sdk, auth, { + contractId: repo.forge.core, + documentType: ROLE_DOC[role], + data: { repoId: decodeIdentifier(repo.repoId), memberId: decodeIdentifier(memberId) }, + }) + invalidateMembers(repo, auth.network) + return result + } catch (e) { + if (!isDuplicate(e)) throw e + invalidateMembers(repo, auth.network) + const existing = await findMembership(sdk, repo, role, memberId) + return { documentId: existing ?? '', confirmed: true, cost: previewCredits(0), actualCredits: 0 } + } +} + +/** Revoke a role: the owner deletes the membership document. No-op when there is none. */ +export async function revokeMember( + sdk: EvoSDK, + auth: WriteAuth, + repo: V2RepoRef, + memberId: string, + role: Role, +): Promise { + if (auth.identityId !== repo.ownerId) throw new Error('only the repo owner can remove members') + const existing = await findMembership(sdk, repo, role, memberId) + if (existing === null) return { deleted: true, actualCredits: 0 } + const result = await deleteDocumentIdempotent(sdk, auth, { + contractId: repo.forge.core, + documentType: ROLE_DOC[role], + documentId: existing, + }) + invalidateMembers(repo, auth.network) + return result +} + +// --------------------------------------------------------------------------- +// v1 collaborators (token admin — CRITICAL key) +// --------------------------------------------------------------------------- + +/** Grant a v1 collaborator WRITE (`maintain=false`) or MAINTAIN — token mint. */ export async function grantCollaborator( sdk: EvoSDK, auth: WriteAuth, @@ -445,10 +679,10 @@ export async function grantCollaborator( ): Promise<{ minted: boolean; cost: CostPreview }> { const result = await grantRole(sdk, auth, repo.contractId, memberId, maintain ? 'maintain' : 'write') invalidateAuthz(repo.contractId) - return { ...result, cost: previewCredits(COST_ESTIMATE_CREDITS.tokenAdmin) } + return { ...result, cost: previewCredits(TOKEN_ADMIN_CREDITS) } } -/** Suspend (freeze) a collaborator's role — token freeze. */ +/** Suspend (freeze) a v1 collaborator's role — token freeze. */ export async function suspendCollaborator( sdk: EvoSDK, auth: WriteAuth, @@ -458,10 +692,10 @@ export async function suspendCollaborator( ): Promise<{ frozen: boolean; cost: CostPreview }> { const result = await suspendRole(sdk, auth, repo.contractId, memberId, maintain ? 'maintain' : 'write') invalidateAuthz(repo.contractId) - return { ...result, cost: previewCredits(COST_ESTIMATE_CREDITS.tokenAdmin) } + return { ...result, cost: previewCredits(TOKEN_ADMIN_CREDITS) } } -/** Revoke a collaborator's role — token freeze + destroy. */ +/** Revoke a v1 collaborator's role — token freeze + destroy. */ export async function revokeCollaborator( sdk: EvoSDK, auth: WriteAuth, @@ -471,141 +705,170 @@ export async function revokeCollaborator( ): Promise<{ revoked: boolean; cost: CostPreview }> { const result = await revokeRole(sdk, auth, repo.contractId, memberId, maintain ? 'maintain' : 'write') invalidateAuthz(repo.contractId) - return { ...result, cost: previewCredits(COST_ESTIMATE_CREDITS.tokenAdmin) } + return { ...result, cost: previewCredits(TOKEN_ADMIN_CREDITS) } } // --------------------------------------------------------------------------- -// Repo lifecycle +// forge-v2 repo creation (three documents, resumable) // --------------------------------------------------------------------------- -/** Options for {@link createRepo}. */ -export interface CreateRepoOptions { - readonly defaultBranch?: string - readonly backendMode?: number +/** Options for {@link createRepoV2}. */ +export interface CreateRepoInput { + readonly name: string readonly description?: string - readonly templateVersion?: number + readonly defaultBranch?: string } -/** A created repo: its contract id, the registry listing id, and the cost preview. */ +/** The steps of a repo creation, in order. */ +export type CreateRepoStep = 'repo' | 'maintainer' | 'config' + +/** A repo creation's journal entry (IndexedDB), kept until all three documents exist. */ +export interface RepoCreationJournal { + readonly network: Network + readonly ownerId: string + readonly input: CreateRepoInput + readonly repoId: string | null + readonly done: readonly CreateRepoStep[] + readonly startedAt: number +} + +/** A created (or completed) repo. */ export interface CreateRepoResult { - readonly contractId: string - readonly listingId: string - readonly cost: CostPreview -} - -/** Validate + normalize a repo name (`^[a-z0-9][a-z0-9._-]{0,62}$` after lowercasing). */ -export function normalizeRepoName(name: string): string { - const normalized = name.toLowerCase() - const bytes = new TextEncoder().encode(normalized) - const first = bytes[0] - const valid = - bytes.length >= 1 && - bytes.length <= 63 && - first !== undefined && - isAlnum(first) && - bytes.slice(1).every((b) => isAlnum(b) || b === 0x2e || b === 0x2d || b === 0x5f) - if (!valid) { - throw new Error(`invalid repo name '${name}': must match ^[a-z0-9][a-z0-9._-]{0,62}$`) - } - return normalized + readonly repoId: string + readonly name: string + /** Credits the steps this run performed took (null when a balance read failed). */ + readonly actualCredits: number | null } -function isAlnum(b: number): boolean { - return (b >= 0x30 && b <= 0x39) || (b >= 0x61 && b <= 0x7a) +function journalKey(network: Network, ownerId: string, name: string): string { + return `create-repo:${network}:${ownerId}:${name}` } -/** - * Create a repository: instantiate its per-repo token contract (the ~1.18 DASH DataContractCreate, - * CRITICAL key) then write its initial `config` (MAINTAIN — owner holds it via baseSupply) and the - * registry `repoListing` (ungated). Idempotent at the contract level via the caller's deterministic - * identity nonce; the follow-on config/listing writes are individually idempotent. - */ -export async function createRepo( - sdk: EvoSDK, - auth: WriteAuth, - name: string, - opts: CreateRepoOptions = {}, -): Promise { - const normalized = normalizeRepoName(name) - // No registry on this network: fail before paying for a contract whose listing could never - // be published (parity with forge-core `create_repo`). - const listingRegistry = registryId(auth) - const contract = await createRepoContract(sdk, auth) - const contractId = contract.contractId - - // config (MAINTAIN-gated create; auto tokenPayment via the gate table). - await createDocumentIdempotent(sdk, auth, { - contractId, - documentType: DOC.config, - data: { - defaultBranch: opts.defaultBranch ?? 'main', - protectedPatterns: '[]', - backend: { mode: opts.backendMode ?? 0, uris: '[]' }, - archived: false, - }, - requiredLevel: SECURITY_LEVEL.HIGH, - }) +/** Unfinished repo creations of `ownerId` (a tab closed mid-way), oldest first. */ +export async function pendingRepoCreations(network: Network, ownerId: string): Promise { + const rows = await idbEntries('journal', `create-repo:${network}:${ownerId}:`) + return rows.map(([, v]) => v).sort((a, b) => a.startedAt - b.startedAt) +} - // registry repoListing (ungated). - const listing = await createDocumentIdempotent(sdk, auth, { - contractId: listingRegistry, - documentType: REGISTRY_DOC.repoListing, - data: { - name, - normalizedName: normalized, - repoContractId: decodeIdentifier(contractId), - templateVersion: opts.templateVersion ?? 1, - description: opts.description ?? '', - topics: '[]', - }, - }) +/** Forget an unfinished creation (the user abandoned it). */ +export function discardRepoCreation(network: Network, ownerId: string, name: string): Promise { + return idbDelete('journal', journalKey(network, ownerId, name)) +} - return { - contractId, - listingId: listing.documentId, - cost: previewCredits(COST_ESTIMATE_CREDITS.repoCreate), +/** A valid forge-v2 repo name for `input` (ASCII lowercased), or an error saying why not. */ +export function normalizeRepoName(input: string): string { + const name = normalizeV2RepoName(input.trim()) + if (name === null) { + throw new Error(`invalid repo name '${input}': use a-z, 0-9, '.', '_' and '-' (max 63), starting with a letter or digit`) } + return name } -// --------------------------------------------------------------------------- -// Ref updates (minimal browser push) -// --------------------------------------------------------------------------- - /** - * Post a `refUpdate` (WRITE-gated) — the minimal browser push. `newOidHex`/`prevOidHex` are git - * object ids (hex); an all-zero `newOid` is a delete. `refNameHash = sha256(refName)` matches - * forge-core. Protected-ref routing (to `protectedRefUpdate`, MAINTAIN) requires the repo's - * config patterns; pass `protected` when known. Full browser push (pack chunking) is out of M3. + * Create a forge-v2 repository: its `repo` document, the owner's `maintainer` document (the + * owner self-enrols, `forge-v2.md` §6, or nobody could push) and its first `config`. Each step + * checks the chain first, so a rerun after an interruption completes what is missing instead + * of failing on the unique `($ownerId, name)` index; the IndexedDB journal lets the UI offer + * that rerun. `onStep` reports progress. */ -export async function pushRefUpdate( +export async function createRepoV2( sdk: EvoSDK, auth: WriteAuth, - repo: V1RepoRef, - input: { - refName: string - newOidHex: string - prevOidHex?: string - force?: boolean - protected?: boolean - }, -): Promise { - if (!isLegalRefName(input.refName)) { - throw new Error(`illegal ref name ${JSON.stringify(input.refName)}`) + forge: ForgeIds, + input: CreateRepoInput, + onStep?: (step: CreateRepoStep, state: 'start' | 'done') => void, +): Promise { + const name = normalizeRepoName(input.name) + const ownerId = auth.identityId + const key = journalKey(auth.network, ownerId, name) + const journal: { -readonly [K in keyof RepoCreationJournal]: RepoCreationJournal[K] } = { + network: auth.network, + ownerId, + input: { ...input, name }, + repoId: null, + done: [], + startedAt: Date.now(), } - const refNameHash = sha256(new TextEncoder().encode(input.refName)) - const data: Record = { - refNameHash, - refName: input.refName, - newOid: hexToBytes(input.newOidHex), - force: input.force ?? false, + const save = (): Promise => idbPut('journal', key, journal) + await save() + let spent: number | null = 0 + const add = (r: { actualCredits: number | null }): void => { + spent = spent === null || r.actualCredits === null ? null : spent + r.actualCredits } - if (input.prevOidHex && input.prevOidHex.length > 0) { - data['prevOid'] = hexToBytes(input.prevOidHex) + const step = async (s: CreateRepoStep, run: () => Promise): Promise => { + onStep?.(s, 'start') + await run() + journal.done = [...journal.done, s] + await save() + onStep?.(s, 'done') } - const documentType = input.protected ? DOC.protectedRefUpdate : DOC.refUpdate - return createDocumentIdempotent(sdk, auth, { - contractId: repo.contractId, - documentType, - data, + + // 1. repo (unique per owner + name) + const existingRepo = async (): Promise => { + const { documents } = await queryDocumentsWithProof(sdk, { + dataContractId: forge.core, + documentTypeName: V2_DOC.repo, + where: [ + ['$ownerId', '==', ownerId], + ['name', '==', name], + ], + limit: 1, + }) + const id = documents[0]?.['$id'] + return typeof id === 'string' ? id : null + } + let repoId = await existingRepo() + await step('repo', async () => { + if (repoId !== null) return + const data: Record = { name, visibility: 'public' } + if (input.description) data['description'] = input.description + if (input.defaultBranch) data['defaultBranch'] = input.defaultBranch + try { + const r = await createDocumentIdempotent(sdk, auth, { contractId: forge.core, documentType: V2_DOC.repo, data }) + add(r) + repoId = r.documentId + } catch (e) { + if (!isDuplicate(e)) throw e + repoId = await existingRepo() + if (repoId === null) throw e + } + }) + if (repoId === null) throw new Error('the repo document did not land; try again') + journal.repoId = repoId + await save() + const R = decodeIdentifier(repoId) + const repo: V2RepoRef = { kind: 'v2', forge, repoId, ownerId, name, visibility: 'public' } + + // 2. the owner's maintainer document (unique per repo + member) + await step('maintainer', async () => { + if ((await findMembership(sdk, repo, 'maintainer', ownerId)) !== null) return + try { + add( + await createDocumentIdempotent(sdk, auth, { + contractId: forge.core, + documentType: V2_DOC.maintainer, + data: { repoId: R, memberId: decodeIdentifier(ownerId) }, + }), + ) + } catch (e) { + if (!isDuplicate(e)) throw e + } }) + + // 3. the first config (append-only; one is enough) + await step('config', async () => { + const { documents } = await queryDocumentsWithProof(sdk, repoSource(repo).repoQuery(DOC.config, { limit: 1 })) + if (documents.length > 0) return + add( + await createDocumentIdempotent(sdk, auth, { + contractId: forge.core, + documentType: DOC.config, + data: { repoId: R, defaultBranch: input.defaultBranch ?? 'main', backend: { mode: 0 } }, + }), + ) + }) + + await idbDelete('journal', key) + invalidateMembers(repo, auth.network) + return { repoId, name, actualCredits: spent } } diff --git a/forge-web/lib/sdk/contract-create.ts b/forge-web/lib/sdk/contract-create.ts deleted file mode 100644 index 4480d50c1..000000000 --- a/forge-web/lib/sdk/contract-create.ts +++ /dev/null @@ -1,214 +0,0 @@ -/** - * Repo contract instantiation (createRepo) — the browser port of forge-core `repo.rs::create_repo`. - * - * Publishing a repo creates its per-repo token-bearing data contract (the headline ~1.18 DASH - * cost) with a **CRITICAL** key (S0.7). The committed `repo-v1` template models an *org* repo - * (token admin held by a control group, positions numbered globally); native validation rejects - * both shapes for a solo owner, so two runtime fixes are applied **exactly** as forge-core does — - * this is load-bearing for cross-client interop (a web-created repo must match a CLI-created one): - * - * 1. {@link applySoloOwnerTokenRules} — drop `groups`, re-point every `MainGroup` token-admin - * rule to `ContractOwner`, null out `mainControlGroup` (a 1-member group is rejected). - * 2. {@link normalizeDocumentPositions} — renumber each object level's `position` fields to a - * contiguous `0..N` (native rs-dpp requires top-level positions with no gaps). - * - * The transforms are pure and unit-tested against the bundled template; the publish step then - * hands the fixed contract to the evo-sdk. `DataContract.fromJSON`'s accepted shape is the one - * SDK-interop risk here (see the createRepo note in the task report). - */ - -import type { DataContract, EvoSDK } from '@dashevo/evo-sdk' - -import { SECURITY_LEVEL, WriteAuthError, findSigningKey, type WriteAuth } from './write' -import repoV1Template from './repo-v1-template.json' - -/** A JSON value (the template is manipulated structurally before publish). */ -export type JsonValue = - | null - | boolean - | number - | string - | JsonValue[] - | { [key: string]: JsonValue } - -function isObject(v: JsonValue | undefined): v is { [key: string]: JsonValue } { - return v !== null && v !== undefined && typeof v === 'object' && !Array.isArray(v) -} - -/** - * Re-point a solo-owner repo's token rules: drop the top-level `groups`, replace every - * `MainGroup` action-taker with `ContractOwner`, and null any `mainControlGroup`. Mutates in - * place. Parity with `apply_solo_owner_token_rules` / `repoint_group_rules_to_owner`. - */ -export function applySoloOwnerTokenRules(template: { [key: string]: JsonValue }): void { - delete template['groups'] - const tokens = template['tokens'] - if (isObject(tokens)) { - for (const key of Object.keys(tokens)) { - const token = tokens[key] - if (token !== undefined) repointGroupRulesToOwner(token) - } - } -} - -function repointGroupRulesToOwner(value: JsonValue | undefined): void { - if (Array.isArray(value)) { - for (const item of value) repointGroupRulesToOwner(item) - return - } - if (!isObject(value)) return - for (const key of Object.keys(value)) { - const v = value[key] - if ( - (key === 'authorizedToMakeChange' || key === 'adminActionTakers') && - v === 'MainGroup' - ) { - value[key] = 'ContractOwner' - } else if (key === 'mainControlGroup') { - value[key] = null - } else { - repointGroupRulesToOwner(v) - } - } -} - -/** - * Renumber every document schema's `position` fields to contiguous `0..N` per object level (in - * existing position order), recursing into nested object properties. Mutates in place. Parity - * with `normalize_document_positions` / `renumber_object_positions`. - */ -export function normalizeDocumentPositions(template: { [key: string]: JsonValue }): void { - const schemas = template['documentSchemas'] - if (!isObject(schemas)) return - for (const key of Object.keys(schemas)) { - const schema = schemas[key] - if (schema !== undefined) renumberObjectPositions(schema) - } -} - -function renumberObjectPositions(schema: JsonValue | undefined): void { - if (!isObject(schema)) return - const props = schema['properties'] - if (!isObject(props)) return - const order: Array<{ key: string; pos: number }> = Object.keys(props).map((key) => { - const prop = props[key] - const pos = isObject(prop) && typeof prop['position'] === 'number' ? prop['position'] : 0 - return { key, pos } - }) - order.sort((a, b) => a.pos - b.pos) - order.forEach((entry, newPos) => { - const prop = props[entry.key] - if (isObject(prop)) { - prop['position'] = newPos - renumberObjectPositions(prop) - } - }) -} - -/** Deep-clone the bundled repo-v1 template and apply both runtime fixes. */ -export function buildRepoV1Contract(): { [key: string]: JsonValue } { - const template = structuredClone(repoV1Template) as unknown as { [key: string]: JsonValue } - applySoloOwnerTokenRules(template) - normalizeDocumentPositions(template) - return template -} - -interface IdentitiesNonceFacade { - nonce(identityId: string): Promise - fetch(identityId: string): Promise< - | { - readonly publicKeys: { - keyId: number - purposeNumber: number - securityLevelNumber: number - validatePrivateKey(bytes: Uint8Array, network: string): boolean - }[] - readonly balance: bigint - getPublicKeyById(keyId: number): unknown - } - | undefined - > -} -interface ContractsPublishFacade { - publish(options: unknown): Promise<{ id?: { toString(): string } } | unknown> -} -interface SdkContractCreateFacades { - identities: IdentitiesNonceFacade - contracts: ContractsPublishFacade -} -function facades(sdk: EvoSDK): SdkContractCreateFacades { - return sdk as unknown as SdkContractCreateFacades -} - -const SEQUENCE_MASK = (1n << 40n) - 1n - -/** The result of a repo contract instantiation. */ -export interface CreateRepoContractResult { - readonly contractId: string - /** Approximate DASH cost previewed pre-sign (the exact fee settles at consensus). */ - readonly estimatedDash: number -} - -/** - * Instantiate a repo's per-repo data contract (DataContractCreate) with the acting identity's - * CRITICAL key. Returns the new contract id. This is the expensive create; callers write the - * initial `config` + registry `repoListing` separately (see `repo/writes.ts::finalizeRepo`). - */ -export async function createRepoContract( - sdk: EvoSDK, - auth: WriteAuth, - opts: { readonly version?: number } = {}, -): Promise { - // Dynamic import keeps the evo-sdk WASM out of the initial bundle (loaded on first write). - const { DataContract, IdentitySigner } = await import('@dashevo/evo-sdk') - const template = buildRepoV1Contract() - const ownerId = auth.identityId - template['ownerId'] = ownerId - - const wif = auth.getSigningKeyWif() - const identity = await facades(sdk).identities.fetch(ownerId) - if (!identity) throw new WriteAuthError(`identity ${ownerId} not found`) - const signing = await findSigningKey(identity, wif, auth.network, SECURITY_LEVEL.CRITICAL) - if (!signing) { - throw new WriteAuthError('repo creation requires a CRITICAL AUTHENTICATION key') - } - - const rawNonce = (await facades(sdk).identities.nonce(ownerId)) ?? 0n - const identityNonce = (rawNonce & SEQUENCE_MASK) + 1n - - const platformVersion = opts.version ?? (sdk as unknown as { version(): number }).version() - - // Derive and stamp the deterministic contract id (owner + identity nonce). - const contractIdBytes = ( - DataContract as unknown as { - generateId(ownerId: string, identityNonce: bigint): { toString(): string } - } - ).generateId(ownerId, identityNonce) - const contractId = contractIdBytes.toString() - template['id'] = contractId - - const dataContract = ( - DataContract as unknown as { - fromJSON(value: unknown, fullValidation: boolean, platformVersion: number): DataContract - } - ).fromJSON(template, true, platformVersion) - - const signer = new IdentitySigner() - signer.addKeyFromWif(wif) - - const published = await facades(sdk).contracts.publish({ - dataContract, - identityKey: signing.publicKey, - signer, - }) - - const publishedId = - published !== null && - typeof published === 'object' && - 'id' in published && - (published as { id?: { toString(): string } }).id - ? (published as { id: { toString(): string } }).id.toString() - : contractId - - return { contractId: publishedId, estimatedDash: 1.18 } -} diff --git a/forge-web/lib/sdk/cost.ts b/forge-web/lib/sdk/cost.ts new file mode 100644 index 000000000..5bf8c77e3 --- /dev/null +++ b/forge-web/lib/sdk/cost.ts @@ -0,0 +1,124 @@ +/** + * Write cost estimates — calibrated against measured forge-v2 costs on devnet moutai. + * + * evo-sdk 4.2 has no fee estimator for a document transition, so the preview is a model: + * a per-type base (what the document costs with no text) plus the storage price of its text, + * 27,500 credits per UTF-8 byte (the 27,000 credits/byte storage rate plus the processing that + * grows with it). Both were fitted to balance deltas measured on moutai (protocol 14, + * 2026-09-25): an issue with a 10-byte title cost 57.7M credits, with a 1,000-byte body 85.2M, + * with 4,000 bytes 167.7M; comments 47.6M / 74.3M / 157.2M for 10 / 1,000 / 4,000 bytes. + * The post-write actual (the balance change) is recorded next to each estimate in the spend + * ledger, so drift shows up there (`ux-dx-spec.md` §4 rule 2). + * + * v1 repos (testnet, protocol 13) use the same model; their token-gated types add one + * WRITE/MAINTAIN token, shown separately. + */ + +/** 1 DASH = 1e11 credits (parity with forge-core `credits_to_dash`). */ +export const CREDITS_PER_DASH = 100_000_000_000 + +/** Measured marginal cost of one byte of document text (storage + the processing it adds). */ +export const CREDITS_PER_TEXT_BYTE = 27_500 + +/** + * What a document of each type costs with no text, in credits (moutai balance deltas, text + * contribution subtracted). Types never measured fall back to {@link DEFAULT_BASE_CREDITS}. + */ +export const BASE_CREDITS: Readonly> = { + // forge-core + repo: 55_000_000, + maintainer: 39_300_000, + writer: 38_800_000, + config: 34_000_000, + release: 57_600_000, + label: 45_000_000, + refUpdate: 45_000_000, + protectedRefUpdate: 45_000_000, + // forge-collab + issue: 57_400_000, + patch: 112_000_000, + comment: 47_300_000, + event: 50_000_000, + authorEvent: 56_600_000, + review: 34_900_000, + star: 27_800_000, + follow: 38_400_000, + // v1 registry + repoListing: 60_000_000, +} + +const DEFAULT_BASE_CREDITS = 50_000_000 + +/** + * What deleting a document gives back, in credits (negative = a refund). Measured on moutai: + * unstar +23.3M, unfollow +34.1M, revoking a writer +20.8M. + */ +export const DELETE_CREDITS: Readonly> = { + star: -23_300_000, + follow: -34_100_000, + maintainer: -20_800_000, + writer: -20_800_000, + release: -30_000_000, + label: -25_000_000, + comment: -25_000_000, + review: -20_000_000, +} + +/** The fee a v1 token-admin action (mint / freeze / destroy) is estimated at. */ +export const TOKEN_ADMIN_CREDITS = 15_000_000 + +/** A pre-sign cost preview for the confirm UI. */ +export interface CostPreview { + /** Estimated credits; negative when the action refunds storage. */ + readonly credits: number + readonly dash: number + /** The token spend, when the action is v1 token-gated (1 WRITE/MAINTAIN token), else 0. */ + readonly tokenAmount: number + /** Token position spent (0 WRITE / 1 MAINTAIN), when gated. */ + readonly tokenPosition?: number +} + +/** Credit → DASH (display). */ +export function creditsToDash(credits: number): number { + return credits / CREDITS_PER_DASH +} + +/** A preview for a plain credit amount. */ +export function previewCredits(credits: number): CostPreview { + return { credits, dash: creditsToDash(credits), tokenAmount: 0 } +} + +/** UTF-8 bytes of every string in `data` (the text a document stores beyond its fixed shape). */ +export function textBytes(data: Readonly>): number { + const encoder = new TextEncoder() + let total = 0 + const walk = (v: unknown): void => { + if (typeof v === 'string') total += encoder.encode(v).length + else if (Array.isArray(v)) v.forEach(walk) + else if (v !== null && typeof v === 'object' && !(v instanceof Uint8Array)) Object.values(v).forEach(walk) + } + walk(data) + return total +} + +/** Estimated credits to create one `documentType` document holding `data`. */ +export function estimateCreateCredits(documentType: string, data: Readonly> = {}): number { + return (BASE_CREDITS[documentType] ?? DEFAULT_BASE_CREDITS) + CREDITS_PER_TEXT_BYTE * textBytes(data) +} + +/** Preview for creating one document (no token spend: v2, or an ungated v1 type). */ +export function previewCreate(documentType: string, data: Readonly> = {}): CostPreview { + return previewCredits(estimateCreateCredits(documentType, data)) +} + +/** Preview for deleting one document of `documentType` (usually a refund: negative credits). */ +export function previewDelete(documentType: string): CostPreview { + return previewCredits(DELETE_CREDITS[documentType] ?? -20_000_000) +} + +/** The sum of several previews (a repo creation is three documents). */ +export function sumPreviews(parts: readonly CostPreview[]): CostPreview { + const credits = parts.reduce((s, p) => s + p.credits, 0) + const tokenAmount = parts.reduce((s, p) => s + p.tokenAmount, 0) + return { credits, dash: creditsToDash(credits), tokenAmount } +} diff --git a/forge-web/lib/sdk/index.ts b/forge-web/lib/sdk/index.ts index 7504152e0..085b70b4b 100644 --- a/forge-web/lib/sdk/index.ts +++ b/forge-web/lib/sdk/index.ts @@ -8,27 +8,44 @@ export { evoSdkService, type EvoSdkConfig } from './service' export { - COST_ESTIMATE_CREDITS, - CREDITS_PER_DASH, + ConsensusRefusal, + DUPLICATE_UNIQUE_CODE, + KEY_LIMIT_CODES, REPO_CREATE_GATES, SECURITY_LEVEL, WriteAuthError, + asConsensusRefusal, createDocumentIdempotent, isStaleDocumentIdError, + measureActual, pendingWriteKey, createGateFor, - creditsToDash, deleteDocumentIdempotent, findSigningKey, isAlreadyExistsError, - previewCredits, previewDocumentCreate, readIdentityBalance, - type CostPreview, + type DeleteResult, + type SpendEvent, type TokenGate, type WriteAuth, type WriteResult, } from './write' +export { + BASE_CREDITS, + CREDITS_PER_DASH, + CREDITS_PER_TEXT_BYTE, + DELETE_CREDITS, + TOKEN_ADMIN_CREDITS, + creditsToDash, + estimateCreateCredits, + previewCreate, + previewCredits, + previewDelete, + sumPreviews, + textBytes, + type CostPreview, +} from './cost' export { GRANT_AMOUNT, ROLE_POSITION, @@ -37,14 +54,6 @@ export { suspendRole, type Role, } from './token-admin' -export { - applySoloOwnerTokenRules, - buildRepoV1Contract, - createRepoContract, - normalizeDocumentPositions, - type CreateRepoContractResult, - type JsonValue, -} from './contract-create' export { ascendingEquivalent, base64ToBytes, diff --git a/forge-web/lib/sdk/repo-v1-template.json b/forge-web/lib/sdk/repo-v1-template.json deleted file mode 100644 index 6d4f2439b..000000000 --- a/forge-web/lib/sdk/repo-v1-template.json +++ /dev/null @@ -1,1492 +0,0 @@ -{ - "$formatVersion": "1", - "id": "11111111111111111111111111111111", - "ownerId": "11111111111111111111111111111111", - "version": 1, - "documentSchemas": { - "config": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "defaultBranch": { - "type": "string", - "maxLength": 255, - "position": 0 - }, - "protectedPatterns": { - "type": "string", - "maxLength": 900, - "position": 1, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "backend": { - "type": "object", - "properties": { - "mode": { - "type": "integer", - "position": 2, - "minimum": 0, - "maximum": 4 - }, - "uris": { - "type": "string", - "maxLength": 1300, - "position": 3, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "required": [ - "mode" - ], - "additionalProperties": false, - "position": 4 - }, - "archived": { - "type": "boolean", - "position": 5 - } - }, - "indices": [ - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "defaultBranch", - "$createdAt" - ], - "additionalProperties": false - }, - "refUpdate": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "refNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "refName": { - "type": "string", - "maxLength": 255, - "position": 1 - }, - "newOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "prevOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "force": { - "type": "boolean", - "position": 4 - } - }, - "indices": [ - { - "name": "refState", - "properties": [ - { - "refNameHash": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "reflog", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "pusher", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "refNameHash", - "refName", - "newOid", - "$createdAt" - ], - "additionalProperties": false - }, - "protectedRefUpdate": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "refNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "refName": { - "type": "string", - "maxLength": 255, - "position": 1 - }, - "newOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "prevOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "force": { - "type": "boolean", - "position": 4 - } - }, - "indices": [ - { - "name": "refState", - "properties": [ - { - "refNameHash": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "reflog", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "pusher", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "refNameHash", - "refName", - "newOid", - "$createdAt" - ], - "additionalProperties": false - }, - "packManifest": { - "type": "object", - "documentsMutable": false, - "documentsCountable": true, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "kind": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "sizeBytes": { - "type": "integer", - "position": 2, - "minimum": 0 - }, - "objectCount": { - "type": "integer", - "position": 3, - "minimum": 0 - }, - "chunkCount": { - "type": "integer", - "position": 4, - "minimum": 0 - }, - "storage": { - "type": "integer", - "position": 5, - "minimum": 0, - "maximum": 1 - }, - "uris": { - "type": "string", - "maxLength": 2600, - "position": 6, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "tips": { - "type": "array", - "byteArray": true, - "maxItems": 512, - "position": 7 - }, - "supersedes": { - "type": "array", - "byteArray": true, - "maxItems": 1024, - "position": 8 - }, - "offsetIndexParts": { - "type": "integer", - "position": 9, - "minimum": 0 - } - }, - "indices": [ - { - "name": "packHash", - "properties": [ - { - "packHash": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "kind", - "properties": [ - { - "kind": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "packHash", - "kind", - "sizeBytes", - "objectCount", - "chunkCount", - "storage", - "offsetIndexParts" - ], - "additionalProperties": false - }, - "manifestPart": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "partSeq": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "entries": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 2 - } - }, - "indices": [ - { - "name": "part", - "properties": [ - { - "packHash": "asc" - }, - { - "partSeq": "asc" - } - ], - "unique": true - } - ], - "required": [ - "packHash", - "partSeq", - "entries" - ], - "additionalProperties": false - }, - "chunk": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "packHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "seq": { - "type": "integer", - "position": 1, - "minimum": 0 - }, - "d0": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 2 - }, - "d1": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 3 - }, - "d2": { - "type": "array", - "byteArray": true, - "maxItems": 4900, - "position": 4 - } - }, - "indices": [ - { - "name": "chunk", - "properties": [ - { - "packHash": "asc" - }, - { - "seq": "asc" - } - ], - "unique": true, - "countable": "countable" - } - ], - "required": [ - "packHash", - "seq", - "d0" - ], - "additionalProperties": false - }, - "issue": { - "type": "object", - "documentsKeepHistory": true, - "documentsCountable": true, - "properties": { - "number": { - "type": "integer", - "position": 0, - "minimum": 1 - }, - "title": { - "type": "string", - "maxLength": 256, - "position": 1 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 3 - }, - "createdAt": { - "type": "integer", - "position": 4, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 5 - } - }, - "required": [], - "additionalProperties": false, - "position": 6 - } - }, - "indices": [ - { - "name": "number", - "properties": [ - { - "number": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "owner", - "properties": [ - { - "$ownerId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "number", - "title" - ], - "additionalProperties": false - }, - "patch": { - "type": "object", - "documentsKeepHistory": true, - "documentsCountable": true, - "properties": { - "number": { - "type": "integer", - "position": 0, - "minimum": 1 - }, - "title": { - "type": "string", - "maxLength": 256, - "position": 1 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "baseRefNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 3 - }, - "baseRefName": { - "type": "string", - "maxLength": 255, - "position": 4 - }, - "sourceListingId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 5 - }, - "sourceContractId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 6 - }, - "sourceRefNameHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 7 - }, - "sourceRefName": { - "type": "string", - "maxLength": 255, - "position": 8 - }, - "headOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 9 - }, - "patchManifestHash": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 10 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 11 - }, - "createdAt": { - "type": "integer", - "position": 12, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 13 - } - }, - "required": [], - "additionalProperties": false, - "position": 14 - } - }, - "indices": [ - { - "name": "number", - "properties": [ - { - "number": "asc" - } - ], - "unique": true - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - }, - { - "name": "source", - "properties": [ - { - "sourceListingId": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "number", - "title", - "baseRefNameHash", - "sourceContractId", - "headOid" - ], - "additionalProperties": false - }, - "comment": { - "type": "object", - "documentsKeepHistory": true, - "properties": { - "targetId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 1 - }, - "replyTo": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 2 - }, - "commitOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - }, - "path": { - "type": "string", - "maxLength": 500, - "position": 4 - }, - "line": { - "type": "integer", - "position": 5, - "minimum": 0 - }, - "side": { - "type": "integer", - "position": 6, - "minimum": 0, - "maximum": 1 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 7 - }, - "createdAt": { - "type": "integer", - "position": 8, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 9 - } - }, - "required": [], - "additionalProperties": false, - "position": 10 - } - }, - "indices": [ - { - "name": "target", - "properties": [ - { - "targetId": "asc" - }, - { - "$createdAt": "asc" - } - ], - "countable": "countable" - } - ], - "required": [ - "$createdAt", - "targetId", - "body" - ], - "additionalProperties": false - }, - "event": { - "type": "object", - "documentsMutable": false, - "canBeDeleted": false, - "properties": { - "targetId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "kind": { - "type": "integer", - "position": 1, - "minimum": 1 - }, - "value": { - "type": "string", - "maxLength": 120, - "position": 2 - }, - "oid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 3 - } - }, - "indices": [ - { - "name": "target", - "properties": [ - { - "targetId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "feed", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "targetId", - "kind", - "$createdAt" - ], - "additionalProperties": false - }, - "review": { - "type": "object", - "documentsMutable": false, - "properties": { - "patchId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 0 - }, - "verdict": { - "type": "integer", - "position": 1, - "minimum": 1, - "maximum": 3 - }, - "commitOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 2 - }, - "body": { - "type": "string", - "maxLength": 5120, - "position": 3 - }, - "imported": { - "type": "object", - "properties": { - "author": { - "type": "string", - "maxLength": 120, - "position": 4 - }, - "createdAt": { - "type": "integer", - "position": 5, - "minimum": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 6 - } - }, - "required": [], - "additionalProperties": false, - "position": 7 - } - }, - "indices": [ - { - "name": "patch", - "properties": [ - { - "patchId": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "patchId", - "verdict", - "commitOid" - ], - "additionalProperties": false - }, - "label": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "name": { - "type": "string", - "maxLength": 30, - "position": 0 - }, - "color": { - "type": "string", - "maxLength": 7, - "position": 1 - }, - "description": { - "type": "string", - "maxLength": 200, - "position": 2 - }, - "retired": { - "type": "boolean", - "position": 3 - } - }, - "indices": [ - { - "name": "name", - "properties": [ - { - "name": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "name" - ], - "additionalProperties": false - }, - "release": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "tagName": { - "type": "string", - "maxLength": 63, - "position": 0 - }, - "name": { - "type": "string", - "maxLength": 120, - "position": 1 - }, - "notes": { - "type": "string", - "maxLength": 5120, - "position": 2 - }, - "yanked": { - "type": "boolean", - "position": 3 - }, - "assets": { - "type": "string", - "maxLength": 4096, - "position": 4, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - } - }, - "indices": [ - { - "name": "tag", - "properties": [ - { - "tagName": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "created", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "tagName" - ], - "additionalProperties": false - }, - "checkRun": { - "type": "object", - "documentsMutable": true, - "tokenCost": { - "create": { - "tokenPosition": 0, - "amount": 1 - }, - "delete": { - "tokenPosition": 0, - "amount": 1 - } - }, - "properties": { - "headOid": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 32, - "position": 0 - }, - "name": { - "type": "string", - "maxLength": 100, - "position": 1 - }, - "status": { - "type": "string", - "maxLength": 30, - "position": 2 - }, - "conclusion": { - "type": "string", - "maxLength": 30, - "position": 3 - }, - "detailsUrl": { - "type": "string", - "maxLength": 300, - "position": 4 - }, - "summary": { - "type": "string", - "maxLength": 1000, - "position": 5 - } - }, - "indices": [ - { - "name": "head", - "properties": [ - { - "headOid": "asc" - }, - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "headOid", - "name", - "status" - ], - "additionalProperties": false - }, - "webhook": { - "type": "object", - "documentsMutable": false, - "tokenCost": { - "create": { - "tokenPosition": 1, - "amount": 1 - }, - "delete": { - "tokenPosition": 1, - "amount": 1 - } - }, - "properties": { - "hookId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "position": 0 - }, - "url": { - "type": "string", - "maxLength": 300, - "position": 1 - }, - "events": { - "type": "string", - "maxLength": 600, - "position": 2, - "description": "JSON-encoded array (D1: v1 meta-schema forbids non-byteArray arrays)" - }, - "relayIdentityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier", - "position": 3 - }, - "encryptedSecret": { - "type": "array", - "byteArray": true, - "maxItems": 128, - "position": 4 - }, - "disabled": { - "type": "boolean", - "position": 5 - } - }, - "indices": [ - { - "name": "hook", - "properties": [ - { - "hookId": "asc" - }, - { - "$createdAt": "asc" - } - ] - }, - { - "name": "list", - "properties": [ - { - "$createdAt": "asc" - } - ] - } - ], - "required": [ - "$createdAt", - "hookId", - "url", - "relayIdentityId" - ], - "additionalProperties": false - } - }, - "groups": { - "0": { - "$formatVersion": "0", - "members": { - "11111111111111111111111111111111": 1 - }, - "requiredPower": 1 - } - }, - "tokens": { - "0": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "write", - "pluralForm": "writes" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": 0, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - }, - "1": { - "$formatVersion": "0", - "conventions": { - "$formatVersion": "0", - "localizations": { - "en": { - "$formatVersion": "0", - "shouldCapitalize": true, - "singularForm": "maintain", - "pluralForm": "maintains" - } - }, - "decimals": 0 - }, - "conventionsChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "baseSupply": 1000000000, - "maxSupply": null, - "keepsHistory": { - "$formatVersion": "0", - "keepsTransferHistory": true, - "keepsFreezingHistory": true, - "keepsMintingHistory": true, - "keepsBurningHistory": true, - "keepsDirectPricingHistory": true, - "keepsDirectPurchaseHistory": true - }, - "startAsPaused": false, - "allowTransferToFrozenBalance": true, - "maxSupplyChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "distributionRules": { - "$formatVersion": "0", - "perpetualDistribution": null, - "perpetualDistributionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "preProgrammedDistribution": null, - "newTokensDestinationIdentity": null, - "newTokensDestinationIdentityRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mintingAllowChoosingDestination": true, - "mintingAllowChoosingDestinationRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "changeDirectPurchasePricingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "marketplaceRules": { - "$formatVersion": "0", - "tradeMode": "NotTradeable", - "tradeModeChangeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "ContractOwner", - "adminActionTakers": "ContractOwner", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - } - }, - "manualMintingRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "manualBurningRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "freezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "unfreezeRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "destroyFrozenFundsRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "emergencyActionRules": { - "$formatVersion": "0", - "authorizedToMakeChange": "MainGroup", - "adminActionTakers": "MainGroup", - "changingAuthorizedActionTakersToNoOneAllowed": false, - "changingAdminActionTakersToNoOneAllowed": false, - "selfChangingAdminActionTakersAllowed": false - }, - "mainControlGroup": 0, - "mainControlGroupCanBeModified": "ContractOwner", - "description": null - } - }, - "keywords": [ - "git", - "forge", - "repository" - ], - "description": "Dash Forge per-repository contract (template v1)." -} diff --git a/forge-web/lib/sdk/write.test.ts b/forge-web/lib/sdk/write.test.ts index 2e644e21d..dacf853a0 100644 --- a/forge-web/lib/sdk/write.test.ts +++ b/forge-web/lib/sdk/write.test.ts @@ -2,30 +2,31 @@ * WriteEngine unit tests — network-free parity + encoding checks. * * The token gate table, cost math, base58 identifier encoding, WIF parsing, identity-file - * extraction, and the createRepo template transforms are all deterministic and verified here - * against the same `repo-v1.json` the CLI compiles in, so a drift between the browser and Rust - * write encodings fails CI without needing testnet. + * extraction and the calibrated cost model are deterministic and verified here against the same + * `repo-v1.json` the CLI compiles in, so a drift between the browser and Rust write encodings + * fails CI without needing testnet. */ import { describe, expect, it } from 'vitest' -import repoV1 from './repo-v1-template.json' +import repoV1 from '../../../forge-contracts/templates/repo-v1.json' import { - COST_ESTIMATE_CREDITS, - CREDITS_PER_DASH, REPO_CREATE_GATES, + asConsensusRefusal, createGateFor, - creditsToDash, isStaleDocumentIdError, pendingWriteKey, previewDocumentCreate, } from './write' import { - applySoloOwnerTokenRules, - buildRepoV1Contract, - normalizeDocumentPositions, - type JsonValue, -} from './contract-create' + CREDITS_PER_DASH, + creditsToDash, + estimateCreateCredits, + previewCreate, + previewDelete, + sumPreviews, + textBytes, +} from './cost' import { base58CheckDecode, base58CheckEncode, @@ -80,7 +81,33 @@ describe('cost preview', () => { it('converts credits to DASH at 1e11', () => { expect(CREDITS_PER_DASH).toBe(100_000_000_000) expect(creditsToDash(CREDITS_PER_DASH)).toBe(1) - expect(creditsToDash(COST_ESTIMATE_CREDITS.repoCreate)).toBeCloseTo(1.18, 5) + }) + + it('matches the moutai measurements within 10 %', () => { + // Balance deltas measured on devnet moutai (protocol 14, 2026-09-25). + const measured: [string, Record, number][] = [ + ['issue', { title: 'z'.repeat(10) }, 57_681_940], + ['issue', { title: 'z'.repeat(10), body: 'z'.repeat(1000) }, 85_175_900], + ['issue', { title: 'z'.repeat(10), body: 'z'.repeat(4000) }, 167_691_860], + ['comment', { body: 'c'.repeat(10) }, 47_624_080], + ['comment', { body: 'c'.repeat(4000) }, 157_220_300], + ['star', {}, 27_792_520], + ['maintainer', {}, 39_381_960], + ] + for (const [type, data, actual] of measured) { + const est = estimateCreateCredits(type, data) + expect(Math.abs(est - actual) / actual, `${type} ${textBytes(data)}B`).toBeLessThan(0.1) + } + }) + + it('sums a repo creation (repo + maintainer + config) near 0.0013 DASH', () => { + const total = sumPreviews([previewCreate('repo', { name: 'demo' }), previewCreate('maintainer'), previewCreate('config')]) + expect(total.dash).toBeGreaterThan(0.0012) + expect(total.dash).toBeLessThan(0.0014) + }) + + it('previews deletes of indexOnly types as refunds', () => { + expect(previewDelete('star').credits).toBeLessThan(0) }) it('folds the token spend into a gated create preview', () => { @@ -221,72 +248,6 @@ describe('identity-file parsing', () => { }) }) -// --------------------------------------------------------------------------- -// createRepo template transforms (parity with forge-core repo.rs) -// --------------------------------------------------------------------------- - -function collectPositions(schema: JsonValue): number[][] { - const out: number[][] = [] - const walk = (node: JsonValue): void => { - if (node === null || typeof node !== 'object' || Array.isArray(node)) return - const props = node['properties'] - if (props !== null && typeof props === 'object' && !Array.isArray(props)) { - const positions: number[] = [] - for (const key of Object.keys(props)) { - const prop = props[key] - if (prop !== null && typeof prop === 'object' && !Array.isArray(prop) && typeof prop['position'] === 'number') { - positions.push(prop['position']) - } - if (prop !== undefined) walk(prop) - } - out.push(positions.slice().sort((a, b) => a - b)) - } - } - walk(schema) - return out -} - -function findMainGroup(node: JsonValue): boolean { - if (node === 'MainGroup') return true - if (Array.isArray(node)) return node.some(findMainGroup) - if (node !== null && typeof node === 'object') { - return Object.values(node).some((v) => findMainGroup(v)) - } - return false -} - -describe('createRepo template transforms', () => { - it('drops the group, re-points MainGroup rules to the owner', () => { - const template = structuredClone(repoV1) as unknown as { [k: string]: JsonValue } - // The committed template targets an org repo (has groups + MainGroup rules). - expect(template['groups']).toBeDefined() - applySoloOwnerTokenRules(template) - expect(template['groups']).toBeUndefined() - expect(findMainGroup(template['tokens'] as JsonValue)).toBe(false) - }) - - it('renumbers every object level to contiguous 0..N positions', () => { - const template = structuredClone(repoV1) as unknown as { [k: string]: JsonValue } - normalizeDocumentPositions(template) - const schemas = template['documentSchemas'] as { [k: string]: JsonValue } - for (const name of Object.keys(schemas)) { - const schema = schemas[name] - if (schema === undefined) continue - for (const positions of collectPositions(schema)) { - const expected = positions.map((_, i) => i) - expect(positions, `${name} positions must be contiguous`).toEqual(expected) - } - } - }) - - it('buildRepoV1Contract applies both fixes without mutating the import', () => { - const built = buildRepoV1Contract() - expect(built['groups']).toBeUndefined() - // The shared import must be untouched (structuredClone isolation). - expect((repoV1 as { groups?: unknown }).groups).toBeDefined() - }) -}) - // --------------------------------------------------------------------------- // misc encoding helpers // --------------------------------------------------------------------------- @@ -324,6 +285,14 @@ describe('pending-write cache key', () => { }) }) +describe('consensus refusal classification', () => { + it('reads the numeric code a wasm error carries', () => { + expect(asConsensusRefusal({ code: 40105, message: 'duplicate unique properties' })?.code).toBe(40105) + expect(asConsensusRefusal({ code: -1, message: 'snapshot' })).toBeNull() + expect(asConsensusRefusal(new Error('fetch failed'))).toBeNull() + }) +}) + describe('stale document id classification', () => { it('recognizes the consensus refusal of an id derived at another protocol version', () => { expect(isStaleDocumentIdError(new Error('Invalid document transition id abc, expected def'))).toBe(true) diff --git a/forge-web/lib/sdk/write.ts b/forge-web/lib/sdk/write.ts index 7acf502a6..4d83f4efe 100644 --- a/forge-web/lib/sdk/write.ts +++ b/forge-web/lib/sdk/write.ts @@ -5,10 +5,12 @@ * findings and forge-core's on-chain doc encoding: * * - **Manual ST assembly** (not `documents.create`): build `Document` → `DocumentCreateTransition` - * → `BatchedTransition` → `BatchTransition` → `StateTransition`, set the nonce, sign, and - * **broadcast-only** (`broadcastStateTransition`). `waitForResponse` / `broadcastAndWait` - * panic under Node/WASM (`time not implemented`, S0.3), so confirmation is a **documents.get - * poll**, exactly the broadcast+poll model the spike froze. + * → `BatchedTransition` → `BatchTransition` → `StateTransition`, set the nonce, sign, + * broadcast, then `waitForResponse` for the verdict (evo-sdk 4.2: it returns a proven + * result, or the consensus error with its code). A wait that fails for transport reasons + * falls back to a **documents.get poll**, the broadcast+poll model of the S0.3 spike. + * - **Deletes** go through the SDK's delete builder, which emits an `indexOnlyDelete` + * carrying the document's values for `indexOnly` types (star, follow). * - **DIP-30 nonce masking**: the identity-contract nonce carries a 24-bit missing-revision * bitset in its high bits; mask to the low 40 before incrementing or the write desyncs. * - **Idempotent retry**: the signed ST bytes are cached (localStorage) keyed by the @@ -33,6 +35,9 @@ import { bytesToHex } from '@noble/hashes/utils.js' import type { Network } from '../constants' import { base58Encode } from '../auth/base58' +import { previewCreate, previewDelete, type CostPreview } from './cost' + +export type { CostPreview } from './cost' // --------------------------------------------------------------------------- // Signing-key selection (via the WASM SDK — no separate secp256k1 dependency) @@ -55,6 +60,8 @@ interface WasmPublicKey { readonly keyId: number readonly purposeNumber: number readonly securityLevelNumber: number + readonly disabledAt?: bigint + readonly expiresAt?: bigint validatePrivateKey(privateKeyBytes: Uint8Array, network: string): boolean } interface WasmIdentity { @@ -71,6 +78,7 @@ interface DocumentsFacadeLike { } interface StateTransitionsFacadeLike { broadcastStateTransition(st: StateTransition): Promise + waitForResponse(st: StateTransition): Promise } interface SdkFacades { identities: IdentitiesFacadeLike @@ -98,6 +106,10 @@ export async function findSigningKey( const pkBytes = PrivateKey.fromWIF(wif).toBytes() for (const key of identity.publicKeys) { if (key.purposeNumber !== PURPOSE_AUTHENTICATION) continue + // A disabled or expired key would be refused at signature validation; skip it so a + // stale session reports "no usable key" instead of an opaque consensus error. + if (key.disabledAt !== undefined) continue + if (key.expiresAt !== undefined && key.expiresAt <= BigInt(Date.now())) continue let matches = false try { matches = key.validatePrivateKey(pkBytes, network) @@ -150,57 +162,26 @@ export function createGateFor(documentType: string): TokenGate | undefined { } // --------------------------------------------------------------------------- -// Cost preview (DASH) — heuristic pre-sign estimate for the confirm UI +// Cost preview — the calibrated model lives in `./cost` // --------------------------------------------------------------------------- -/** 1 DASH = 1e11 credits (parity with forge-core `credits_to_dash`). */ -export const CREDITS_PER_DASH = 100_000_000_000 - -/** Credit → DASH (display). */ -export function creditsToDash(credits: number): number { - return credits / CREDITS_PER_DASH -} - /** - * Heuristic pre-sign credit estimates per write kind. Document writes are order-of-magnitude - * (processing + storage); the repo contract-create figures come from the S0.7 measurement - * (~0.24 DASH for a token contract) and the repo-v1 template's larger footprint (~1.18 DASH). - * These drive the confirm dialog's "≈ Ð" preview; the exact fee settles at consensus. + * The preview for a v1 repo-contract document create: the calibrated estimate plus the + * WRITE/MAINTAIN token its type spends, if gated. forge-v2 types spend no tokens; their + * previews come from {@link previewCreate} directly. */ -export const COST_ESTIMATE_CREDITS = { - documentCreate: 20_000_000, - documentDelete: 2_000_000, - tokenAdmin: 15_000_000, - repoCreate: 118_000_000_000, -} as const - -/** A pre-sign cost preview for the confirm UI. */ -export interface CostPreview { - readonly credits: number - readonly dash: number - /** The token spend, when the action is token-gated (1 WRITE/MAINTAIN token), else 0. */ - readonly tokenAmount: number - /** Token position spent (0 WRITE / 1 MAINTAIN), when gated. */ - readonly tokenPosition?: number -} - -/** Build the cost preview for a repo document create (folds in any token gate). */ -export function previewDocumentCreate(documentType: string): CostPreview { +export function previewDocumentCreate( + documentType: string, + data: Readonly> = {}, +): CostPreview { const gate = createGateFor(documentType) - const credits = COST_ESTIMATE_CREDITS.documentCreate return { - credits, - dash: creditsToDash(credits), + ...previewCreate(documentType, data), tokenAmount: gate?.amount ?? 0, ...(gate ? { tokenPosition: gate.position } : {}), } } -/** Cost preview for a plain (untyped-cost) credit amount. */ -export function previewCredits(credits: number): CostPreview { - return { credits, dash: creditsToDash(credits), tokenAmount: 0 } -} - // --------------------------------------------------------------------------- // Signed-ST idempotency cache (localStorage; keyed by the logical write) // --------------------------------------------------------------------------- @@ -343,25 +324,136 @@ export class WriteAuthError extends Error { } } +/** + * Platform refused the write with a consensus error: the transition was checked and rejected + * (a duplicate unique index, a membership gate, a spent key). `code` is the consensus error + * code (`40105` duplicate unique properties, `40120` gate not satisfied, ...). + */ +export class ConsensusRefusal extends Error { + constructor( + readonly code: number, + message: string, + ) { + super(message) + this.name = 'ConsensusRefusal' + } +} + +/** Consensus codes for "this key may not spend": budget exhausted/exceeded, key expired. */ +export const KEY_LIMIT_CODES: ReadonlySet = new Set([20015, 20016, 40218]) + +/** Duplicate unique properties: someone already holds the unique slot (an issue number). */ +export const DUPLICATE_UNIQUE_CODE = 40105 + +/** The numeric consensus code a wasm error carries, if any. */ +function consensusCodeOf(e: unknown): number | null { + if (e === null || typeof e !== 'object') return null + try { + const code = (e as { code?: unknown }).code + if (typeof code === 'number' && code >= 10000 && code < 50000) return code + } catch { + /* freed wasm pointer */ + } + return null +} + +/** The consensus refusal `e` is, or null when it is transport noise or unclassified. */ +export function asConsensusRefusal(e: unknown): ConsensusRefusal | null { + if (e instanceof ConsensusRefusal) return e + const code = consensusCodeOf(e) + return code === null ? null : new ConsensusRefusal(code, errorMessage(e)) +} + +/** + * The SDK proves an indexOnly write (star, follow) by the state it affected, not by the + * transition, and says so by rejecting the strict wait with this message. The write landed. + */ +function isAffectedStateSnapshot(e: unknown): boolean { + return errorMessage(e).includes('VerifiedDocuments snapshot') +} + +/** + * Wait for Platform's verdict on a broadcast transition: `'landed'` once proven, a thrown + * {@link ConsensusRefusal} when consensus rejected it, `'unknown'` when the wait itself failed + * (timeout, transport) — the caller then polls for the document instead. + */ +async function awaitOutcome(sdk: EvoSDK, st: StateTransition): Promise<'landed' | 'unknown'> { + try { + await facades(sdk).stateTransitions.waitForResponse(st) + return 'landed' + } catch (e) { + if (isAffectedStateSnapshot(e)) return 'landed' + const refusal = asConsensusRefusal(e) + if (refusal !== null) throw refusal + return 'unknown' + } +} + +/** Read a balance until it moves off `before` (a write's fee settles a block later). */ +async function balanceAfter(sdk: EvoSDK, identityId: string, before: bigint): Promise { + for (let i = 0; i < 8; i++) { + try { + const now = (await facades(sdk).identities.fetch(identityId))?.balance + if (now !== undefined && now !== before) return now + } catch { + /* transient read failure: try again */ + } + await new Promise((r) => setTimeout(r, 1000)) + } + return null +} + +/** The credits a write took (negative: refunded), from the balance on each side of it. */ +export async function measureActual(sdk: EvoSDK, identityId: string, before: bigint | null): Promise { + if (before === null) return null + const after = await balanceAfter(sdk, identityId, before) + return after === null ? null : Number(before - after) +} + // --------------------------------------------------------------------------- // The write context (who is acting; how to reach their key — never React state) // --------------------------------------------------------------------------- +/** One broadcast write, as the spend ledger records it. */ +export interface SpendEvent { + readonly identityId: string + readonly network: Network + /** `create:issue`, `delete:star`, … */ + readonly kind: string + /** The repo the write belongs to (base58 `repoId` / v1 contract id), when it has one. */ + readonly repo: string | null + readonly documentId: string + readonly estimateCredits: number + /** The balance change the write caused, or null when it could not be read in time. */ + readonly actualCredits: number | null +} + /** Identifies the acting identity and yields its signing key (WIF) on demand. */ export interface WriteAuth { readonly identityId: string readonly network: Network /** Return the acting identity's signing-key WIF, or throw {@link WriteAuthError}. */ getSigningKeyWif(): string + /** Told about every write that landed (the local spend ledger listens here). */ + readonly onSpend?: (event: SpendEvent) => void } /** The outcome of an idempotent write. */ export interface WriteResult { readonly documentId: string - /** True once the document is query-visible on Platform (poll confirmed). */ + /** True once Platform proved the write (or the document became query-visible). */ readonly confirmed: boolean - /** The pre-sign cost preview shown to the user. */ + /** The pre-sign estimate shown to the user. */ readonly cost: CostPreview + /** What the write actually took from the balance (credits; negative = refund), if read. */ + readonly actualCredits: number | null +} + +/** The repo a write's data names (`repoId` bytes), for the ledger. */ +function repoOf(data: Readonly>, contractId: string): string | null { + const repoId = data['repoId'] + if (repoId instanceof Uint8Array && repoId.length === 32) return base58Encode(repoId) + return contractId } async function documentExists( @@ -450,12 +542,17 @@ export function documentForCreate( } /** - * Create a document with idempotent retry. Builds + signs a broadcast-only state transition, - * caches the signed bytes keyed by the logical write ({@link pendingWriteKey}: owner, contract, - * type and data), broadcasts, and polls for confirmation. A retry of the same write while a + * Create a document with idempotent retry. Builds + signs a state transition, caches the + * signed bytes keyed by the logical write ({@link pendingWriteKey}: owner, contract, type and + * data), broadcasts, and waits for Platform's verdict. A retry of the same write while a * cached transition is pending re-broadcasts those exact bytes (same nonce and id, so it can - * land at most once) instead of signing a second document. An already-processed error, or the - * doc appearing on a poll, resolves as success. + * land at most once) instead of signing a second document. + * + * The verdict: a proven result resolves `confirmed`; a consensus refusal (a duplicate issue + * number, a membership gate, a spent key) throws {@link ConsensusRefusal} with its code, so + * callers can retry the ones they understand; a wait that fails for transport reasons falls + * back to polling for the document (or `probe`, for indexOnly types that have no document to + * fetch by id). * * If the network refuses the create because its id was derived at a stale protocol version * (a 13 -> 14 upgrade under an open tab), the version is re-read with a proved query and the @@ -475,23 +572,48 @@ export async function createDocumentIdempotent( readonly gate?: TokenGate | null readonly requiredLevel?: number readonly confirmTimeoutMs?: number + /** Whether the write landed, for types `documents.get` cannot fetch (indexOnly). */ + readonly probe?: () => Promise }, ): Promise { const { contractId, documentType, data } = params const requiredLevel = params.requiredLevel ?? SECURITY_LEVEL.HIGH const confirmTimeoutMs = params.confirmTimeoutMs ?? 30_000 const gate = params.gate === undefined ? createGateFor(documentType) : params.gate ?? undefined - const cost = previewDocumentCreate(documentType) + const cost = previewDocumentCreate(documentType, data) + const landed = (documentId: string, timeoutMs: number): Promise => + params.probe + ? pollUntil(params.probe, timeoutMs) + : pollForDocument(sdk, contractId, documentType, documentId, timeoutMs) const wif = auth.getSigningKeyWif() const ownerId = auth.identityId const cacheKey = pendingWriteKey(ownerId, contractId, documentType, data) + const identity = await facades(sdk).identities.fetch(ownerId) + if (!identity) throw new WriteAuthError(`identity ${ownerId} not found on ${auth.network}`) + const balanceBefore = identity.balance + + const finish = async (documentId: string, confirmed: boolean): Promise => { + const actualCredits = confirmed ? await measureActual(sdk, ownerId, balanceBefore) : null + if (confirmed) { + auth.onSpend?.({ + identityId: ownerId, + network: auth.network, + kind: `create:${documentType}`, + repo: repoOf(data, contractId), + documentId, + estimateCredits: cost.credits, + actualCredits, + }) + } + return { documentId, confirmed, cost, actualCredits } + } // A previous attempt at this same write timed out: finish it, never sign a second one. const cached = loadPendingST(cacheKey) if (cached) { const { documentId } = cached - if (!(await documentExists(sdk, contractId, documentType, documentId))) { + if (!(await landed(documentId, 0))) { const { StateTransition: StateTransitionClass } = await import('@dashevo/evo-sdk') try { await facades(sdk).stateTransitions.broadcastStateTransition( @@ -499,23 +621,24 @@ export async function createDocumentIdempotent( ) } catch (e) { // Already processed / nonce consumed: the poll below decides whether it landed. - if (!isAlreadyExistsError(e)) throw e + if (!isAlreadyExistsError(e)) { + clearPendingST(cacheKey) + throw asConsensusRefusal(e) ?? e + } } } - const confirmed = await pollForDocument(sdk, contractId, documentType, documentId, confirmTimeoutMs) + const confirmed = await landed(documentId, confirmTimeoutMs) // One re-broadcast per cached transition. If it still has not landed (its nonce was // overtaken, say), drop it so the next attempt signs afresh rather than re-polling a // write that cannot land until the entry expires. clearPendingST(cacheKey) - return { documentId, confirmed, cost } + return finish(documentId, confirmed) } - const identity = await facades(sdk).identities.fetch(ownerId) - if (!identity) throw new WriteAuthError(`identity ${ownerId} not found on ${auth.network}`) const signing = await findSigningKey(identity, wif, auth.network, requiredLevel) if (!signing) { throw new WriteAuthError( - 'no matching AUTHENTICATION key for the stored signing key at the required security level', + 'no usable AUTHENTICATION key for the stored signing key (it may be disabled or expired)', ) } @@ -528,13 +651,13 @@ export async function createDocumentIdempotent( await facades(sdk).stateTransitions.broadcastStateTransition(signed.st) } catch (e) { if (isAlreadyExistsError(e)) { - const confirmed = await pollForDocument(sdk, contractId, documentType, signed.documentId, 5_000) + const confirmed = await landed(signed.documentId, 5_000) clearPendingST(cacheKey) - return { documentId: signed.documentId, confirmed, cost } + return finish(signed.documentId, confirmed) } if (!isStaleDocumentIdError(e)) { clearPendingST(cacheKey) - throw e + throw asConsensusRefusal(e) ?? e } // Refused at basic validation (nothing landed): learn the network's version from a // proved read and prepare the write once more. @@ -546,15 +669,37 @@ export async function createDocumentIdempotent( } catch (e2) { if (!isAlreadyExistsError(e2)) { clearPendingST(cacheKey) - throw e2 + throw asConsensusRefusal(e2) ?? e2 } } } const { documentId } = signed - const confirmed = await pollForDocument(sdk, contractId, documentType, documentId, confirmTimeoutMs) + let outcome: 'landed' | 'unknown' + try { + outcome = await awaitOutcome(sdk, signed.st) + } catch (refusal) { + // Consensus checked the transition and refused it: nothing will land under this nonce. + clearPendingST(cacheKey) + throw refusal + } + const confirmed = outcome === 'landed' || (await landed(documentId, confirmTimeoutMs)) if (confirmed) clearPendingST(cacheKey) - return { documentId, confirmed, cost } + return finish(documentId, confirmed) +} + +/** Poll `check` until it holds or the budget elapses (one immediate check). */ +async function pollUntil(check: () => Promise, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs + for (;;) { + try { + if (await check()) return true + } catch { + /* a failed read is "not yet" */ + } + if (Date.now() >= deadline) return false + await new Promise((r) => setTimeout(r, 1500)) + } } /** Consensus refused a create because its id was derived at another protocol version. */ @@ -640,10 +785,31 @@ async function signCreate( return { st, bytes: st.toBytes(), documentId } } +/** The outcome of a delete. */ +export interface DeleteResult { + /** True once the document is gone (proven, or no longer found). */ + readonly deleted: boolean + /** What the delete gave back (negative credits) or took, if the balance could be read. */ + readonly actualCredits: number | null +} + +interface DocumentsDeleteFacadeLike { + delete(options: { document: unknown; identityKey: unknown; signer: unknown }): Promise +} + /** - * Delete a document (broadcast-only, idempotent). Fetches the live `Document`, wraps it in a - * `DocumentDeleteTransition`, signs, broadcasts, and polls for its disappearance. If the doc - * is already gone this resolves as a no-op success. Used by unstar / unfollow. + * Delete one of the signer's own documents through the SDK's delete builder, which picks the + * transition kind from the document type: a stored document is deleted by id; an `indexOnly` + * one (`star`, `follow`) has no stored row, so its delete must carry the document's values, + * and Drive checks them against the committed index entry (`indexOnlyDelete`, protocol 14). + * + * - Stored types: pass `documentId`; the live document is checked first and a delete of a + * document already gone resolves as a no-op success. + * - indexOnly types: pass `document`, the wasm `Document` a query returned (its values are the + * delete), and `probeGone` to confirm it disappeared. + * + * A consensus refusal throws {@link ConsensusRefusal}; a proven outcome (or the document + * gone on a poll) resolves `deleted`. */ export async function deleteDocumentIdempotent( sdk: EvoSDK, @@ -652,51 +818,64 @@ export async function deleteDocumentIdempotent( readonly contractId: string readonly documentType: string readonly documentId: string - readonly gate?: TokenGate | null + /** The wasm `Document` to delete by its values (indexOnly types). */ + readonly document?: unknown + /** Whether the document is gone, for types `documents.get` cannot fetch (indexOnly). */ + readonly probeGone?: () => Promise readonly requiredLevel?: number readonly confirmTimeoutMs?: number }, -): Promise<{ deleted: boolean }> { +): Promise { const { contractId, documentType, documentId } = params const requiredLevel = params.requiredLevel ?? SECURITY_LEVEL.HIGH const confirmTimeoutMs = params.confirmTimeoutMs ?? 30_000 + const gone = params.probeGone ?? (async () => !(await documentExists(sdk, contractId, documentType, documentId))) - const live = await facades(sdk).documents.get(contractId, documentType, documentId) - if (live === undefined || live === null) return { deleted: true } + if (params.document === undefined && (await gone())) return { deleted: true, actualCredits: 0 } const wif = auth.getSigningKeyWif() const ownerId = auth.identityId const identity = await facades(sdk).identities.fetch(ownerId) if (!identity) throw new WriteAuthError(`identity ${ownerId} not found on ${auth.network}`) const signing = await findSigningKey(identity, wif, auth.network, requiredLevel) - if (!signing) throw new WriteAuthError('no matching signing key for delete') - - const { DocumentDeleteTransition, BatchedTransition, BatchTransition, PrivateKey } = - await import('@dashevo/evo-sdk') - const nonce = await nextContractNonce(sdk, ownerId, contractId) - const deleteTransition = new DocumentDeleteTransition({ - document: live as ConstructorParameters[0]['document'], - identityContractNonce: nonce, - }) - const batched = new BatchedTransition(deleteTransition.toDocumentTransition()) - const batch = BatchTransition.fromBatchedTransitions([batched], ownerId, 0) - const st = batch.toStateTransition() - st.setIdentityContractNonce(nonce) - const privateKey = PrivateKey.fromWIF(wif) - st.sign(privateKey, signing.publicKey as Parameters[1]) + if (!signing) { + throw new WriteAuthError('no usable AUTHENTICATION key for the stored signing key (it may be disabled or expired)') + } + const { IdentitySigner } = await import('@dashevo/evo-sdk') + const signer = new IdentitySigner() + signer.addKeyFromWif(wif) + const document = params.document ?? { id: documentId, ownerId, dataContractId: contractId, documentTypeName: documentType } + let proven = false try { - await facades(sdk).stateTransitions.broadcastStateTransition(st) + await (sdk as unknown as { documents: DocumentsDeleteFacadeLike }).documents.delete({ + document, + identityKey: signing.publicKey, + signer, + }) + proven = true } catch (e) { - if (!isAlreadyExistsError(e)) throw e + if (isAffectedStateSnapshot(e)) proven = true + else { + const refusal = asConsensusRefusal(e) + if (refusal !== null) throw refusal + if (!isAlreadyExistsError(e)) throw e + } } - - const deadline = Date.now() + confirmTimeoutMs - for (;;) { - if (!(await documentExists(sdk, contractId, documentType, documentId))) return { deleted: true } - if (Date.now() >= deadline) return { deleted: false } - await new Promise((r) => setTimeout(r, 1500)) + const deleted = proven || (await pollUntil(gone, confirmTimeoutMs)) + const actualCredits = deleted ? await measureActual(sdk, ownerId, identity.balance) : null + if (deleted) { + auth.onSpend?.({ + identityId: ownerId, + network: auth.network, + kind: `delete:${documentType}`, + repo: null, + documentId, + estimateCredits: previewDelete(documentType).credits, + actualCredits, + }) } + return { deleted, actualCredits } } /** Read an identity's credit balance (for the auth surface / cost affordability checks). */ diff --git a/forge-web/lib/spend.ts b/forge-web/lib/spend.ts new file mode 100644 index 000000000..51c5b0f91 --- /dev/null +++ b/forge-web/lib/spend.ts @@ -0,0 +1,116 @@ +/** + * The local spend ledger (`ux-dx-spec.md` §4 rule 3): one row per broadcast write — estimate, + * actual balance change, repo and kind — kept in IndexedDB on this device only. + * + * Settings → Spend reads it back as month / all-time totals by repo, flags estimates that + * missed by more than 25 % (how estimate drift gets noticed), and reconciles the ledger + * against the identity's balance change since the ledger's first row. + */ + +import type { Network } from './constants' +import { idbEntries, idbGet, idbPut } from './idb' +import type { SpendEvent } from './sdk/write' + +/** A ledger row. */ +export interface SpendRow extends SpendEvent { + readonly at: number +} + +/** A ledger's starting point: the balance before its first recorded write. */ +interface Baseline { + readonly at: number + readonly balanceCredits: string +} + +function prefix(network: Network, identityId: string): string { + return `spend:${network}:${identityId}:` +} + +function baselineKey(network: Network, identityId: string): string { + return `baseline:${network}:${identityId}` +} + +/** + * Record a write. `balanceAfter` (credits, read after the write) seeds the reconciliation + * baseline the first time a ledger for this identity is written: the balance before its first + * write is `balanceAfter` plus what that write took. + */ +export async function recordSpend(event: SpendEvent, balanceAfter: bigint | null): Promise { + const at = Date.now() + const row: SpendRow = { ...event, at } + const key = `${prefix(event.network, event.identityId)}${String(at).padStart(15, '0')}:${event.documentId}` + await idbPut('spend', key, row) + const bk = baselineKey(event.network, event.identityId) + if (balanceAfter !== null && (await idbGet('spend', bk)) === undefined) { + const before = balanceAfter + BigInt(event.actualCredits ?? event.estimateCredits) + await idbPut('spend', bk, { at, balanceCredits: before.toString() }) + } +} + +/** Every row of an identity's ledger, oldest first. */ +export async function readLedger(network: Network, identityId: string): Promise { + const rows = await idbEntries('spend', prefix(network, identityId)) + return rows.map(([, v]) => v).sort((a, b) => a.at - b.at) +} + +/** The ledger's baseline balance (credits), or null before the first write. */ +export async function readBaseline(network: Network, identityId: string): Promise<{ at: number; credits: bigint } | null> { + const b = await idbGet('spend', baselineKey(network, identityId)) + return b === undefined ? null : { at: b.at, credits: BigInt(b.balanceCredits) } +} + +/** An estimate that missed its actual by more than a quarter (`ux-dx-spec.md` §4 rule 2). */ +export function estimateMissed(row: Pick): boolean { + if (row.actualCredits === null || row.estimateCredits === 0) return false + return Math.abs(row.actualCredits - row.estimateCredits) > Math.abs(row.estimateCredits) * 0.25 +} + +/** Totals by repo (credits; the credits a row took, refunds negative). */ +export interface SpendSummary { + readonly allTime: number + readonly thisMonth: number + readonly byRepo: ReadonlyArray<{ readonly repo: string; readonly credits: number; readonly writes: number }> + readonly missed: number +} + +/** Summarize a ledger. A row with no measured actual counts at its estimate. */ +export function summarize(rows: readonly SpendRow[], now = Date.now()): SpendSummary { + const month = new Date(now) + const monthStart = new Date(month.getFullYear(), month.getMonth(), 1).getTime() + const byRepo = new Map() + let allTime = 0 + let thisMonth = 0 + let missed = 0 + for (const r of rows) { + const credits = r.actualCredits ?? r.estimateCredits + allTime += credits + if (r.at >= monthStart) thisMonth += credits + if (estimateMissed(r)) missed += 1 + const key = r.repo ?? '(no repo)' + const e = byRepo.get(key) ?? { credits: 0, writes: 0 } + byRepo.set(key, { credits: e.credits + credits, writes: e.writes + 1 }) + } + return { + allTime, + thisMonth, + missed, + byRepo: [...byRepo.entries()] + .map(([repo, v]) => ({ repo, ...v })) + .sort((a, b) => b.credits - a.credits), + } +} + +/** + * The reconciliation line: what the ledger explains vs what the balance actually moved since + * the ledger began. Positive `unexplained` = spent elsewhere (another app or key); negative = + * credited (a top-up). + */ +export function reconcile( + ledgerCredits: number, + baseline: bigint | null, + currentBalance: bigint | null, +): { balanceChange: number; unexplained: number } | null { + if (baseline === null || currentBalance === null) return null + const balanceChange = Number(baseline - currentBalance) + return { balanceChange, unexplained: balanceChange - ledgerCredits } +} From c6fdaf37e114a39e3b9d245bd8cf9a1a9c4285b4 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 10:27:26 -0500 Subject: [PATCH 2/9] feat(web): enable forge-v2 writes in the UI New repo (three documents, step list, resumable from the IndexedDB journal), members add/remove for the owner, issue create with the numbering retry message, comments, author close/reopen via authorEvent, member close/reopen and labels, PR reviews and merge marks, v2 star/unstar and follow/unfollow. Every signing button shows a calibrated cost first and checks both budgets; confirmed writes toast their actual cost and land in the spend ledger. The empty repo shows the push commands. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/app/new/page.tsx | 204 +++++++++++------- forge-web/components/confirm-dialog.tsx | 69 +++--- forge-web/components/profile-content.tsx | 16 +- forge-web/components/repo/issue-content.tsx | 176 ++++++++++----- forge-web/components/repo/issues-content.tsx | 40 ++-- forge-web/components/repo/pull-content.tsx | 117 +++++++--- forge-web/components/repo/repo-header.tsx | 15 +- .../components/repo/repo-home-content.tsx | 53 ++++- .../components/repo/settings-content.tsx | 107 ++++++++- forge-web/components/repo/star-button.tsx | 52 +++-- forge-web/components/repo/v2-writes-note.tsx | 18 -- forge-web/components/ui/copy-row.tsx | 37 ++++ forge-web/components/ui/cost-preview.tsx | 30 +-- forge-web/components/ui/toaster.tsx | 46 ++++ forge-web/contexts/auth-context.tsx | 89 ++++++-- forge-web/hooks/use-toasts.ts | 40 ++++ forge-web/hooks/use-ui-store.ts | 16 +- forge-web/hooks/use-write-guard.ts | 56 +++++ forge-web/lib/auth/controller.ts | 3 + forge-web/lib/view/funds.ts | 63 ++++++ 20 files changed, 923 insertions(+), 324 deletions(-) delete mode 100644 forge-web/components/repo/v2-writes-note.tsx create mode 100644 forge-web/components/ui/copy-row.tsx create mode 100644 forge-web/components/ui/toaster.tsx create mode 100644 forge-web/hooks/use-toasts.ts create mode 100644 forge-web/hooks/use-write-guard.ts create mode 100644 forge-web/lib/view/funds.ts diff --git a/forge-web/app/new/page.tsx b/forge-web/app/new/page.tsx index e0946bd8b..3b5f8321e 100644 --- a/forge-web/app/new/page.tsx +++ b/forge-web/app/new/page.tsx @@ -1,81 +1,110 @@ 'use client' /** - * `/new` — create a repository. Instantiates the per-repo token contract (~1.18 DASH, - * CRITICAL key) + initial config + registry listing. The 1.18 DASH cost is previewed and - * confirmed before signing; on success we jump to the new repo home. + * `/new` — create a forge-v2 repository: three documents in forge-core (the `repo`, the + * owner's `maintainer`, the first `config`), about 0.0013 DASH. The cost is previewed before + * signing; the steps run one by one and are journaled in IndexedDB, so a closed tab offers + * "Finish creating " on the next visit instead of leaving a half-made repo. On success + * the repo's empty state shows the push commands (`ux-dx-spec.md` §5.5). + * + * On a network without forge-v2 (testnet today) repos are not created from the browser: a v1 + * repo was its own ~1.18 DASH contract, and that path is gone. */ -import { useMemo, useState } from 'react' +import { useEffect, useMemo, useState } from 'react' import { useRouter } from 'next/navigation' -import { GitBranch, Hammer, Lock, Terminal } from 'lucide-react' +import { Check, GitBranch, Hammer, Loader2, Lock, Terminal } from 'lucide-react' import { AppShell } from '@/components/app-shell' import { Button } from '@/components/ui/button' import { Field, Input, Textarea } from '@/components/ui/input' import { CostPreview } from '@/components/ui/cost-preview' import { ConfirmDialog } from '@/components/confirm-dialog' import { EmptyState } from '@/components/ui/states' -import { NotDeployedState, isRegistryDeployed, isV2Deployed } from '@/components/ui/network-badge' -import { ACTIVE_NETWORK } from '@/lib/constants' +import { NotDeployedState, isV2Deployed } from '@/components/ui/network-badge' +import { ACTIVE_NETWORK, DEFAULT_NETWORK } from '@/lib/constants' import { useAuth } from '@/contexts/auth-context' import { useUiStore } from '@/hooks/use-ui-store' import { useSdk } from '@/hooks/use-sdk' -import { createRepo, normalizeRepoName } from '@/lib/repo' -import { previewCredits, COST_ESTIMATE_CREDITS } from '@/lib/sdk' - -// The mode is recorded in the repo config. It does not yet route pushes: `git push` stores -// packs on Platform whatever this says (roadmap gap 3), and only `dg repack` / `dg reseed` -// move them — so the hints describe the preference, not where bytes will land. -const BACKENDS = [ - { mode: 0, label: '⛓ platform', hint: 'Packs stored on Dash Platform' }, - { mode: 1, label: '🌐 ipfs', hint: 'Prefer IPFS for packs; hashes stay on Platform' }, - { mode: 2, label: '🌐 s3', hint: 'Prefer S3-compatible storage for packs' }, - { mode: 3, label: '🌐 https', hint: 'Prefer an HTTPS origin for packs' }, +import { useWriteGuard } from '@/hooks/use-write-guard' +import { + createRepoV2, + discardRepoCreation, + normalizeRepoName, + pendingRepoCreations, + type CreateRepoInput, + type CreateRepoStep, + type RepoCreationJournal, +} from '@/lib/repo' +import { previewCreate, sumPreviews } from '@/lib/sdk' + +const STEPS: readonly { step: CreateRepoStep; label: string }[] = [ + { step: 'repo', label: 'Repository document' }, + { step: 'maintainer', label: 'You, as its first maintainer' }, + { step: 'config', label: 'Initial config (default branch)' }, ] +type StepState = 'todo' | 'running' | 'done' + export default function NewRepoPage(): JSX.Element { const router = useRouter() const { sdk } = useSdk() const { identity, signer } = useAuth() const openLogin = useUiStore((s) => s.openLogin) + const guard = useWriteGuard() + const forge = ACTIVE_NETWORK.v2 const [name, setName] = useState('') const [description, setDescription] = useState('') const [defaultBranch, setDefaultBranch] = useState('main') - const [backendMode, setBackendMode] = useState(0) - const [confirm, setConfirm] = useState(false) + const [confirm, setConfirm] = useState(null) + const [progress, setProgress] = useState | null>(null) + const [pending, setPending] = useState([]) + + useEffect(() => { + if (!identity) return + pendingRepoCreations(DEFAULT_NETWORK, identity).then(setPending, () => setPending([])) + }, [identity]) const nameError = useMemo(() => { if (name.trim() === '') return null try { - normalizeRepoName(name.trim()) + normalizeRepoName(name) return null } catch (e) { return e instanceof Error ? e.message : 'invalid name' } }, [name]) - const cost = previewCredits(COST_ESTIMATE_CREDITS.repoCreate) - - const create = async (): Promise => { - if (!sdk || !signer) throw new Error('sign in first') - const result = await createRepo(sdk, signer, name.trim(), { - defaultBranch, - backendMode, - description: description.trim(), - }) - void result - router.push(`/repo?owner=${encodeURIComponent(identity ?? '')}&name=${encodeURIComponent(normalizeRepoName(name.trim()))}`) + const input = (): CreateRepoInput => ({ + name: normalizeRepoName(name), + ...(description.trim() ? { description: description.trim() } : {}), + ...(defaultBranch.trim() && defaultBranch.trim() !== 'main' ? { defaultBranch: defaultBranch.trim() } : {}), + }) + const costOf = (i: CreateRepoInput) => + sumPreviews([ + previewCreate('repo', { name: i.name, description: i.description ?? '', defaultBranch: i.defaultBranch ?? '' }), + previewCreate('maintainer'), + previewCreate('config', { defaultBranch: i.defaultBranch ?? 'main' }), + ]) + const cost = costOf(name.trim() && nameError === null ? input() : { name: 'x' }) + + const create = async (i: CreateRepoInput): Promise => { + if (!sdk || !signer || !forge) throw new Error('sign in first') + setProgress({ repo: 'todo', maintainer: 'todo', config: 'todo' }) + const result = await createRepoV2(sdk, signer, forge, i, (step, state) => + setProgress((p) => ({ ...(p ?? { repo: 'todo', maintainer: 'todo', config: 'todo' }), [step]: state === 'start' ? 'running' : 'done' })), + ) + router.push(`/repo?owner=${encodeURIComponent(identity ?? '')}&name=${encodeURIComponent(result.name)}&created=1`) } - if (!isRegistryDeployed()) { + if (!isV2Deployed()) { return ( - {isV2Deployed() ? ( + {ACTIVE_NETWORK.registryContractId !== null ? ( .`} + title={`New repos are forge-v2, which ${ACTIVE_NETWORK.key} does not run yet`} + body="Existing v1 repos here stay readable and writable (issues, comments, stars). A v1 repo was its own ~1.18 DASH contract; creating one from the browser is no longer offered." /> ) : ( @@ -90,7 +119,7 @@ export default function NewRepoPage(): JSX.Element { Sign in} /> @@ -106,26 +135,39 @@ export default function NewRepoPage(): JSX.Element {

Forge a new repo

-

A fresh contract, owned by your identity.

+

Three documents on {ACTIVE_NETWORK.key}, owned by your identity.

+ {pending.map((j) => ( +
+ + Creating {j.input.name} did not finish ({j.done.length} of 3 steps). + + + +
+ ))} +
- - setName(e.target.value)} - placeholder="forge-core" - className="font-mono" - spellCheck={false} - autoFocus - /> + + setName(e.target.value)} placeholder="forge-core" className="font-mono" spellCheck={false} autoFocus /> {nameError ?

{nameError}

: null} - -