Merge branch 'feature/4bytes-decoding' into develop

This commit is contained in:
Willian Mitsuda 2021-09-27 15:50:46 -03:00
commit 8f8bef7471
17 changed files with 341 additions and 138 deletions

View File

@ -2,5 +2,6 @@
node_modules
4bytes
!4bytes/signatures
!4bytes/with_parameter_names
trustwallet
!trustwallet/blockchains/ethereum/assets

View File

@ -14,9 +14,14 @@ WORKDIR /assets
COPY trustwallet/blockchains/ethereum/assets /assets/
RUN find . -name logo.png | parallel magick convert {} -filter Lanczos -resize 32x32 {}
FROM alpine:3.14.0 AS fourbytesbuilder
WORKDIR /signatures
COPY 4bytes/signatures /signatures/
COPY 4bytes/with_parameter_names /signatures/
FROM nginx:1.21.1-alpine
RUN apk add jq
COPY 4bytes/signatures /usr/share/nginx/html/signatures/
COPY --from=fourbytesbuilder /signatures /usr/share/nginx/html/signatures/
COPY --from=logobuilder /assets /usr/share/nginx/html/assets/
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /otterscan-build/build /usr/share/nginx/html/

View File

@ -53,6 +53,7 @@
"eject": "react-scripts eject",
"source-map-explorer": "source-map-explorer build/static/js/*.js",
"assets-start": "docker run --rm -p 3001:80 --name otterscan-assets -d -v$(pwd)/4bytes/signatures:/usr/share/nginx/html/signatures/ -v$(pwd)/trustwallet/blockchains/ethereum/assets:/usr/share/nginx/html/assets -v$(pwd)/nginx.conf:/etc/nginx/conf.d/default.conf nginx:1.21.1-alpine",
"assets-start-with-param-names": "docker run --rm -p 3001:80 --name otterscan-assets -d -v$(pwd)/4bytes/with_parameter_names:/usr/share/nginx/html/signatures/ -v$(pwd)/trustwallet/blockchains/ethereum/assets:/usr/share/nginx/html/assets -v$(pwd)/nginx.conf:/etc/nginx/conf.d/default.conf nginx:1.21.1-alpine",
"assets-stop": "docker stop otterscan-assets",
"docker-build": "DOCKER_BUILDKIT=1 docker build -t otterscan -f Dockerfile .",
"docker-start": "docker run --rm -p 5000:80 --name otterscan -d otterscan",

View File

