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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
237 changes: 154 additions & 83 deletions forge-web/app/new/page.tsx
Original file line number Diff line number Diff line change
@@ -1,81 +1,131 @@
'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 <name>" 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 { useCallback, 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 {
checkRepoInput,
createRepoV2,
discardRepoCreation,
normalizeRepoName,
pendingRepoCreations,
type CreateRepoInput,
type CreateRepoStep,
type RepoCreationJournal,
} from '@/lib/repo'
import { previewCreate, sumPreviews } from '@/lib/sdk'
import { errorMessage } from '@/lib/utils'

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'
const INITIAL_PROGRESS: Record<CreateRepoStep, StepState> = { repo: 'todo', maintainer: 'todo', config: 'todo' }

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<CreateRepoInput | null>(null)
const [progress, setProgress] = useState<Record<CreateRepoStep, StepState> | null>(null)
const [pending, setPending] = useState<RepoCreationJournal[]>([])

const reloadPending = useCallback(() => {
if (!identity) return
pendingRepoCreations(DEFAULT_NETWORK, identity).then(setPending, () => setPending([]))
}, [identity])
useEffect(reloadPending, [reloadPending])

const nameError = useMemo(() => {
if (name.trim() === '') return null
try {
normalizeRepoName(name.trim())
checkRepoInput({ name: normalizeRepoName(name), description })
return null
} catch (e) {
return e instanceof Error ? e.message : 'invalid name'
return errorMessage(e, 'invalid name')
}
}, [name, description])
// An unfinished creation of this name resumes with the values it started with.
const resuming = useMemo(() => {
if (nameError !== null || name.trim() === '') return null
const n = normalizeRepoName(name)
return pending.find((j) => j.input.name === n) ?? null
}, [name, nameError, pending])
const differs =
resuming !== null &&
((resuming.input.description ?? '') !== description.trim() || (resuming.input.defaultBranch ?? 'main') !== (defaultBranch.trim() || 'main'))

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', { ...i, visibility: 'public' }),
previewCreate('maintainer'),
previewCreate('config', { defaultBranch: i.defaultBranch ?? 'main' }),
])
const cost = costOf(name.trim() && nameError === null ? input() : { name: 'x' })

const create = async (i: CreateRepoInput): Promise<void> => {
if (!sdk || !signer || !forge) throw new Error('sign in first')
setProgress(INITIAL_PROGRESS)
let result
try {
result = await createRepoV2(sdk, signer, forge, i, (step, state) =>
setProgress((p) => ({ ...(p ?? INITIAL_PROGRESS), [step]: state === 'start' ? 'running' : 'done' })),
)
} catch (e) {
setProgress(null)
throw e
} finally {
reloadPending()
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}, [name])

const cost = previewCredits(COST_ESTIMATE_CREDITS.repoCreate)

