Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(explorer): global transactions listener #3285

Merged
merged 16 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
5 changes: 5 additions & 0 deletions .changeset/tall-penguins-promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@latticexyz/explorer": patch
---

Transactions are now monitored across all tabs while the World Explorer is open.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import { Navigation } from "../../../../../components/Navigation";
import { Providers } from "./Providers";
import { TransactionsWatcher } from "./observe/TransactionsWatcher";

export default function WorldLayout({ children }: { children: React.ReactNode }) {
return (
<Providers>
<Navigation />
{children}
<TransactionsWatcher>
karooolis marked this conversation as resolved.
Show resolved Hide resolved
<Navigation />
{children}
</TransactionsWatcher>
</Providers>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { cn } from "../../../../../../utils";
import { Confirmations } from "./Confirmations";
import { TimingRowExpanded } from "./TimingRowExpanded";
import { columns } from "./TransactionsTable";
import { WatchedTransaction } from "./useTransactionWatcher";
import { WatchedTransaction } from "./useTransactionsWatcher";

function TransactionTableRowDataCell({
label,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { BlockExplorerLink } from "./BlockExplorerLink";
import { TimeAgo } from "./TimeAgo";
import { TimingRowHeader } from "./TimingRowHeader";
import { TransactionTableRow } from "./TransactionTableRow";
import { WatchedTransaction, useTransactionWatcher } from "./useTransactionWatcher";
import { WatchedTransaction, useTransactionsWatcher } from "./useTransactionsWatcher";

const columnHelper = createColumnHelper<WatchedTransaction>();
export const columns = [
Expand Down Expand Up @@ -94,7 +94,7 @@ export const columns = [
];

export function TransactionsTable() {
const transactions = useTransactionWatcher();
const transactions = useTransactionsWatcher();
const [expanded, setExpanded] = useState<ExpandedState>({});

const table = useReactTable({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,49 +1,22 @@
import { useParams } from "next/navigation";
import {
AbiFunction,
Address,
BaseError,
DecodeFunctionDataReturnType,
Hex,
Log,
Transaction,
TransactionReceipt,
decodeFunctionData,
parseAbiItem,
parseEventLogs,
} from "viem";
import { BaseError, Hex, TransactionReceipt, decodeFunctionData, parseEventLogs } from "viem";
import { useConfig, useWatchBlocks } from "wagmi";
import { getTransaction, simulateContract, waitForTransactionReceipt } from "wagmi/actions";
import { useStore } from "zustand";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Message } from "../../../../../../observer/messages";
import { type Write, store } from "../../../../../../observer/store";
import { useCallback, useEffect } from "react";
import { store as observerStore } from "../../../../../../observer/store";
import { useChain } from "../../../../hooks/useChain";
import { useWorldAbiQuery } from "../../../../queries/useWorldAbiQuery";
import { store as worldStore } from "../store";

export type WatchedTransaction = {
writeId: string;
hash?: Hex;
from?: Address;
timestamp?: bigint;
transaction?: Transaction;
functionData?: DecodeFunctionDataReturnType;
value?: bigint;
receipt?: TransactionReceipt;
status: "pending" | "success" | "reverted" | "rejected" | "unknown";
write?: Write;
logs?: Log[];
error?: BaseError;
};

export function useTransactionWatcher() {
export function TransactionsWatcher({ children }: { children: React.ReactNode }) {
const { id: chainId } = useChain();
const { worldAddress } = useParams();
const wagmiConfig = useConfig();
const { data: worldAbiData } = useWorldAbiQuery();
const abi = worldAbiData?.abi;
const [transactions, setTransactions] = useState<WatchedTransaction[]>([]);
const observerWrites = useStore(store, (state) => state.writes);
const { transactions, setTransaction, updateTransaction } = useStore(worldStore);
const observerWrites = useStore(observerStore, (state) => state.writes);

const handleTransaction = useCallback(
async (hash: Hex, timestamp: bigint) => {
Expand All @@ -66,22 +39,19 @@ export function useTransactionWatcher() {
}

const write = Object.values(observerWrites).find((write) => write.hash === hash);
setTransactions((prevTransactions) => [
{
hash,
writeId: write?.writeId ?? hash,
from: transaction.from,
timestamp,
transaction,
status: "pending",
functionData: {
functionName,
args,
},
value: transaction.value,
setTransaction({
hash,
writeId: write?.writeId ?? hash,
from: transaction.from,
timestamp,
transaction,
status: "pending",
functionData: {
functionName,
args,
},
...prevTransactions,
]);
value: transaction.value,
});

let receipt: TransactionReceipt | undefined;
try {
Expand Down Expand Up @@ -115,21 +85,14 @@ export function useTransactionWatcher() {
logs: receipt?.logs || [],
});

setTransactions((prevTransactions) =>
prevTransactions.map((transaction) =>
transaction.hash === hash
? {
...transaction,
receipt,
logs,
status,
error: transactionError as BaseError,
}
: transaction,
),
);
updateTransaction(hash, {
receipt,
logs,
status,
error: transactionError as BaseError,
});
},
[abi, observerWrites, wagmiConfig, worldAddress],
[abi, wagmiConfig, worldAddress, observerWrites, setTransaction, updateTransaction],
);

useEffect(() => {
Expand All @@ -155,42 +118,5 @@ export function useTransactionWatcher() {
pollingInterval: 500,
});

const mergedTransactions = useMemo((): WatchedTransaction[] => {
const mergedMap = new Map<string | undefined, WatchedTransaction>();

for (const write of Object.values(observerWrites)) {
if (write.address !== worldAddress) continue;

const parsedAbiItem = parseAbiItem(`function ${write.functionSignature}`) as AbiFunction;
const writeResult = write.events.find((event): event is Message<"write:result"> => event.type === "write:result");

mergedMap.set(write.hash || write.writeId, {
hash: write.hash,
writeId: write.writeId,
from: write.from,
status: writeResult?.status === "rejected" ? "rejected" : "pending",
timestamp: BigInt(write.time) / 1000n,
functionData: {
functionName: parsedAbiItem.name,
args: write.args,
},
value: write.value,
error: writeResult && "reason" in writeResult ? (writeResult.reason as BaseError) : undefined,
write,
});
}

for (const transaction of transactions) {
const existing = mergedMap.get(transaction.hash);
if (existing) {
mergedMap.set(transaction.hash, { ...transaction, write: existing.write });
} else {
mergedMap.set(transaction.hash, { ...transaction });
}
}

return Array.from(mergedMap.values()).sort((a, b) => Number(b.timestamp ?? 0n) - Number(a.timestamp ?? 0n));
}, [observerWrites, worldAddress, transactions]);

return mergedTransactions;
return children;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { useParams } from "next/navigation";
import {
AbiFunction,
Address,
BaseError,
DecodeFunctionDataReturnType,
Hex,
Log,
Transaction,
TransactionReceipt,
parseAbiItem,
} from "viem";
import { useStore } from "zustand";
import { useMemo } from "react";
import { Message } from "../../../../../../observer/messages";
import { type Write, store as observerStore } from "../../../../../../observer/store";
import { store as worldStore } from "../store";

export type WatchedTransaction = {
writeId: string;
hash?: Hex;
from?: Address;
timestamp?: bigint;
transaction?: Transaction;
functionData?: DecodeFunctionDataReturnType;
value?: bigint;
receipt?: TransactionReceipt;
status: "pending" | "success" | "reverted" | "rejected" | "unknown";
write?: Write;
logs?: Log[];
error?: BaseError;
};

export function useTransactionsWatcher() {
karooolis marked this conversation as resolved.
Show resolved Hide resolved
const { worldAddress } = useParams();
const { transactions } = useStore(worldStore);
karooolis marked this conversation as resolved.
Show resolved Hide resolved
const observerWrites = useStore(observerStore, (state) => state.writes);

const mergedTransactions = useMemo((): WatchedTransaction[] => {
const mergedMap = new Map<string | undefined, WatchedTransaction>();

for (const write of Object.values(observerWrites)) {
if (write.address !== worldAddress) continue;

const parsedAbiItem = parseAbiItem(`function ${write.functionSignature}`) as AbiFunction;
const writeResult = write.events.find((event): event is Message<"write:result"> => event.type === "write:result");

mergedMap.set(write.hash || write.writeId, {
hash: write.hash,
writeId: write.writeId,
from: write.from,
status: writeResult?.status === "rejected" ? "rejected" : "pending",
timestamp: BigInt(write.time) / 1000n,
functionData: {
functionName: parsedAbiItem.name,
args: write.args,
},
value: write.value,
error: writeResult && "reason" in writeResult ? (writeResult.reason as BaseError) : undefined,
write,
});
}

for (const transaction of transactions) {
const existing = mergedMap.get(transaction.hash);
if (existing) {
mergedMap.set(transaction.hash, { ...transaction, write: existing.write });
} else {
mergedMap.set(transaction.hash, { ...transaction });
}
}

return Array.from(mergedMap.values()).sort((a, b) => Number(b.timestamp ?? 0n) - Number(a.timestamp ?? 0n));
}, [observerWrites, worldAddress, transactions]);

return mergedTransactions;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { createStore } from "zustand";
import { WatchedTransaction } from "./observe/useTransactionsWatcher";

export type State = {
transactions: WatchedTransaction[];
setTransaction: (transaction: WatchedTransaction) => void;
updateTransaction: (hash: string, updatedTransaction: Partial<WatchedTransaction>) => void;
};

export const store = createStore<State>()((set) => ({
transactions: [],
setTransaction: (transaction) =>
set((state) => ({
transactions: [...state.transactions, transaction],
})),
updateTransaction: (hash: string, updatedTransaction: Partial<WatchedTransaction>) =>
set((state) => ({
transactions: state.transactions.map((tx) => (tx.hash === hash ? { ...tx, ...updatedTransaction } : tx)),
})),
}));
4 changes: 2 additions & 2 deletions packages/explorer/src/app/(explorer)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ export default function RootLayout({
return (
<html lang="en">
<body className={`${inter.variable} ${jetbrains.variable} dark`}>
<Theme>
<Theme appearance="dark">
<div className="container">{children}</div>
<Toaster richColors closeButton duration={10000} />
<Toaster richColors closeButton duration={10000} theme="dark" />
</Theme>
</body>
</html>
Expand Down
Loading