Skip to content
Closed
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
4 changes: 4 additions & 0 deletions src/app/chain/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { supabase, type Storyline } from "../../../lib/supabase";
import { STORY_FACTORY } from "../../../lib/contracts/constants";
import { useChainPlot } from "../../hooks/useChainPlot";
import type { PublishState } from "../../hooks/usePublish";
import { PublishRecovery } from "../../components/PublishRecovery";
import Link from "next/link";
import { ConnectWallet } from "../../components/ConnectWallet";
import { Select } from "../../components/Select";
Expand Down Expand Up @@ -101,6 +102,9 @@ export default function ChainPlotPage() {

return (
<div className="mx-auto max-w-2xl px-6 py-12">
{/* Recovery banner for failed indexing */}
<PublishRecovery />

<h1 className="text-accent text-2xl font-bold tracking-tight">
Chain Plot
</h1>
Expand Down
4 changes: 4 additions & 0 deletions src/app/create/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
MAX_CONTENT_LENGTH,
} from "../../../lib/content";
import { usePublish, type PublishState } from "../../hooks/usePublish";
import { PublishRecovery } from "../../components/PublishRecovery";
import { storyFactoryAbi, storylineCreatedEvent } from "../../../lib/contracts/abi";
import { STORY_FACTORY } from "../../../lib/contracts/constants";
import { decodeEventLog, encodeEventTopics } from "viem";
Expand Down Expand Up @@ -45,7 +46,7 @@
const [content, setContent] = useState("");
const hasDeadline = true; // mandatory 7-day deadline for all storylines

const { state, error, receipt, execute, reset } = usePublish();

Check warning on line 49 in src/app/create/page.tsx

View workflow job for this annotation

GitHub Actions / lint-and-typecheck

'reset' is assigned a value but never used
const { valid, charCount } = validateContentLength(content);
const titleValid = title.trim().length > 0;
const genreValid = genre.length > 0;
Expand Down Expand Up @@ -123,6 +124,9 @@

return (
<div className="animate-in mx-auto max-w-2xl px-6 py-12">
{/* Recovery banner for failed indexing */}
<PublishRecovery />

{/* Manuscript header */}
<div className="mb-8">
<h1 className="text-2xl font-bold tracking-tight text-foreground">
Expand Down
97 changes: 97 additions & 0 deletions src/components/PublishRecovery.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"use client";

import { useState } from "react";
import {
usePublishIntent,
MAX_RETRY_COUNT,
} from "../hooks/usePublishIntent";
import { EXPLORER_URL } from "../../lib/contracts/constants";

/**
* Recovery banner for failed indexing after successful on-chain tx.
* Mount on any page where publishing can occur (create, chain).
* Renders nothing if no pending intent exists.
*/
export function PublishRecovery() {
const { pendingIntent, retryIndexing, clearIntent } = usePublishIntent();
const [retrying, setRetrying] = useState(false);

if (!pendingIntent) return null;

const maxRetriesExceeded = pendingIntent.retryCount >= MAX_RETRY_COUNT;

const handleRetry = async () => {
setRetrying(true);
await retryIndexing();
setRetrying(false);
};

return (
<div className="mb-6 rounded-lg border border-accent-dim/30 bg-surface px-4 py-4">
<div className="flex items-start gap-3">
<span className="mt-0.5 text-accent-dim text-sm">!</span>
<div className="flex-1">
<p className="text-sm font-medium text-foreground">
Previous publish needs indexing
</p>
<p className="mt-1 text-xs text-muted">
Your transaction was confirmed on-chain but indexing failed.
{maxRetriesExceeded
? " Maximum retries reached — the backfill process will handle this automatically."
: " You can retry indexing or dismiss this notice."}
</p>

{/* Tx hash link */}
{pendingIntent.txHash && (
<p className="mt-2 text-xs">
<span className="text-muted">TX: </span>
<a
href={`${EXPLORER_URL}/tx/${pendingIntent.txHash}`}
target="_blank"
rel="noopener noreferrer"
className="text-accent-dim hover:text-accent break-all transition-colors"
>
{pendingIntent.txHash.slice(0, 10)}...
{pendingIntent.txHash.slice(-8)}
</a>
</p>
)}

{/* Last error */}
{pendingIntent.lastError && (
<p className="mt-1 text-xs text-error">
{pendingIntent.lastError}
{pendingIntent.retryCount > 0 && (
<span className="text-muted">
{" "}
({pendingIntent.retryCount}/{MAX_RETRY_COUNT} retries)
</span>
)}
</p>
)}

{/* Actions */}
<div className="mt-3 flex gap-2">
{!maxRetriesExceeded && (
<button
type="button"
onClick={handleRetry}
disabled={retrying}
className="rounded border border-accent px-3 py-1.5 text-xs text-accent transition-colors hover:bg-accent hover:text-background disabled:opacity-50"
>
{retrying ? "Retrying..." : "Retry Indexing"}
</button>
)}
<button
type="button"
onClick={clearIntent}
className="rounded border border-border px-3 py-1.5 text-xs text-muted transition-colors hover:text-foreground"
>
Dismiss
</button>
</div>
</div>
</div>
</div>
);
}
51 changes: 44 additions & 7 deletions src/hooks/usePublish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useWriteContract } from "wagmi";
import { hashContent } from "../../lib/content";
import { publicClient } from "../../lib/rpc";
import type { Hex, Abi, TransactionReceipt } from "viem";
import { usePublishIntent } from "./usePublishIntent";

export type PublishState =
| "idle"
Expand Down Expand Up @@ -36,15 +37,19 @@ interface PublishOptions {
*
* Manages the 5-state flow: uploading -> confirming -> pending -> indexing -> published.
* Caches CID keyed by content hash for retry (skips re-upload if content unchanged).
* Integrates with usePublishIntent for crash-safe recovery.
*/
export function usePublish() {
const [state, setState] = useState<PublishState>("idle");
const [error, setError] = useState<string | null>(null);
const [txHash, setTxHash] = useState<Hex | undefined>(undefined);
const [receipt, setReceipt] = useState<TransactionReceipt | undefined>(undefined);
const [receipt, setReceipt] = useState<TransactionReceipt | undefined>(
undefined,
);
const cachedCid = useRef<{ cid: string; contentHash: string } | null>(null);

const { writeContractAsync } = useWriteContract();
const { saveIntent, persistTxHash, clearIntent } = usePublishIntent();

const execute = useCallback(
async (opts: PublishOptions) => {
Expand Down Expand Up @@ -75,28 +80,60 @@ export function usePublish() {
cachedCid.current = { cid, contentHash };
}

// Save intent before wallet confirmation
saveIntent({
content: opts.content,
metadata: opts.metadata ?? {},
indexerRoute: opts.indexerRoute,
uploadKeyPrefix: opts.uploadKeyPrefix,
});

// 2. Submit tx to wallet
setState("confirming");
const writeCall = opts.buildWriteCall(cid, contentHash);

const hash = await writeContractAsync(writeCall);
let hash: Hex;
try {
hash = await writeContractAsync(writeCall);
} catch (err) {
// User rejected tx — clear intent, no recovery needed
clearIntent();
throw err;
}
setTxHash(hash);

// Persist tx hash after wallet confirms
persistTxHash(hash);

// 3. Wait for tx confirmation
setState("pending");
const receipt = await publicClient.waitForTransactionReceipt({ hash });
const txReceipt = await publicClient.waitForTransactionReceipt({
hash,
});

setReceipt(receipt);
setReceipt(txReceipt);

// 4. Trigger indexer
setState("indexing");
await new Promise((r) => setTimeout(r, 5000));
await fetch(opts.indexerRoute, {
const indexRes = await fetch(opts.indexerRoute, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ txHash: hash, content: opts.content, ...opts.metadata }),
body: JSON.stringify({
txHash: hash,
content: opts.content,
...opts.metadata,
}),
});

// 409 = already indexed, treat as success
if (!indexRes.ok && indexRes.status !== 409) {
throw new Error(`Indexing failed (${indexRes.status})`);
}

// Clear intent on success
clearIntent();

// 5. Done
setState("published");
cachedCid.current = null;
Expand All @@ -107,7 +144,7 @@ export function usePublish() {
setState("error");
}
},
[writeContractAsync],
[writeContractAsync, saveIntent, persistTxHash, clearIntent],
);

const reset = useCallback(() => {
Expand Down
Loading
Loading