Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
b289f0e
fix(explorer-api): write dropped and pending txs under the chain lock
alejoamiras Nov 27, 2026
5291e01
fix(explorer-api): move a re-registered contract to its canonical block
alejoamiras Nov 27, 2026
ce5bc1a
fix(explorer-api): validate the tips on the chain they are stored aga…
alejoamiras Nov 27, 2026
8dc2b40
fix: retire cached chain reads when the chain changes
alejoamiras Nov 27, 2026
fdfa1d8
test(explorer-api): expect a replaced tip height cleared and requested
alejoamiras Nov 27, 2026
70e836e
fix(explorer-api): read tx effects by height from canonical blocks only
alejoamiras Nov 27, 2026
0173d27
fix(explorer-api): resolve tip mismatches a chain change fixed while …
alejoamiras Nov 27, 2026
12af1e6
fix(explorer-ui-v2): show a tx only an orphaned block holds as not mined
alejoamiras Nov 27, 2026
2da731e
fix(explorer-api): keep each tip repair window within the request's b…
alejoamiras Nov 27, 2026
302ade6
fix(explorer-api): heartbeat between the txs of a pending or dropped …
alejoamiras Nov 27, 2026
0522b93
fix(explorer-ui-v2): refresh open block pages and contract instances …
alejoamiras Nov 27, 2026
cf12034
fix(explorer-api): bump the chain revision at start-up in archive mod…
alejoamiras Nov 27, 2026
ec13970
docs(explorer-api): keep the chain lock and contract store comments t…
alejoamiras Nov 27, 2026
64f2094
fix(explorer-api): accept a tip tier at block 0 as valid
alejoamiras Nov 27, 2026
541675c
fix(explorer-api): read the tx effects at height 0 as a bounded read
alejoamiras Nov 27, 2026
9ff14f2
test(explorer-api): hold the mempool heartbeat open to show the lock …
alejoamiras Nov 27, 2026
da4850f
fix(explorer-api): ask for a tip repair's mismatch height before its …
alejoamiras Nov 27, 2026
c2601f0
fix(explorer-api): pick a tip repair among due windows before the limit
alejoamiras Nov 27, 2026
29e9181
fix(explorer-ui-v2): list a block's own txs on its page
alejoamiras Nov 27, 2026
246df31
fix(explorer-ui-v2): show only the tx page's selected status
alejoamiras Nov 27, 2026
bb8cf54
fix(explorer-api): send the least recently seen due tip repair first
alejoamiras Nov 27, 2026
4b7b6a7
test(explorer-api): send a tip repair again once its window's backoff…
alejoamiras Nov 27, 2026
f2cbbc2
fix(explorer-ui-v2): show no index or fee on an orphaned block's page
alejoamiras Nov 27, 2026
2c9b619
fix(explorer-ui-v2): show no status for a tx no lookup found
alejoamiras Nov 27, 2026
c28a2d7
docs(explorer-api): describe the tip repair request and the mismatch …
alejoamiras Nov 27, 2026
d242ff7
fix(explorer-api): roll back the block when a contract row hits a ret…
alejoamiras Nov 27, 2026
ce1d8e4
fix(explorer-ui-v2): keep refetching a tx effect while it is orphaned
alejoamiras Nov 27, 2026
6196ec1
refactor(explorer-api): take the chain walk bound from the message re…
alejoamiras Nov 27, 2026
12c0131
docs(explorer-ui-v2): say what refreshes a cached block
alejoamiras Nov 27, 2026
b5d85cc
test(explorer-api): cover a retryable error wrapped as a query error'…
alejoamiras Nov 27, 2026
b16b13c
fix(explorer-api): roll back the block when a contract row hits a sys…
alejoamiras Nov 27, 2026
f7656c9
fix(explorer-ui-v2): refetch open tx and block pages that a catch-up …
alejoamiras Nov 27, 2026
c8df0d0
fix(explorer-ui-v2): refetch a tx page that has found nothing every m…
alejoamiras Nov 27, 2026
a718768
test(explorer-api): load start.js before the start-up test runs
alejoamiras Nov 27, 2026
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 services/explorer-api/src/events/received/on-block/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { z } from "zod";
import { SERVICE_NAME } from "../../../constants.js";
import { L2_NETWORK_ID } from "../../../environment.js";
import { logger } from "../../../logger.js";
import { bumpChainRevision } from "../../../svcs/cache/chain-revision.js";
import { observeRollupVersion } from "../../../svcs/database/controllers/l2/chain-info/rollup-version-cache.js";
import {
applyCatchupBlock,
Expand Down Expand Up @@ -52,6 +53,9 @@ const afterCommit = async (
{ block }: IncomingBlock,
{ canonical }: ChainOutcome,
) => {
// Any applied block can change a cached chain read: the statuses it
// changed, the txs and contracts it took, its children's orphan flags.
await bumpChainRevision();
if (!canonical) {
return;
}
Expand Down
39 changes: 16 additions & 23 deletions services/explorer-api/src/events/received/on-dropped-txs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EventHandler } from "@chicmoz-pkg/message-bus";
import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus";
import {
DroppedTxsEvent,
generateL2TopicName,
Expand All @@ -7,36 +7,29 @@ import {
import { SERVICE_NAME } from "../../constants.js";
import { L2_NETWORK_ID } from "../../environment.js";
import { logger } from "../../logger.js";
import { withChainLock } from "../../svcs/database/controllers/chain-lock.js";
import { storeDroppedTx } from "../../svcs/database/controllers/dropped-tx/store.js";
import { deleteTx } from "../../svcs/database/controllers/l2Tx/index.js";
import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js";
import { deletePublicCall } from "../../svcs/database/controllers/l2Public-call/delete.js";
import { deleteL2ToL1Msgs } from "../../svcs/database/controllers/l2PendingL2ToL1Msg/delete.js";

const onDroppedTxs = async ({ txs }: DroppedTxsEvent) => {
const onDroppedTxs = async ({ txs }: DroppedTxsEvent, heartbeat: Heartbeat) => {
logger.info(`🗑️ Received ${txs.length} dropped txs to handle`);

for (const droppedTx of txs) {
const isAlreadyStored = await txEffectExists(droppedTx.txHash);
if (isAlreadyStored) {
logger.info(`🗑️ Dropped tx ${droppedTx.txHash} already exists, skipping`);
continue;
}
try {
// Store as dropped transaction
await storeDroppedTx(droppedTx);

// Delete public call data
await deletePublicCall(droppedTx.txHash);

// Delete L2-to-L1 messages
await deleteL2ToL1Msgs(droppedTx.txHash);

// Delete from pending transactions
await deleteTx(droppedTx.txHash);
} catch (error) {
logger.error(`Error processing dropped tx ${droppedTx.txHash}:`, error);
}
// Each tx waits for the chain lock on its own.
await heartbeat();
await withChainLock(async (dbTx) => {
if (await txEffectExists(droppedTx.txHash, dbTx)) {
logger.info(`🗑️ Dropped tx ${droppedTx.txHash} is mined, skipping`);
return;
}
await storeDroppedTx(droppedTx, dbTx);
await deletePublicCall(droppedTx.txHash, dbTx);
await deleteL2ToL1Msgs(droppedTx.txHash, dbTx);
await deleteTx(droppedTx.txHash, dbTx);
});
}
};

Expand All @@ -47,5 +40,5 @@ export const droppedTxHandler: EventHandler = {
handlerName: "droppedTxHandler",
}),
topic: generateL2TopicName(L2_NETWORK_ID, "DROPPED_TXS_EVENT"),
cb: onDroppedTxs as (arg0: unknown) => Promise<void>,
cb: onDroppedTxs as (arg0: unknown, heartbeat: Heartbeat) => Promise<void>,
};
36 changes: 23 additions & 13 deletions services/explorer-api/src/events/received/on-pending-txs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EventHandler } from "@chicmoz-pkg/message-bus";
import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus";
import {
PendingTxsEvent,
generateL2TopicName,
Expand All @@ -8,30 +8,40 @@ import { chicmozL2PendingTxSchema } from "@chicmoz-pkg/types";
import { SERVICE_NAME } from "../../constants.js";
import { L2_NETWORK_ID } from "../../environment.js";
import { logger } from "../../logger.js";
import { withChainLock } from "../../svcs/database/controllers/chain-lock.js";
import { storeOrUpdateL2Tx } from "../../svcs/database/controllers/l2Tx/index.js";
import { removeDroppedTxByHash } from "../../svcs/database/controllers/dropped-tx/index.js";
import { handleDuplicateError } from "./utils.js";
import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js";

const onPendingTxs = async ({ txs }: PendingTxsEvent) => {
const onPendingTxs = async ({ txs }: PendingTxsEvent, heartbeat: Heartbeat) => {
logger.info(`🕐 Received ${txs.length} pending txs to store`);

for (const tx of txs) {
try {
const res = chicmozL2PendingTxSchema.parse(tx);

// Each tx waits for the chain lock on its own.
await heartbeat();
const parsed = chicmozL2PendingTxSchema.safeParse(tx);
if (!parsed.success) {
logger.error(
`Failed to parse pending tx ${tx.txHash}: ${parsed.error.message}`,
);
continue;
}
const res = parsed.data;
await withChainLock(async (dbTx) => {
if (await txEffectExists(res.txHash, dbTx)) {
logger.info(`🕐 Pending tx ${res.txHash} is mined, skipping`);
return;
}
// Handle resubmissions: remove from dropped table if exists
const removedCount = await removeDroppedTxByHash(res.txHash);
const removedCount = await removeDroppedTxByHash(res.txHash, dbTx);
if (removedCount > 0) {
logger.info(
`🔄 Resubmitted tx ${res.txHash}: removed from dropped table`,
);
}
// Store/update in pending table (handles both new and resubmitted transactions)
await storeOrUpdateL2Tx(res);
await storeOrUpdateL2Tx(res, dbTx);
logger.debug(`✅ Stored/updated pending tx: ${res.txHash}`);
} catch (e) {
handleDuplicateError(e as Error, `tx ${tx.txHash}`);
}
});
}
};

Expand All @@ -42,5 +52,5 @@ export const pendingTxHandler: EventHandler = {
handlerName: "pendingTxHandler",
}),
topic: generateL2TopicName(L2_NETWORK_ID, "PENDING_TXS_EVENT"),
cb: onPendingTxs as (arg0: unknown) => Promise<void>,
cb: onPendingTxs as (arg0: unknown, heartbeat: Heartbeat) => Promise<void>,
};
8 changes: 6 additions & 2 deletions services/explorer-api/src/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
} from "./environment.js";
import { subscribeHandlers } from "./events/received/index.js";
import { logger } from "./logger.js";
import { removeDroppedThatHaveTxEffects } from "./svcs/database/controllers/dropped-tx/remove.js";
import { bumpChainRevision } from "./svcs/cache/chain-revision.js";
import { removeMinedDroppedTxs } from "./svcs/database/controllers/dropped-tx/remove.js";
import { updateContractInstanceAztecScanNotes } from "./svcs/database/controllers/l2/aztec-scan-notes.js";
import { initializeRollupVersionCache } from "./svcs/database/controllers/l2/chain-info/rollup-version-cache.js";
import { deleteAllTxs } from "./svcs/database/controllers/l2Tx/delete-all-txs.js";
Expand All @@ -23,7 +24,7 @@ import {

export const start = async () => {
await deleteAllTxs(); // TODO: perhaps a more specific deleteAllTxs should be created, also some logs could be good.
await removeDroppedThatHaveTxEffects();
await removeMinedDroppedTxs();
await initializeRollupVersionCache();
await initializeProtocolContracts();
const aztecScanNotes = AZTEC_SCAN_NOTES[L2_NETWORK_ID];
Expand All @@ -39,6 +40,9 @@ ORIGIN: ${notes.origin}`);
});
}
}
// In archive mode too: a crash between a block's commit and its bump left
// that bump undone, and the writes above change cached reads as well.
await bumpChainRevision();

if (ARCHIVE_MODE) {
logger.info(
Expand Down
31 changes: 31 additions & 0 deletions services/explorer-api/src/svcs/cache/chain-revision.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { getEntry, setEntry } from "@chicmoz-pkg/redis-helper";
import { randomUUID } from "node:crypto";
import { logger } from "../../logger.js";

const CHAIN_REVISION = "chainRevision";
const NO_REVISION = "none";
// Longer than any entry it keys lives: a revision that expired back to
// NO_REVISION would serve the entries cached under it before the last bump.
const CHAIN_REVISION_TTL_SECONDS = 7 * 24 * 60 * 60;

/** The last part of a chain read's cache key: a chain change retires it. */
export const getChainRevision = async (): Promise<string> =>
(await getEntry([CHAIN_REVISION])).value ?? NO_REVISION;

/**
* Retires every chain read cached so far. A random value, not a counter: the
* cache client has no atomic increment, and the keys only need a value never
* used before. A failed bump is logged, and those reads live out their TTL.
*/
export const bumpChainRevision = async (): Promise<void> => {
const stored = await setEntry(
[CHAIN_REVISION],
randomUUID(),
CHAIN_REVISION_TTL_SECONDS,
);
if (!stored) {
logger.warn(
"Could not bump the chain revision: cached chain reads live out their TTL",
);
}
};
22 changes: 22 additions & 0 deletions services/explorer-api/src/svcs/database/controllers/chain-lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getDb as db } from "@chicmoz-pkg/postgres-helper";
import { sql } from "drizzle-orm";
import { L2_NETWORK_ID } from "../../../environment.js";
import { type DbTx } from "./utils.js";

const LOCK_NAMESPACE = 1_815_307_112;

/**
* Runs `fn` in one transaction that takes the network's chain lock before
* any other: every write that depends on which blocks are canonical takes
* it first, so those writers queue on it rather than deadlock over rows.
* `lock_timeout` bounds every lock wait in the transaction, this one
* included: a wait over 10 s throws.
*/
export const withChainLock = <T>(fn: (dbTx: DbTx) => Promise<T>): Promise<T> =>
db().transaction(async (dbTx) => {
await dbTx.execute(sql`SET LOCAL lock_timeout = '10s'`);
await dbTx.execute(
sql`SELECT pg_advisory_xact_lock(${LOCK_NAMESPACE}::int4, hashtext(${L2_NETWORK_ID}))`,
);
return fn(dbTx);
});
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { getDb as db } from "@chicmoz-pkg/postgres-helper";
import { HexString } from "@chicmoz-pkg/types";
import { eq } from "drizzle-orm";
import { and, eq, exists, isNull, sql } from "drizzle-orm";
import { logger } from "../../../../logger.js";
import { droppedTx } from "../../../database/schema/dropped-tx/index.js";
import { txEffect } from "../../schema/index.js";
import { getDroppedTxs } from "./get-tx.js";
import { body, l2Block, txEffect } from "../../schema/index.js";
import { withChainLock } from "../chain-lock.js";

/**
* Removes a dropped transaction by its hash
Expand All @@ -14,8 +14,9 @@ import { getDroppedTxs } from "./get-tx.js";
*/
export const removeDroppedTxByHash = async (
txHash: HexString,
executor: ReturnType<typeof db> = db(),
): Promise<number> => {
const deletedEntries = await db()
const deletedEntries = await executor
.delete(droppedTx)
.where(eq(droppedTx.txHash, txHash))
.returning();
Expand All @@ -27,20 +28,25 @@ export const removeDroppedTxByHash = async (
return deletedEntries.length;
};

export const removeDroppedThatHaveTxEffects = async (): Promise<number> => {
const allDroppedTxs = await getDroppedTxs();
let count = 0;
for (const tx of allDroppedTxs) {
const txEffectRes = await db()
.select()
.from(txEffect)
.where(eq(txEffect.txHash, tx.txHash))
.limit(1);
if (txEffectRes.length > 0) {
await removeDroppedTxByHash(tx.txHash);
count++;
}
}
logger.info(`🗑️🗑️🔥🔥 removed ${count} dropped txs that already had a txEffect`);
return count;
/** Removes the dropped rows of txs a canonical block holds: those are mined. */
export const removeMinedDroppedTxs = async (): Promise<number> => {
const { rowCount } = await withChainLock((dbTx) =>
dbTx.delete(droppedTx).where(
exists(
dbTx
.select({ one: sql`1` })
.from(txEffect)
.innerJoin(body, eq(txEffect.bodyId, body.id))
.innerJoin(l2Block, eq(body.blockHash, l2Block.hash))
.where(
and(
eq(txEffect.txHash, droppedTx.txHash),
isNull(l2Block.orphan_timestamp),
),
),
),
),
);
logger.info(`🗑️🗑️🔥🔥 removed ${rowCount ?? 0} dropped txs that are mined`);
return rowCount ?? 0;
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import { ChicmozL2DroppedTx } from "@chicmoz-pkg/types";
import { logger } from "../../../../logger.js";
import { droppedTx } from "../../schema/dropped-tx/index.js";

export const storeDroppedTx = async (tx: ChicmozL2DroppedTx): Promise<void> => {
const res = await db()
export const storeDroppedTx = async (
tx: ChicmozL2DroppedTx,
executor: ReturnType<typeof db> = db(),
): Promise<void> => {
const res = await executor
.insert(droppedTx)
.values(tx)
.onConflictDoNothing()
Expand Down
Loading
Loading