GraphProtocol: Read IPFS Data in Subgraph
Things to note
- It is required that the files which you're trying to read are pinned on the IPFS node that the Graph Node indexing the subgraph connects to. In the case of the hosted service, this is https://api.thegraph.com/ipfs/.
- The following method works if the IPFS hash is stored as bytes32 format only
- To convert IPFS Hash to/from bytes32, see this article
- For more info, read subgraph docs
Add the following in the top of subgraph manifest subgraph.yaml
# ...
features:
- ipfsOnEthereumContracts
# ...
Use the following function to get the data stored in IPFS as a string
import { Bytes, ByteArray, ipfs } from "@graphprotocol/graph-ts";
export function getDataFromIpfsHash(hash: Bytes): string {
const hashStr = hash.toHexString();
const hashHex = "1220" + hashStr.slice(2);
const ipfsHashBase58 = ByteArray.fromHexString(hashHex).toBase58();
const ipfsHash = ipfsHashBase58; // readable IPFS hash
let result = ipfs.cat(ipfsHashBase58);
if (!result) {
return "";
}
const ipfsBytes = result;
const ipfsData = ByteArray.fromHexString(result.toHexString()).toString();
return ipfsData
}
Last Updated on
Comments