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

Get transaction details (request) #101

Merged
merged 11 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { TransactionType } from '@circle-fin/developer-controlled-wallets';
import { useEffect, useState } from 'react';

import { ChainLabel } from '~/components/ChainLabel';
import { Badge } from '~/components/ui/badge';
import { TransactionType } from '~/lib/constants';
import { formatDate, shortenAddress, shortenHash } from '~/lib/format';
import { Transaction } from '~/lib/types';

Expand All @@ -9,8 +11,36 @@
transaction: Transaction;
}

export interface ActiveTransactionDetailsProps {
/** The on-chain transaction */
transactionId: string;
loadTransactionById: (transactionId: string) => Promise<Transaction>;
}

/** The details of an on-chain transaction */
export function TransactionDetails({ transaction }: TransactionDetailsProps) {
export function TransactionDetails(
props: TransactionDetailsProps | ActiveTransactionDetailsProps,
avkos marked this conversation as resolved.
Show resolved Hide resolved
) {
const [transaction, setTransaction] = useState<Transaction>(
(props as TransactionDetailsProps)?.transaction,
);
useEffect(() => {
if ((props as ActiveTransactionDetailsProps)?.transactionId) {
(props as ActiveTransactionDetailsProps)

Check failure on line 29 in packages/circle-demo-webapp/app/components/TransactionDetails/TransactionDetails.tsx

View workflow job for this annotation

GitHub Actions / Install, lint and build

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
.loadTransactionById((props as ActiveTransactionDetailsProps).transactionId)
.then((tx) => {
setTransaction(tx);
});
}
}, [

Check warning on line 35 in packages/circle-demo-webapp/app/components/TransactionDetails/TransactionDetails.tsx

View workflow job for this annotation

GitHub Actions / Install, lint and build

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array
(props as ActiveTransactionDetailsProps)?.transactionId,

Check warning on line 36 in packages/circle-demo-webapp/app/components/TransactionDetails/TransactionDetails.tsx

View workflow job for this annotation

GitHub Actions / Install, lint and build

React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked
(props as ActiveTransactionDetailsProps).loadTransactionById,

Check warning on line 37 in packages/circle-demo-webapp/app/components/TransactionDetails/TransactionDetails.tsx

View workflow job for this annotation

GitHub Actions / Install, lint and build

React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked
]);

if (!transaction) {
return null;
}

const isInbound = transaction.transactionType === TransactionType.Inbound;

return (
Expand Down
45 changes: 45 additions & 0 deletions packages/circle-demo-webapp/app/hooks/useGetTransaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { GetTransactionInput } from '@circle-fin/developer-controlled-wallets';
import { useState } from 'react';

import { TransactionWithToken } from '~/lib/types';
import { callGetFetch } from '~/lib/utils';

interface UseGetTransactionResult {
error: Error | undefined;
transaction: TransactionWithToken | undefined;
isLoading: boolean;
getTransaction: (args: GetTransactionInput) => Promise<boolean>;
setTransaction: (transaction: TransactionWithToken | undefined) => void;
}

export const useGetTransaction = (): UseGetTransactionResult => {
const [transaction, setTransaction] = useState<TransactionWithToken | undefined>();
const [error, setError] = useState<Error | undefined>(undefined);
const [isLoading, setIsLoading] = useState<boolean>(false);

const getTransaction = async (args: GetTransactionInput) => {
setIsLoading(true);
setError(undefined);
try {
const res = await callGetFetch<{ transaction: TransactionWithToken }>(
`/api/getTransaction`,
args as unknown as Record<string, string>,
);
setTransaction(res.transaction);
return true;
} catch (err) {
setError(err as Error);
return false;
} finally {
setIsLoading(false);
}
};

return {
error,
isLoading,
transaction,
getTransaction,
setTransaction,
avkos marked this conversation as resolved.
Show resolved Hide resolved
};
};
4 changes: 2 additions & 2 deletions packages/circle-demo-webapp/app/lib/format.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
export function shortenAddress(address: string): string {
return `${address.slice(0, 6)}...${address.slice(-4)}`;
return `${String(address).slice(0, 6)}...${String(address).slice(-4)}`;
}

export function shortenHash(hash: string): string {
return `${hash.slice(0, 10)}...${hash.slice(-10)}`;
return `${String(hash).slice(0, 10)}...${String(hash).slice(-10)}`;
avkos marked this conversation as resolved.
Show resolved Hide resolved
}

export function formatDate(date: string): string {
Expand Down
41 changes: 41 additions & 0 deletions packages/circle-demo-webapp/app/lib/memcache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { sdk } from '~/lib/sdk';
import { Token } from '~/lib/types';

class MemCache<ReturnType> {
avkos marked this conversation as resolved.
Show resolved Hide resolved
private map: Map<string, ReturnType>;
private load: (id: string) => Promise<ReturnType>;

constructor(options: { loadFunction: (id: string) => Promise<ReturnType> }) {
this.load = options.loadFunction;
this.map = new Map<string, ReturnType>();
}

set(key: string, value: ReturnType): void {
this.map.set(key, value);
}

get(key: string): ReturnType | undefined {
return this.map.get(key);
}

has(key: string): boolean {
return this.map.has(key);
}

async loadAndSet(key: string): Promise<ReturnType> {
const data = this.get(key);
if (data) {
return data;
}
const value = await this.load(key);
this.set(key, value);
return value;
}
}

export const cachedCoins = new MemCache<Token>({
loadFunction: async (id: string) => {
const res = await sdk.getToken({ id });
return res.data?.token as Token;
},
});
22 changes: 22 additions & 0 deletions packages/circle-demo-webapp/app/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';

import { Blockchain } from '~/lib/constants';
import { ErrorResponse } from '~/lib/responses';

export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
Expand All @@ -22,6 +23,27 @@ export async function callFetch<ReturnType extends object>(
},
body: JSON.stringify(body),
});
if (res.status !== 200) {
const errorData = (await res.json()) as ErrorResponse;
throw new Error(errorData.error);
}
return (await res.json()) as ReturnType;
}

export async function callGetFetch<ReturnType extends object>(
avkos marked this conversation as resolved.
Show resolved Hide resolved
url: string,
query: Record<string, string>,
): Promise<ReturnType> {
const res = await fetch(`${url}?${new URLSearchParams(query)}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (res.status !== 200) {
const errorData = (await res.json()) as ErrorResponse;
throw new Error(errorData.error);
}
return (await res.json()) as ReturnType;
}

Expand Down
35 changes: 24 additions & 11 deletions packages/circle-demo-webapp/app/routes/api.getTransaction.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import { GetTransactionInput } from '@circle-fin/developer-controlled-wallets';
import { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/node';
import {
GetTransactionInput,
TransactionType,
} from '@circle-fin/developer-controlled-wallets';
import { LoaderFunctionArgs } from '@remix-run/node';

import { cachedCoins } from '~/lib/memcache';
import { sdk } from '~/lib/sdk';
import { TransactionWithToken } from '~/lib/types';

/**
* @deprecated Use `loader` instead
*/
export async function action({ request }: ActionFunctionArgs) {
const res = await sdk.getTransaction((await request.json()) as GetTransactionInput);
return Response.json(res.data);
}
export async function loader(o: LoaderFunctionArgs) {
const url = new URL(o.request.url);
avkos marked this conversation as resolved.
Show resolved Hide resolved

const params: GetTransactionInput = {
id: url.searchParams.get('id')!,
};
const txType = url.searchParams.get('txType');
if (txType) {
params.txType = txType as TransactionType;
}

const res = await sdk.getTransaction(params);
if (res?.data?.transaction?.tokenId) {
(res.data.transaction as TransactionWithToken).token = await cachedCoins.loadAndSet(
res.data.transaction?.tokenId,
);
}

export async function loader({ request }: LoaderFunctionArgs) {
const res = await sdk.getTransaction((await request.json()) as GetTransactionInput);
return Response.json(res.data);
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { ListTransactionsInput } from '@circle-fin/developer-controlled-wallets';
import { LoaderFunctionArgs } from '@remix-run/node';

import { cachedCoins } from '~/lib/memcache';
import { sdk } from '~/lib/sdk';
import { Token, TransactionWithToken } from '~/lib/types';

const cachedCoins = new Map<string, Token>();
import { TransactionWithToken } from '~/lib/types';

export async function loader(o: LoaderFunctionArgs) {
const url = new URL(o.request.url);
Expand All @@ -27,17 +26,12 @@ export async function loader(o: LoaderFunctionArgs) {
for (const tx of txs) {
if (tx.tokenId && !needToLoad[String(tx.tokenId)] && !cachedCoins.has(tx.tokenId)) {
needToLoad[tx.tokenId] = true;
prs.push(sdk.getToken({ id: tx.tokenId }));
prs.push(cachedCoins.loadAndSet(tx.tokenId));
}
}

if (prs.length > 0) {
const tokens = await Promise.all(prs);
for (const token of tokens) {
if (token.data?.token) {
cachedCoins.set(token.data.token.id, token.data.token as Token);
}
}
await Promise.all(prs);
}
const txWithTokens: TransactionWithToken[] = [];

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { LoaderCircle } from 'lucide-react';
import { useMemo } from 'react';

import { ChainLabel } from '~/components/ChainLabel';
Expand All @@ -22,55 +23,75 @@
);

export interface TransactionDetailsProps {
/** The wallet associated with the on-chain account */
transaction: TransactionWithToken;
/** Child components to associate with the wallet */
}

export interface TransactionLoadingDetailsProps {
isLoading: boolean;
}

export interface CommonTransactionDetailsProps {
children?: React.ReactNode;
avkos marked this conversation as resolved.
Show resolved Hide resolved
onClose?: () => void;
}

/** The details of an on-chain account */
export function TransactionDetails({ transaction, onClose }: TransactionDetailsProps) {
const shortHash = useMemo(() => shortenHash(transaction.txHash!), [transaction]);
const isInbound = transaction.transactionType === TransactionType.Inbound;
export function TransactionDetails(
props: CommonTransactionDetailsProps &
(TransactionDetailsProps | TransactionLoadingDetailsProps),
avkos marked this conversation as resolved.
Show resolved Hide resolved
) {
const transaction = (props as TransactionDetailsProps).transaction;
const isLoading = (props as TransactionLoadingDetailsProps).isLoading;
avkos marked this conversation as resolved.
Show resolved Hide resolved
if (!transaction && !isLoading) {
return null;
}

const shortHash = useMemo(() => shortenHash(transaction?.txHash!), [transaction]);

Check failure on line 49 in packages/circle-demo-webapp/app/routes/transactions.$walletId/components/TransactionDetails/TransactionDetails.tsx

View workflow job for this annotation

GitHub Actions / Install, lint and build

React Hook "useMemo" is called conditionally. React Hooks must be called in the exact same order in every component render

Check failure on line 49 in packages/circle-demo-webapp/app/routes/transactions.$walletId/components/TransactionDetails/TransactionDetails.tsx

View workflow job for this annotation

GitHub Actions / Install, lint and build

Optional chain expressions can return undefined by design - using a non-null assertion is unsafe and wrong
avkos marked this conversation as resolved.
Show resolved Hide resolved
const isInbound = transaction?.transactionType === TransactionType.Inbound;
return (
<Dialog open onOpenChange={onClose}>
<Dialog open onOpenChange={props.onClose}>
<DialogContent className="min-w-[480px]">
<DialogTitle>Transaction Details</DialogTitle>
<div>
<OneLine label="Hash" value={shortHash} />
<OneLine
label="Status"
value={<TransactionStateText state={transaction.state} />}
/>
<OneLine label="From" value={transaction.sourceAddress} />
<OneLine label="To" value={transaction.destinationAddress} />
{transaction.token && (
<OneLine label="Token" value={<TokenItem token={transaction.token} />} />
)}
{isLoading ? (
<div className="flex justify-center items-center w-full h-40">
<LoaderCircle className="animate-spin" />
</div>
) : (
<div>
<OneLine label="Hash" value={shortHash} />
avkos marked this conversation as resolved.
Show resolved Hide resolved
<OneLine
label="Status"
value={<TransactionStateText state={transaction.state} />}
/>
<OneLine label="From" value={transaction.sourceAddress} />
<OneLine label="To" value={transaction.destinationAddress} />
{transaction.token && (
<OneLine label="Token" value={<TokenItem token={transaction.token} />} />
)}

<OneLine
label="Amount"
value={
<span
className={`text-right font-medium ${
isInbound ? 'text-green-600' : 'text-destructive'
}`}
>
{isInbound ? '+' : '-'} {transaction.amounts?.[0] ?? '0.00'}
</span>
}
/>
<OneLine
label="Date"
value={formatDate(transaction.firstConfirmDate ?? transaction.createDate)}
/>
<OneLine
label="Blockchain"
value={<ChainLabel blockchain={transaction.blockchain} />}
/>
<OneLine label="Note" value={transaction.refId} />
</div>
<OneLine
label="Amount"
value={
<span
className={`text-right font-medium ${
isInbound ? 'text-green-600' : 'text-destructive'
}`}
>
{isInbound ? '+' : '-'} {transaction.amounts?.[0] ?? '0.00'}
</span>
}
/>
<OneLine
label="Date"
value={formatDate(transaction.firstConfirmDate ?? transaction.createDate)}
/>
<OneLine
label="Blockchain"
value={<ChainLabel blockchain={transaction.blockchain} />}
/>
<OneLine label="Note" value={transaction.refId} />
</div>
)}
</DialogContent>
</Dialog>
);
Expand Down
Loading
Loading