From de690386d6b87bf6ac2889fc446bf8decd485f80 Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Mon, 30 Oct 2023 22:59:45 -0700 Subject: [PATCH] Fetch source code in addition to JSON metadata --- index.html | 18 +++++++++++++++++- index.js | 6 +++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index e0fead7..86310ba 100644 --- a/index.html +++ b/index.html @@ -220,6 +220,8 @@ const metadata = decodeCBOR(cbor); logOutput(result, '✅ Successfully decoded CBOR metadata.', JSON.stringify(metadata, null, 2)); + // Fetch JSON metadata + let json; if (metadata.bzzr0 !== undefined) { const hex = [...metadata.bzzr0].map(b => b.toString(16).padStart(2, '0')).join(''); logOutput(result, '❌ Unable to fetch JSON metadata because the smart contract uses a Swarm hash.', `bzzr://${hex}`); @@ -232,13 +234,27 @@ const { cidV0, cidV1 } = calculateCID(metadata); logOutput(result, '✅ Successfully calculated IPFS CID.', `IPFS CIDv0: ${cidV0}\nIPFS CIDv1: ${cidV1}`); try { - const json = await fetchJSONMetadata(cidV1, ipfs); + json = await fetchCID(cidV1, ipfs).then(r => r.json()); logOutput(result, '✅ Successfully fetched JSON metadata.', JSON.stringify(json, null, 2)); } catch { logOutput(result, '❌ Failed to fetch JSON metadata from IPFS.', `IPFS node: ${ipfs}`); } } + + // Fetch source code + if (json?.sources !== undefined) { + for (const [file, source] of Object.entries(json.sources)) { + try { + const cidV0 = source.urls[1].substring(11); + const code = await fetchCID(cidV0, ipfs).then(r => r.text()); + logOutput(result, `✅ Successfully fetched source code for "${file}" from IPFS.`, code); + } + catch { + logOutput(result, `❌ Failed to fetch source code for "${file}" from IPFS.`, `IPFS node: ${ipfs}`); + } + } + } } document.querySelector('form').addEventListener('submit', async e => { diff --git a/index.js b/index.js index 865677b..118ffa8 100644 --- a/index.js +++ b/index.js @@ -155,7 +155,7 @@ function calculateCID(metadata) { return { solcVersion, cidV0, cidV1 }; } -function fetchJSONMetadata(cid, ipfs) { +function fetchCID(cid, ipfs) { let response; if (cid[0] === 'Q') { // v0 response = fetch(`${ipfs.origin}/ipfs/${cid}${ipfs.search}`); @@ -168,7 +168,7 @@ function fetchJSONMetadata(cid, ipfs) { response = fetch(`${ipfs.protocol}//${cid}.ipfs.${ipfs.host}${ipfs.pathname}${ipfs.search}`); } } - return response.then(r => r.json()); + return response; } -export { fetchBytecode, extractCBOR, decodeCBOR, calculateCID, fetchJSONMetadata }; +export { fetchBytecode, extractCBOR, decodeCBOR, calculateCID, fetchCID }; -- 2.47.3