Add global method name cache

This commit is contained in:
Willian Mitsuda 2021-07-13 02:19:33 -03:00
parent 7f39ba5232
commit 9128973a9b

View File

@ -2,31 +2,30 @@ import { useState, useEffect, useContext } from "react";
import { RuntimeContext } from "./useRuntime"; import { RuntimeContext } from "./useRuntime";
import { fourBytesURL } from "./url"; import { fourBytesURL } from "./url";
const cache = new Map<string, string | null>();
export const use4Bytes = (data: string) => { export const use4Bytes = (data: string) => {
const runtime = useContext(RuntimeContext); const runtime = useContext(RuntimeContext);
const assetsURLPrefix = runtime.config?.assetsURLPrefix;
let rawFourBytes = data.slice(0, 10);
const [name, setName] = useState<string>(); const [name, setName] = useState<string>();
const [fourBytes, setFourBytes] = useState<string>();
useEffect(() => { useEffect(() => {
if (data === "0x") { if (assetsURLPrefix === undefined || fourBytes === undefined) {
setName("Transfer");
return; return;
} }
let _name = data.slice(0, 10); const signatureURL = fourBytesURL(assetsURLPrefix, fourBytes);
// Try to resolve 4bytes name
const fourBytes = _name.slice(2);
const { config } = runtime;
if (!config) {
setName(_name);
return;
}
const signatureURL = fourBytesURL(config.assetsURLPrefix ?? "", fourBytes);
fetch(signatureURL) fetch(signatureURL)
.then(async (res) => { .then(async (res) => {
if (!res.ok) { if (!res.ok) {
console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`); console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`);
// Use the default 4 bytes as name
setName(rawFourBytes);
cache.set(fourBytes, null);
return; return;
} }
@ -35,15 +34,39 @@ export const use4Bytes = (data: string) => {
let method = sig.slice(0, cut); let method = sig.slice(0, cut);
method = method.charAt(0).toUpperCase() + method.slice(1); method = method.charAt(0).toUpperCase() + method.slice(1);
setName(method); setName(method);
cache.set(fourBytes, method);
return; return;
}) })
.catch((err) => { .catch((err) => {
console.error(`Couldn't fetch signature URL ${signatureURL}`, err); console.error(`Couldn't fetch signature URL ${signatureURL}`, err);
});
// Use the default 4 bytes as name // Use the default 4 bytes as name
setName(_name); setName(rawFourBytes);
}, [runtime, data]); });
}, [rawFourBytes, assetsURLPrefix, fourBytes]);
if (data === "0x") {
return "Transfer";
}
if (assetsURLPrefix === undefined) {
return rawFourBytes;
}
// 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);
return entry;
}
if (name === undefined && fourBytes === undefined) {
setFourBytes(rawFourBytes.slice(2));
return "";
}
return name; return name;
}; };