const create = async (): Promise<void> => {
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()))}`)
router.push(`/repo?owner=${encodeURIComponent(identity ?? '')}&name=${encodeURIComponent(result.name)}&created=1`)
}

if (!isRegistryDeployed()) {
if (!isV2Deployed()) {
return (
<AppShell>
{isV2Deployed() ? (
{ACTIVE_NETWORK.registryContractId !== null ? (
<EmptyState
icon={Terminal}
title="Create forge-v2 repos with dg for now"
body={`${ACTIVE_NETWORK.key} runs forge-v2, where a repo is three documents (the repo, your maintainer membership, its first config). Creating one from the browser is coming next; until then: dg repo create <name>.`}
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."
/>
) : (
<NotDeployedState />
Expand All @@ -90,7 +140,7 @@ export default function NewRepoPage(): JSX.Element {
<EmptyState
icon={Lock}
title="Sign in to forge a repo"
body="Creating a repo instantiates its on-chain token contract — that needs your identity's key."
body="Creating a repo writes three small documents signed by your identity."
action={<Button variant="primary" onClick={openLogin}>Sign in</Button>}
/>
</AppShell>
Expand All @@ -106,26 +156,39 @@ export default function NewRepoPage(): JSX.Element {
</span>
<div>
<h1 className="text-xl">Forge a new repo</h1>
<p className="text-dense text-anvil-500 dark:text-anvil-400">A fresh contract, owned by your identity.</p>
<p className="text-dense text-anvil-500 dark:text-anvil-400">Three documents on {ACTIVE_NETWORK.key}, owned by your identity.</p>
</div>
</div>

{pending.map((j) => (
<div key={j.input.name} className="mb-4 flex flex-wrap items-center gap-2 rounded-md border border-caution/40 bg-caution/5 px-3 py-2 text-dense">
<span className="flex-1">
Creating <span className="font-mono">{j.input.name}</span> did not finish ({j.done.length} of 3 steps).
</span>
<Button size="sm" variant="primary" onClick={() => setConfirm(j.input)}>
Finish creating {j.input.name}
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => {
void discardRepoCreation(DEFAULT_NETWORK, identity, j.input.name)
setPending((p) => p.filter((x) => x !== j))
}}
>
Dismiss
</Button>
</div>
))}

<div className="space-y-4">
<Field label="Repository name" htmlFor="repo-name" hint="Lowercase; letters, digits, and . _ - (max 63).">
<Input
id="repo-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="forge-core"
className="font-mono"
spellCheck={false}
autoFocus
/>
<Field label="Repository name" htmlFor="repo-name" hint="Lowercase; letters, digits, and . _ - (max 63). The name is permanent.">
<Input id="repo-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="forge-core" className="font-mono" spellCheck={false} autoFocus />
</Field>
{nameError ? <p className="-mt-2 text-[12px] text-danger">{nameError}</p> : null}

<Field label="Description" htmlFor="repo-desc" hint="Shown in discovery. Optional.">
<Textarea id="repo-desc" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="What is this repo for?" className="min-h-[72px]" />
<Field label="Description" htmlFor="repo-desc" hint="Shown in discovery. Optional; editable later.">
<Textarea id="repo-desc" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="What is this repo for?" className="min-h-[72px]" maxLength={500} />
</Field>

<Field label="Default branch" htmlFor="repo-branch">
Expand All @@ -135,50 +198,58 @@ export default function NewRepoPage(): JSX.Element {
</div>
</Field>

<Field label="Storage backend" hint="Recorded in the repo config. git push currently stores packs on Platform whatever you pick; dg repack / dg reseed move them. Change it later with dg repo backend set.">
<div className="grid grid-cols-2 gap-2">
{BACKENDS.map((b) => (
<button
key={b.mode}
type="button"
onClick={() => setBackendMode(b.mode)}
className={
'rounded-md border px-3 py-2 text-left text-dense transition-colors ' +
(backendMode === b.mode
? 'border-forge-500 bg-forge-500/5'
: 'border-anvil-200 hover:bg-anvil-50 dark:border-anvil-750 dark:hover:bg-anvil-850')
}
>
<div className="font-medium">{b.label}</div>
<div className="mt-0.5 text-[11px] text-anvil-500 dark:text-anvil-400">{b.hint}</div>
</button>
))}
</div>
</Field>

{differs ? (
<p className="text-[12px] text-caution">
An unfinished creation of this name started with a different description or branch; finishing it keeps those
values. Change them after it exists.
</p>
) : null}
<CostPreview cost={cost} />
<p className="-mt-2 text-[12px] text-anvil-500 dark:text-anvil-400">
One-time. Code goes to storage you choose when you push; Platform keeps manifests and refs.
</p>

{progress ? (
<ol aria-label="Creation steps" className="space-y-1 rounded-md border border-anvil-200 p-3 dark:border-anvil-800">
{STEPS.map(({ step, label }) => (
<li key={step} className="flex items-center gap-2 text-dense">
{progress[step] === 'done' ? (
<Check className="h-4 w-4 text-verify" aria-hidden />
) : progress[step] === 'running' ? (
<Loader2 className="h-4 w-4 animate-spin text-anvil-400" aria-hidden />
) : (
<span className="h-4 w-4 rounded-full border border-anvil-300 dark:border-anvil-700" aria-hidden />
)}
{label}
</li>
))}
</ol>
) : null}

<Button
variant="primary"
size="lg"
className="w-full"
disabled={name.trim() === '' || nameError !== null}
onClick={() => setConfirm(true)}
disabled={name.trim() === '' || nameError !== null || guard.disabledReason !== null}
title={guard.disabledReason ?? undefined}
onClick={() => {
if (guard.check(cost.credits)) setConfirm(input())
}}
>
Create repository
</Button>
</div>
</div>

<ConfirmDialog
open={confirm}
onClose={() => setConfirm(false)}
title="Create this repository?"
description="This instantiates a new on-chain token contract with your identity's CRITICAL key. The contract is permanent: it cannot be deleted, and the fee is not refunded."
cost={cost}
open={confirm !== null}
onClose={() => setConfirm(null)}
title={confirm ? `Create ${confirm.name}?` : 'Create repository?'}
description="Writes the repo document, makes you its first maintainer, and records its config. Repos cannot be deleted (archive instead), and the name is permanent."
cost={confirm ? costOf(confirm) : cost}
confirmLabel="Sign & create"
successNote="Contract created — opening your repo"
onConfirm={create}
successNote="Created — opening your repo"
onConfirm={() => (confirm ? create(confirm) : Promise.resolve())}
/>
</AppShell>
)
Expand Down
15 changes: 11 additions & 4 deletions forge-web/app/settings/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

/** `/settings` — account settings: identity, network, running balance/spend, sign out. */
/** `/settings` — account settings: identity, network, balance, the local spend ledger, sign out. */

import Link from 'next/link'
import { LogOut, Wallet } from 'lucide-react'
Expand All @@ -12,12 +12,14 @@ import { Oid } from '@/components/ui/oid'
import { useAuth } from '@/contexts/auth-context'
import { useUiStore } from '@/hooks/use-ui-store'
import { NetworkBadge } from '@/components/ui/network-badge'
import { SpendPanel } from '@/components/spend-panel'
import { creditsToDash } from '@/lib/sdk'
import { balanceToDash, dashToUsd } from '@/lib/view/format'

export default function SettingsPage(): JSX.Element {
const { identity, balance, logout } = useAuth()
const openLogin = useUiStore((s) => s.openLogin)
const openTopUp = useUiStore((s) => s.openTopUp)

if (!identity) {
return (
Expand Down Expand Up @@ -57,9 +59,14 @@ export default function SettingsPage(): JSX.Element {
<div className="mt-1 font-mono text-dense text-anvil-400">
{credits.toLocaleString()} credits · ≈ {dashToUsd(creditsToDash(credits))}
</div>
<a href="https://bridge.thepasta.org" target="_blank" rel="noreferrer noopener" className="mt-3 inline-block text-dense text-forge-600 underline dark:text-forge-400">
Top up at the bridge →
</a>
<button type="button" onClick={() => openTopUp()} className="mt-3 inline-block text-dense text-forge-600 underline dark:text-forge-400">
Top up →
</button>
</section>

<section className="rounded-lg border border-anvil-200 p-4 dark:border-anvil-800">
<h2 className="mb-3 text-dense font-medium text-anvil-500 dark:text-anvil-400">Spend</h2>
<SpendPanel />
</section>

<section className="rounded-lg border border-anvil-200 p-4 dark:border-anvil-800">
Expand Down
14 changes: 13 additions & 1 deletion forge-web/components/app-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { ThemeToggle } from '@/components/theme-toggle'
import { NetworkBadge } from '@/components/ui/network-badge'
import { creditsToDash } from '@/lib/sdk'
import { balanceToDash, dashToUsd } from '@/lib/view/format'
import { FundsPill } from '@/components/funds-pill'

export function AppHeader(): JSX.Element {
const openLogin = useUiStore((s) => s.openLogin)
Expand Down Expand Up @@ -67,7 +68,10 @@ export function AppHeader(): JSX.Element {
<div className="ml-auto flex items-center gap-1.5">
<ThemeToggle />
{identity ? (
<AccountMenu identity={identity} balance={balance} onLogout={logout} />
<>
<FundsPill />
<AccountMenu identity={identity} balance={balance} onLogout={logout} />
</>
) : (
<Button variant="primary" size="sm" onClick={openLogin}>
Sign in
Expand Down Expand Up @@ -127,6 +131,14 @@ function AccountMenu({
{credits.toLocaleString()} credits · ≈ {dashToUsd(creditsToDash(credits))}
</div>
</div>
<Link
href="/settings"
role="menuitem"
className="block rounded-md px-3 py-2 text-dense hover:bg-anvil-100 dark:hover:bg-anvil-800"
onClick={() => setOpen(false)}
>
Settings &amp; spend
</Link>
<Link
href={`/u?name=${encodeURIComponent(identity)}`}
role="menuitem"
Expand Down
Loading
Loading