From 50ac6f7a3e612081533b1b9caebeb81daec34d2d Mon Sep 17 00:00:00 2001 From: Willian Mitsuda Date: Tue, 9 Aug 2022 01:50:38 -0300 Subject: [PATCH] Extract swr fetcher --- src/use4Bytes.ts | 59 +++++++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/src/use4Bytes.ts b/src/use4Bytes.ts index 85f4e98..ddf8e2b 100644 --- a/src/use4Bytes.ts +++ b/src/use4Bytes.ts @@ -5,6 +5,7 @@ import { TransactionDescription, } from "@ethersproject/abi"; import { BigNumberish } from "@ethersproject/bignumber"; +import { Fetcher } from "swr"; import useSWRImmutable from "swr/immutable"; import { RuntimeContext } from "./useRuntime"; import { fourBytesURL } from "./url"; @@ -29,16 +30,32 @@ export const extract4Bytes = (rawInput: string): string | null => { return rawInput.slice(0, 10); }; -const fetch4Bytes = async ( - assetsURLPrefix: string, - fourBytes: string -): Promise => { - const signatureURL = fourBytesURL(assetsURLPrefix, fourBytes); +type FourBytesKey = [id: "4bytes", fourBytes: string]; +type FourBytesFetcher = Fetcher< + FourBytesEntry | null | undefined, + FourBytesKey +>; + +const fourBytesFetcher = + (assetsURLPrefix: string): FourBytesFetcher => + async (_, key) => { + if (key === null || key === "0x") { + return undefined; + } + + // Handle simple transfers with invalid selector like tx: + // 0x8bcbdcc1589b5c34c1e55909c8269a411f0267a4fed59a73dd4348cc71addbb9, + // which contains 0x00 as data + if (key.length !== 10) { + return undefined; + } + + const fourBytes = key.slice(2); + const signatureURL = fourBytesURL(assetsURLPrefix, fourBytes); - try { const res = await fetch(signatureURL); if (!res.ok) { - console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`); + console.warn(`Signature does not exist in 4bytes DB: ${fourBytes}`); return null; } @@ -53,11 +70,7 @@ const fetch4Bytes = async ( signature: sig, }; return entry; - } catch (err) { - console.error(`Couldn't fetch signature URL ${signatureURL}`, err); - return null; - } -}; + }; /** * Extract 4bytes DB info @@ -75,26 +88,10 @@ export const use4Bytes = ( const { config } = useContext(RuntimeContext); const assetsURLPrefix = config?.assetsURLPrefix; + const fourBytesKey = assetsURLPrefix !== undefined ? rawFourBytes : null; - const fourBytesFetcher = (key: string | null) => { - if (key === null || key === "0x") { - return undefined; - } - - // Handle simple transfers with invalid selector like tx: - // 0x8bcbdcc1589b5c34c1e55909c8269a411f0267a4fed59a73dd4348cc71addbb9, - // which contains 0x00 as data - if (key.length !== 10) { - return undefined; - } - - return fetch4Bytes(assetsURLPrefix!, key.slice(2)); - }; - - const { data, error } = useSWRImmutable( - assetsURLPrefix !== undefined ? rawFourBytes : null, - fourBytesFetcher - ); + const fetcher = fourBytesFetcher(assetsURLPrefix!); + const { data, error } = useSWRImmutable(["4bytes", fourBytesKey], fetcher); return error ? undefined : data; };