Merge branch 'feature/optimize-0x0fe2542079644e107cbf13690eb9c2c65963ccb79089ff96bfaf8dced2331c92' into feature/trace-tx

This commit is contained in:
Willian Mitsuda 2021-10-29 23:34:54 -03:00
commit 7b6cf499bc
8 changed files with 163 additions and 70 deletions

View File

@ -15,7 +15,7 @@ import {
type TokenTransferItemProps = {
t: TokenTransfer;
txData: TransactionData;
tokenMeta?: TokenMeta | undefined;
tokenMeta: TokenMeta | null | undefined;
};
// TODO: handle partial

View File

@ -20,7 +20,7 @@ type DecoratedAddressLinkProps = {
selfDestruct?: boolean;
txFrom?: boolean;
txTo?: boolean;
tokenMeta?: TokenMeta;
tokenMeta?: TokenMeta | null | undefined;
};
const DecoratedAddresssLink: React.FC<DecoratedAddressLinkProps> = ({

View File

@ -3,7 +3,8 @@ import AddressHighlighter from "../components/AddressHighlighter";
import DecoratedAddressLink from "../components/DecoratedAddressLink";
import ContentFrame from "../ContentFrame";
import { TransactionData } from "../types";
import { useTraceTransaction } from "../useErigonHooks";
import { useBatch4Bytes } from "../use4Bytes";
import { useTraceTransaction, useUniqueSignatures } from "../useErigonHooks";
import { RuntimeContext } from "../useRuntime";
import TraceItem from "./TraceItem";
@ -14,6 +15,8 @@ type TraceProps = {
const Trace: React.FC<TraceProps> = ({ txData }) => {
const { provider } = useContext(RuntimeContext);
const traces = useTraceTransaction(provider, txData.transactionHash);
const uniqueSignatures = useUniqueSignatures(traces);
const sigMap = useBatch4Bytes(uniqueSignatures);
return (
<ContentFrame tabs>
@ -37,6 +40,7 @@ const Trace: React.FC<TraceProps> = ({ txData }) => {
t={t}
txData={txData}
last={i === a.length - 1}
fourBytesMap={sigMap}
/>
))}
</div>

View File

@ -4,29 +4,36 @@ import DecoratedAddressLink from "../components/DecoratedAddressLink";
import FormattedBalance from "../components/FormattedBalance";
import FunctionSignature from "./FunctionSignature";
import { TransactionData } from "../types";
import { rawInputTo4Bytes, use4Bytes } from "../use4Bytes";
import { extract4Bytes, FourBytesEntry } from "../use4Bytes";
import { TraceGroup } from "../useErigonHooks";
type TraceItemProps = {
t: TraceGroup;
txData: TransactionData;
last: boolean;
fourBytesMap: Record<string, FourBytesEntry | null | undefined>;
};
const TraceItem: React.FC<TraceItemProps> = ({ t, txData, last }) => {
const raw4Bytes = rawInputTo4Bytes(t.input);
const fourBytesEntry = use4Bytes(raw4Bytes);
const TraceItem: React.FC<TraceItemProps> = ({
t,
txData,
last,
fourBytesMap,
}) => {
const raw4Bytes = extract4Bytes(t.input);
const sigText =
raw4Bytes === null
? "<fallback>"
: fourBytesMap[raw4Bytes]?.name ?? raw4Bytes;
return (
<>
<div className="flex">
<div className="relative w-5">
<div className="absolute border-l border-b w-full h-full transform -translate-y-1/2"></div>
{!last && (
<div className="absolute left-0 border-l w-full h-full transform translate-y-1/2"></div>
)}
</div>
<div className="flex items-baseline border rounded px-1 py-px">
<div className="flex relative">
<div className="absolute border-l border-b w-5 h-full transform -translate-y-1/2"></div>
{!last && (
<div className="absolute left-0 border-l w-5 h-full transform translate-y-1/2"></div>
)}
<div className="ml-5 flex items-baseline border rounded px-1 py-px">
<span className="text-xs text-gray-400 lowercase">{t.type}</span>
<span>
<AddressHighlighter address={t.to}>
@ -39,37 +46,28 @@ const TraceItem: React.FC<TraceItemProps> = ({ t, txData, last }) => {
</AddressHighlighter>
</span>
<span>.</span>
<FunctionSignature
callType={t.type}
sig={fourBytesEntry ? fourBytesEntry.name : raw4Bytes}
/>
<FunctionSignature callType={t.type} sig={sigText} />
{t.value && !t.value.isZero() && (
<span className="text-red-700 whitespace-nowrap">
{"{"}value: <FormattedBalance value={t.value} /> ETH{"}"}
</span>
)}
<span>(</span>
{t.input.length > 10 && (
<span className="whitespace-nowrap">
input=[0x{t.input.slice(10)}]
</span>
)}
<span>)</span>
<span className="whitespace-nowrap">
({t.input.length > 10 && <>input=[0x{t.input.slice(10)}]</>})
</span>
</div>
</div>
{t.children && (
<div className="flex">
<div className={`w-10 ${last ? "" : "border-l"}`}></div>
<div className="space-y-3">
{t.children.map((tc, i, a) => (
<TraceItem
key={i}
t={tc}
txData={txData}
last={i === a.length - 1}
/>
))}
</div>
<div className={`pl-10 ${last ? "" : "border-l"} space-y-3`}>
{t.children.map((tc, i, a) => (
<TraceItem
key={i}
t={tc}
txData={txData}
last={i === a.length - 1}
fourBytesMap={fourBytesMap}
/>
))}
</div>
)}
</>

View File

@ -108,4 +108,4 @@ export type TokenMeta = {
decimals: number;
};
export type TokenMetas = Record<string, TokenMeta>;
export type TokenMetas = Record<string, TokenMeta | null | undefined>;

View File

@ -7,6 +7,8 @@ export type FourBytesEntry = {
signature: string | undefined;
};
export type FourBytesMap = Record<string, FourBytesEntry | null | undefined>;
const simpleTransfer: FourBytesEntry = {
name: "Transfer",
signature: undefined,
@ -14,8 +16,76 @@ const simpleTransfer: FourBytesEntry = {
const fullCache = new Map<string, FourBytesEntry | null>();
export const extract4Bytes = (rawInput: string): string | null => {
if (rawInput.length < 10) {
return null;
}
return rawInput.slice(0, 10);
};
export const rawInputTo4Bytes = (rawInput: string) => rawInput.slice(0, 10);
const fetch4Bytes = async (
assetsURLPrefix: string,
fourBytes: string
): Promise<FourBytesEntry | null> => {
const signatureURL = fourBytesURL(assetsURLPrefix, fourBytes);
try {
const res = await fetch(signatureURL);
if (!res.ok) {
console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`);
return null;
}
// Get only the first occurrence, for now ignore alternative param names
const sigs = await res.text();
const sig = sigs.split(";")[0];
const cut = sig.indexOf("(");
const method = sig.slice(0, cut);
const entry: FourBytesEntry = {
name: method,
signature: sig,
};
return entry;
} catch (err) {
console.error(`Couldn't fetch signature URL ${signatureURL}`, err);
return null;
}
};
export const useBatch4Bytes = (
rawFourByteSigs: string[] | undefined
): FourBytesMap => {
const runtime = useContext(RuntimeContext);
const assetsURLPrefix = runtime.config?.assetsURLPrefix;
const [fourBytesMap, setFourBytesMap] = useState<FourBytesMap>({});
useEffect(() => {
if (!rawFourByteSigs || !assetsURLPrefix) {
setFourBytesMap({});
return;
}
const loadSigs = async () => {
const promises = rawFourByteSigs.map((s) =>
fetch4Bytes(assetsURLPrefix, s.slice(2))
);
const results = await Promise.all(promises);
const _fourBytesMap: Record<string, FourBytesEntry | null> = {};
for (let i = 0; i < rawFourByteSigs.length; i++) {
_fourBytesMap[rawFourByteSigs[i]] = results[i];
}
setFourBytesMap(_fourBytesMap);
};
loadSigs();
}, [assetsURLPrefix, rawFourByteSigs]);
return fourBytesMap;
};
/**
* Extract 4bytes DB info
*
@ -47,34 +117,12 @@ export const use4Bytes = (
return;
}
const signatureURL = fourBytesURL(assetsURLPrefix, fourBytes);
fetch(signatureURL)
.then(async (res) => {
if (!res.ok) {
console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`);
fullCache.set(fourBytes, null);
setEntry(null);
return;
}
// Get only the first occurrence, for now ignore alternative param names
const sigs = await res.text();
const sig = sigs.split(";")[0];
const cut = sig.indexOf("(");
const method = sig.slice(0, cut);
const entry: FourBytesEntry = {
name: method,
signature: sig,
};
setEntry(entry);
fullCache.set(fourBytes, entry);
})
.catch((err) => {
console.error(`Couldn't fetch signature URL ${signatureURL}`, err);
setEntry(null);
fullCache.set(fourBytes, null);
});
const loadSig = async () => {
const entry = await fetch4Bytes(assetsURLPrefix, fourBytes);
fullCache.set(fourBytes, entry);
setEntry(entry);
};
loadSig();
}, [fourBytes, assetsURLPrefix]);
if (rawFourBytes === "0x") {

View File

@ -1,10 +1,11 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useMemo } from "react";
import { Block, BlockWithTransactions } from "@ethersproject/abstract-provider";
import { JsonRpcProvider } from "@ethersproject/providers";
import { getAddress } from "@ethersproject/address";
import { Contract } from "@ethersproject/contracts";
import { BigNumber } from "@ethersproject/bignumber";
import { arrayify, hexDataSlice, isHexString } from "@ethersproject/bytes";
import { extract4Bytes } from "./use4Bytes";
import { getInternalOperations } from "./nodeFunctions";
import {
TokenMetas,
@ -221,7 +222,7 @@ export const useTxData = (
// Extract token meta
const tokenMetas: TokenMetas = {};
for (const t of tokenTransfers) {
if (tokenMetas[t.token]) {
if (tokenMetas[t.token] !== undefined) {
continue;
}
const erc20Contract = new Contract(t.token, erc20, provider);
@ -237,6 +238,7 @@ export const useTxData = (
decimals,
};
} catch (err) {
tokenMetas[t.token] = null;
console.warn(`Couldn't get token ${t.token} metadata; ignoring`, err);
}
}
@ -398,3 +400,43 @@ export const useTraceTransaction = (
return traceGroups;
};
/**
* Flatten a trace tree and extract and dedup 4byte function signatures
*/
export const useUniqueSignatures = (traces: TraceGroup[] | undefined) => {
const uniqueSignatures = useMemo(() => {
if (!traces) {
return undefined;
}
const sigs = new Set<string>();
let nextTraces: TraceGroup[] = [...traces];
while (nextTraces.length > 0) {
const traces = nextTraces;
nextTraces = [];
for (const t of traces) {
if (
t.type === "CALL" ||
t.type === "DELEGATECALL" ||
t.type === "STATICCALL" ||
t.type === "CALLCODE"
) {
const fourBytes = extract4Bytes(t.input);
if (fourBytes) {
sigs.add(fourBytes);
}
}
if (t.children) {
nextTraces.push(...t.children);
}
}
}
return [...sigs];
}, [traces]);
return uniqueSignatures;
};

View File

@ -14,7 +14,8 @@
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
"jsx": "react-jsx",
"downlevelIteration": true
},
"include": ["src"]
}