2021-07-12 22:13:12 +00:00
|
|
|
import { useState, useEffect, useContext } from "react";
|
|
|
|
import { RuntimeContext } from "./useRuntime";
|
|
|
|
import { fourBytesURL } from "./url";
|
|
|
|
|
2021-07-13 05:19:33 +00:00
|
|
|
const cache = new Map<string, string | null>();
|
|
|
|
|
2021-07-13 05:36:09 +00:00
|
|
|
export const use4Bytes = (rawFourBytes: string) => {
|
2021-07-12 22:13:12 +00:00
|
|
|
const runtime = useContext(RuntimeContext);
|
2021-07-13 05:19:33 +00:00
|
|
|
const assetsURLPrefix = runtime.config?.assetsURLPrefix;
|
|
|
|
|
2021-07-12 22:13:12 +00:00
|
|
|
const [name, setName] = useState<string>();
|
2021-07-13 05:19:33 +00:00
|
|
|
const [fourBytes, setFourBytes] = useState<string>();
|
2021-07-12 22:13:12 +00:00
|
|
|
useEffect(() => {
|
2021-07-13 05:19:33 +00:00
|
|
|
if (assetsURLPrefix === undefined || fourBytes === undefined) {
|
2021-07-12 22:13:12 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-07-13 05:19:33 +00:00
|
|
|
const signatureURL = fourBytesURL(assetsURLPrefix, fourBytes);
|
2021-07-12 22:13:12 +00:00
|
|
|
fetch(signatureURL)
|
|
|
|
.then(async (res) => {
|
|
|
|
if (!res.ok) {
|
|
|
|
console.error(`Signature does not exist in 4bytes DB: ${fourBytes}`);
|
2021-07-13 05:19:33 +00:00
|
|
|
|
|
|
|
// Use the default 4 bytes as name
|
|
|
|
setName(rawFourBytes);
|
|
|
|
cache.set(fourBytes, null);
|
2021-07-12 22:13:12 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const sig = await res.text();
|
|
|
|
const cut = sig.indexOf("(");
|
|
|
|
let method = sig.slice(0, cut);
|
|
|
|
method = method.charAt(0).toUpperCase() + method.slice(1);
|
|
|
|
setName(method);
|
2021-07-13 05:19:33 +00:00
|
|
|
cache.set(fourBytes, method);
|
2021-07-12 22:13:12 +00:00
|
|
|
return;
|
|
|
|
})
|
|
|
|
.catch((err) => {
|
|
|
|
console.error(`Couldn't fetch signature URL ${signatureURL}`, err);
|
2021-07-13 05:19:33 +00:00
|
|
|
|
|
|
|
// Use the default 4 bytes as name
|
|
|
|
setName(rawFourBytes);
|
2021-07-12 22:13:12 +00:00
|
|
|
});
|
2021-07-13 05:19:33 +00:00
|
|
|
}, [rawFourBytes, assetsURLPrefix, fourBytes]);
|
|
|
|
|
2021-07-13 05:36:09 +00:00
|
|
|
if (rawFourBytes === "0x") {
|
2021-07-13 05:19:33 +00:00
|
|
|
return "Transfer";
|
|
|
|
}
|
|
|
|
if (assetsURLPrefix === undefined) {
|
|
|
|
return rawFourBytes;
|
|
|
|
}
|
2021-07-12 22:13:12 +00:00
|
|
|
|
2021-07-13 05:19:33 +00:00
|
|
|
// 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 "";
|
|
|
|
}
|
2021-07-12 22:13:12 +00:00
|
|
|
|
|
|
|
return name;
|
|
|
|
};
|