@ -7,7 +7,7 @@ import DecoratedAddressLink from "./components/DecoratedAddressLink";
import FormattedBalance from "./components/FormattedBalance";
import {
AddressContext,
TokenMetas,
TokenMeta,
TokenTransfer,
TransactionData,
} from "./types";
@ -15,14 +15,14 @@ import {
type TokenTransferItemProps = {
t: TokenTransfer;
txData: TransactionData;
tokenMetas: TokenMetas;
tokenMeta?: TokenMeta | undefined;
};
// TODO: handle partial
const TokenTransferItem: React.FC<TokenTransferItemProps> = ({
t,
txData,
tokenMetas,
tokenMeta,
}) => (
<div className="flex items-baseline space-x-2 px-2 py-1 truncate hover:bg-gray-100">
<span className="text-gray-500">
@ -57,7 +57,7 @@ const TokenTransferItem: React.FC<TokenTransferItemProps> = ({
<ValueHighlighter value={t.value}>
<FormattedBalance
value={t.value}
decimals={tokenMetas[t.token].decimals}
decimals={tokenMeta?.decimals ?? 0}
/>
</ValueHighlighter>
</span>
@ -65,11 +65,9 @@ const TokenTransferItem: React.FC<TokenTransferItemProps> = ({
<DecoratedAddressLink
address={t.token}
text={
tokenMetas[t.token]
? `${tokenMetas[t.token].name} (${tokenMetas[t.token].symbol})`
: ""
tokenMeta ? `${tokenMeta.name} (${tokenMeta.symbol})` : undefined
}
tokenMeta={tokenMetas[t.token]}
tokenMeta={tokenMeta}
/>
</AddressHighlighter>
</div>

View File

@ -1,14 +1,15 @@
import React from "react";
import { use4Bytes } from "../use4Bytes";
import { rawInputTo4Bytes, use4Bytes } from "../use4Bytes";
type MethodNameProps = {
data: string;
};
const MethodName: React.FC<MethodNameProps> = ({ data }) => {
const rawFourBytes = data.slice(0, 10);
const methodName = use4Bytes(rawFourBytes);
const isSimpleTransfer = data === "0x";
const rawFourBytes = rawInputTo4Bytes(data);
const fourBytesEntry = use4Bytes(rawFourBytes);
const methodName = fourBytesEntry?.name ?? rawFourBytes;
const isSimpleTransfer = rawFourBytes === "0x";
const methodTitle = isSimpleTransfer
? "ETH Transfer"
: methodName === rawFourBytes

View File

@ -1,79 +0,0 @@
import React from "react";
import AddressHighlighter from "../components/AddressHighlighter";
import DecoratedAddressLink from "../components/DecoratedAddressLink";
import Copy from "../components/Copy";
import { ParamType } from "@ethersproject/abi";
import { TransactionData } from "../types";
type DecodedParamRowProps = {
prefix?: string;
i?: number | undefined;
r: any;
paramType: ParamType;
txData: TransactionData;
};
const DecodedParamRow: React.FC<DecodedParamRowProps> = ({
prefix,
i,
r,
paramType,
txData,
}) => {
return (
<>
<tr className="grid grid-cols-12 gap-x-2 py-2 hover:bg-gray-100">
<td className="col-span-3 pl-1">
{prefix && <span className="text-gray-300">{prefix}</span>}
{paramType.name}{" "}
{i !== undefined && (
<span className="text-gray-400 text-xs">({i})</span>
)}
</td>
<td className="col-span-1 text-gray-500">{paramType.type}</td>
<td className="col-span-8 pr-1 font-code break-all">
{paramType.baseType === "address" ? (
<div className="flex items-baseline space-x-2 -ml-1 mr-3">
<AddressHighlighter address={r.toString()}>
<DecoratedAddressLink
address={r.toString()}
miner={r.toString() === txData.confirmedData?.miner}
txFrom={r.toString() === txData.from}
txTo={r.toString() === txData.to}
/>
</AddressHighlighter>
<Copy value={r.toString()} />
</div>
) : paramType.baseType === "bool" ? (
<span className={`${r ? "text-green-700" : "text-red-700"}`}>
{r.toString()}
</span>
) : paramType.baseType === "bytes" ? (
<span>
{r.toString()}{" "}
<span className="font-sans text-xs text-gray-400">
{r.toString().length / 2 - 1}{" "}
{r.toString().length / 2 - 1 === 1 ? "byte" : "bytes"}
</span>
</span>
) : paramType.baseType === "tuple" ? (
<></>
) : (
r.toString()
)}
</td>
</tr>
{paramType.baseType === "tuple" &&
r.map((e: any, idx: number) => (
<DecodedParamRow key={idx}
prefix={paramType.name + "."}
r={e}
paramType={paramType.components[idx]}
txData={txData}
/>
))}
</>
);
};
export default React.memo(DecodedParamRow);

View File

@ -1,5 +1,9 @@
import React, { useMemo } from "react";
import { TransactionDescription } from "@ethersproject/abi";
import {
TransactionDescription,
Fragment,
Interface,
} from "@ethersproject/abi";
import { BigNumber } from "@ethersproject/bignumber";
import { toUtf8String } from "@ethersproject/strings";
import { Tab } from "@headlessui/react";
@ -31,7 +35,8 @@ import ExternalLink from "../components/ExternalLink";
import RelativePosition from "../components/RelativePosition";
import PercentagePosition from "../components/PercentagePosition";
import ModeTab from "../components/ModeTab";
import DecodedParamsTable from "./DecodedParamsTable";
import DecodedParamsTable from "./decoder/DecodedParamsTable";
import { rawInputTo4Bytes, use4Bytes } from "../use4Bytes";
type DetailsProps = {
txData: TransactionData;
@ -62,6 +67,20 @@ const Details: React.FC<DetailsProps> = ({
}
}, [txData]);
const fourBytes = rawInputTo4Bytes(txData.data);
const fourBytesEntry = use4Bytes(fourBytes);
const fourBytesTxDesc = useMemo(() => {
if (!txData || !fourBytesEntry?.signature) {
return undefined;
}
const sig = fourBytesEntry?.signature;
const functionFragment = Fragment.fromString(`function ${sig}`);
const intf = new Interface([functionFragment]);
return intf.parseTransaction({ data: txData.data, value: txData.value });
}, [txData, fourBytesEntry]);
const resolvedTxDesc = txDesc ?? fourBytesTxDesc;
return (
<ContentFrame tabs>
<InfoRow title="Transaction Hash">
@ -187,7 +206,7 @@ const Details: React.FC<DetailsProps> = ({
key={i}
t={t}
txData={txData}
tokenMetas={txData.tokenMetas}
tokenMeta={txData.tokenMetas[t.token]}
/>
))}
</div>
@ -322,15 +341,18 @@ const Details: React.FC<DetailsProps> = ({
</Tab.List>
<Tab.Panels>
<Tab.Panel>
{txDesc === undefined ? (
{fourBytes === "0x" ? (
<>No parameters</>
) : resolvedTxDesc === undefined ? (
<>Waiting for data...</>
) : txDesc === null ? (
) : resolvedTxDesc === null ? (
<>No decoded data</>
) : (
<DecodedParamsTable
args={txDesc.args}
paramTypes={txDesc.functionFragment.inputs}
args={resolvedTxDesc.args}
paramTypes={resolvedTxDesc.functionFragment.inputs}
txData={txData}
hasParamNames={resolvedTxDesc === txDesc}
/>
)}
</Tab.Panel>

View File

@ -6,8 +6,8 @@ import AddressHighlighter from "../components/AddressHighlighter";
import DecoratedAddressLink from "../components/DecoratedAddressLink";
import Copy from "../components/Copy";
import ModeTab from "../components/ModeTab";
import DecodedParamsTable from "./DecodedParamsTable";
import DecodedLogSignature from "./DecodedLogSignature";
import DecodedParamsTable from "./decoder/DecodedParamsTable";
import DecodedLogSignature from "./decoder/DecodedLogSignature";
import { TransactionData } from "../types";
type LogEntryProps = {

View File

@ -0,0 +1,26 @@
import React from "react";
import AddressHighlighter from "../../components/AddressHighlighter";
import DecoratedAddressLink from "../../components/DecoratedAddressLink";
import Copy from "../../components/Copy";
import { TransactionData } from "../../types";
type AddressDecoderProps = {
r: any;
txData: TransactionData;
};
const AddressDecoder: React.FC<AddressDecoderProps> = ({ r, txData }) => (
<div className="flex items-baseline space-x-2 -ml-1 mr-3">
<AddressHighlighter address={r.toString()}>
<DecoratedAddressLink
address={r.toString()}
miner={r.toString() === txData.confirmedData?.miner}
txFrom={r.toString() === txData.from}
txTo={r.toString() === txData.to}
/>
</AddressHighlighter>
<Copy value={r.toString()} />
</div>
);
export default React.memo(AddressDecoder);

View File

@ -0,0 +1,13 @@
import React from "react";
type BooleanDecoderProps = {
r: any;
};
const BooleanDecoder: React.FC<BooleanDecoderProps> = ({ r }) => (
<span className={`${r ? "text-green-700" : "text-red-700"}`}>
{r.toString()}
</span>
);
export default React.memo(BooleanDecoder);

View File

@ -0,0 +1,17 @@
import React from "react";
type BytesDecoderProps = {
r: any;
};
const BytesDecoder: React.FC<BytesDecoderProps> = ({ r }) => (
<span>
{r.toString()}{" "}
<span className="font-sans text-xs text-gray-400">
{r.toString().length / 2 - 1}{" "}
{r.toString().length / 2 - 1 === 1 ? "byte" : "bytes"}
</span>
</span>
);
export default React.memo(BytesDecoder);

View File

@ -0,0 +1,92 @@
import React, { ReactNode } from "react";
import { ParamType } from "@ethersproject/abi";
import Uint256Decoder from "./Uint256Decoder";
import AddressDecoder from "./AddressDecoder";
import BooleanDecoder from "./BooleanDecoder";
import BytesDecoder from "./BytesDecoder";
import { TransactionData } from "../../types";
type DecodedParamRowProps = {
prefix?: ReactNode;
i?: number | undefined;
r: any;
paramType: ParamType;
txData: TransactionData;
arrayElem?: number | undefined;
};
const DecodedParamRow: React.FC<DecodedParamRowProps> = ({
prefix,
i,
r,
paramType,
txData,
arrayElem,
}) => (
<>
<tr className="grid grid-cols-12 gap-x-2 py-2 hover:bg-gray-100">
<td className="col-span-3 pl-1">
{prefix && <span className="text-gray-300">{prefix}</span>}
{arrayElem !== undefined ? (
<span className="text-gray-400">
{" "}
[<span className="text-black">{arrayElem}</span>]
</span>
) : (
<>
{paramType.name ?? <span className="italic">param_{i}</span>}{" "}
{i !== undefined && (
<span className="text-gray-400 text-xs">({i})</span>
)}
</>
)}
</td>
<td className="col-span-1 text-gray-500">{paramType.type}</td>
<td className="col-span-8 pr-1 font-code break-all">
{paramType.baseType === "uint256" ? (
<Uint256Decoder r={r} />
) : paramType.baseType === "address" ? (
<AddressDecoder r={r} txData={txData} />
) : paramType.baseType === "bool" ? (
<BooleanDecoder r={r} />
) : paramType.baseType === "bytes" ? (
<BytesDecoder r={r} />
) : paramType.baseType === "tuple" || paramType.baseType === "array" ? (
<></>
) : (
r.toString()
)}
</td>
</tr>
{paramType.baseType === "tuple" &&
r.map((e: any, idx: number) => (
<DecodedParamRow
key={idx}
prefix={
paramType.name ? (
paramType.name + "."
) : (
<span className="italic">param_{i}.</span>
)
}
i={idx}
r={e}
paramType={paramType.components[idx]}
txData={txData}
/>
))}
{paramType.baseType === "array" &&
r.map((e: any, idx: number) => (
<DecodedParamRow
key={idx}
prefix={paramType.name ?? <span className="italic">param_{i}</span>}
r={e}
paramType={paramType.arrayChildren}
txData={txData}
arrayElem={idx}
/>
))}
</>
);
export default React.memo(DecodedParamRow);

View File

@ -1,20 +1,22 @@
import React from "react";
import { ParamType, Result } from "@ethersproject/abi";
import DecodedParamRow from "./DecodedParamRow";
import { TransactionData } from "../types";
import { TransactionData } from "../../types";
type DecodedParamsTableProps = {
args: Result;
paramTypes: ParamType[];
txData: TransactionData;
hasParamNames?: boolean;
};
const DecodedParamsTable: React.FC<DecodedParamsTableProps> = ({
args,
paramTypes,
txData,
hasParamNames = true,
}) => (
<table className="border rounded w-full">
<table className="border w-full">
<thead>
<tr className="grid grid-cols-12 text-left gap-x-2 py-2 bg-gray-100">
<th className="col-span-3 pl-1">
@ -23,6 +25,15 @@ const DecodedParamsTable: React.FC<DecodedParamsTableProps> = ({
<th className="col-span-1">type</th>
<th className="col-span-8 pr-1">value</th>
</tr>
{!hasParamNames && (
<tr className="grid grid-cols-12 text-left gap-x-2 py-2 bg-yellow-100 text-red-700">
<th className="col-span-12 px-1">
{paramTypes.length > 0 && paramTypes[0].name !== null
? "Parameter names are estimated."
: "Parameter names are not available."}
</th>
</tr>
)}
</thead>
<tbody className="divide-y">
{args.map((r, i) => (

View File

@ -0,0 +1,69 @@
import React, { useState } from "react";
import { BigNumber } from "@ethersproject/bignumber";
import { hexlify, hexZeroPad } from "@ethersproject/bytes";
import { commify, formatEther } from "@ethersproject/units";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSync } from "@fortawesome/free-solid-svg-icons/faSync";
type Uint256DecoderProps = {
r: any;
};
enum DisplayMode {
RAW,
EIGHTEEN_DECIMALS,
HEX,
_LAST,
}
const VERY_BIG_NUMBER = BigNumber.from(10).pow(BigNumber.from(36));
const initDisplayMode = (r: any): DisplayMode => {
const n = BigNumber.from(r);
if (n.gte(VERY_BIG_NUMBER)) {
return DisplayMode.HEX;
}
return DisplayMode.RAW;
};
const Uint256Decoder: React.FC<Uint256DecoderProps> = ({ r }) => {
const [displayMode, setDisplayMode] = useState<DisplayMode>(
initDisplayMode(r)
);
const toggleModes = () => {
const next = displayMode + 1;
setDisplayMode(next === DisplayMode._LAST ? 0 : next);
};
return (
<div className="flex items-baseline space-x-2">
<button
className="flex items-baseline space-x-2 rounded-lg bg-gray-50 text-gray-300 hover:text-gray-500 font-sans text-xs px-3 py-1 min-w-max"
onClick={toggleModes}
>
<div>
<FontAwesomeIcon icon={faSync} size="1x" />
</div>
<span>
{displayMode === DisplayMode.RAW
? "Raw"
: displayMode === DisplayMode.HEX
? "Hex"
: "18 dec"}
</span>
</button>
<span>
{displayMode === DisplayMode.RAW ? (
<>{commify(r.toString())}</>
) : displayMode === DisplayMode.HEX ? (
<>{hexZeroPad(hexlify(r), 32)}</>
) : (
<>{commify(formatEther(r))}</>
)}
</span>
</div>
);
};
export default React.memo(Uint256Decoder);

View File

@ -108,6 +108,4 @@ export type TokenMeta = {
decimals: number;
};
export type TokenMetas = {
[tokenAddress: string]: TokenMeta;
};
export type TokenMetas = Record<string, TokenMeta>;

View File

@ -2,16 +2,48 @@ import { useState, useEffect, useContext } from "react";
import { RuntimeContext } from "./useRuntime";
import { fourBytesURL } from "./url";
const cache = new Map<string, string | null>();
export type FourBytesEntry = {
name: string;
signature: string | undefined;
};
const simpleTransfer: FourBytesEntry = {
name: "Transfer",
signature: undefined,
};
const fullCache = new Map<string, FourBytesEntry | null>();
export const rawInputTo4Bytes = (rawInput: string) => rawInput.slice(0, 10);
/**
* Extract 4bytes DB info
*
* @param rawFourBytes an hex string containing the 4bytes signature in the "0xXXXXXXXX" format.
*/
export const use4Bytes = (
rawFourBytes: string
): FourBytesEntry | null | undefined => {
if (rawFourBytes !== "0x") {
if (rawFourBytes.length !== 10 || !rawFourBytes.startsWith("0x")) {
throw new Error(
`rawFourBytes must contain a 4 bytes hex method signature starting with 0x; received value: "${rawFourBytes}"`
);
}
}
export const use4Bytes = (rawFourBytes: string) => {
const runtime = useContext(RuntimeContext);
const assetsURLPrefix = runtime.config?.assetsURLPrefix;
const [name, setName] = useState<string>();
const [fourBytes, setFourBytes] = useState<string>();
const fourBytes = rawFourBytes.slice(2);
const [entry, setEntry] = useState<FourBytesEntry | null | undefined>(
fullCache.get(fourBytes)
);
useEffect(() => {
if (assetsURLPrefix === undefined || fourBytes === undefined) {
if (assetsURLPrefix === undefined) {
return;
}
if (fourBytes === "") {
return;
}
@ -20,51 +52,47 @@ export const use4Bytes = (rawFourBytes: string) => {
.then(async (res) => {
if (!res.ok) {
console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`);
// Use the default 4 bytes as name
setName(rawFourBytes);
cache.set(fourBytes, null);
fullCache.set(fourBytes, null);
setEntry(null);
return;
}
const sig = await res.text();
// 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("(");
let method = sig.slice(0, cut);
method = method.charAt(0).toUpperCase() + method.slice(1);
setName(method);
cache.set(fourBytes, method);
return;
const entry: FourBytesEntry = {
name: method,
signature: sig,
};
setEntry(entry);
fullCache.set(fourBytes, entry);
})
.catch((err) => {
console.error(`Couldn't fetch signature URL ${signatureURL}`, err);
// Use the default 4 bytes as name
setName(rawFourBytes);
setEntry(null);
fullCache.set(fourBytes, null);
});
}, [rawFourBytes, assetsURLPrefix, fourBytes]);
}, [fourBytes, assetsURLPrefix]);
if (rawFourBytes === "0x") {
return "Transfer";
return simpleTransfer;
}
if (assetsURLPrefix === undefined) {
return rawFourBytes;
return undefined;
}
// Try to resolve 4bytes name
const entry = cache.get(rawFourBytes.slice(2));
if (entry === null) {
return rawFourBytes;
}
if (entry !== undefined) {
// Simulates LRU
cache.delete(entry);
cache.set(rawFourBytes.slice(2), entry);
if (entry === null || entry === undefined) {
return entry;
}
if (name === undefined && fourBytes === undefined) {
setFourBytes(rawFourBytes.slice(2));
return "";
}
return name;
// Simulates LRU
// TODO: implement LRU purging
fullCache.delete(fourBytes);
fullCache.set(fourBytes, entry);
return entry;
};