0

Im writing a function in solidity where the user enters a CID from an IPFS link, which looks like:

 QmcQvCyLAncpEzvmYtKfvVPVayGqFvTQrYpUpPAJeoXGke

So far im using string type, and it works.

Which is the correct and most efficient type for a CID? (int / uint?, bytes? )

 function storeCID(string memory cid) public returns (uint256){

// some login here...

               
    }

2 Answers 2

1

I would say usually string. I think in terms of most efficient storage wise, converting it all the way into bytes would yield the lowest storage cost. Since IPFS cant be accessed through contracts though, it doesn't matter a ton. If the storage cost matters a lot to you depends a lot on your application and what you are doing with them. A lot of time, you will reconstruct the ipfs link using a prefix/suffix plus the content identifier.

In short, storing them as strings make them much easier for people to work with, but if you needed as much storage efficiency as possible for some reason, in theory converting the value to bytes would probably yield the lowest storage amount.

1
  • Thanks for your answer. Ok, so in my case it would be more efficient to use bytes as Im just storing CIDs. Then I build the full links from server/client...
    – Xunorus
    Nov 17, 2022 at 17:41
0

You can store it as bytes32 type, thats the most efficient way.

import bs58 from "bs58";

// Return bytes32 hex string from base58 encoded ipfs hash,
// stripping leading 2 bytes from 34 byte IPFS hash
// Assume IPFS defaults: function:0x12=sha2, size:0x20=256 bits
// E.g. "QmNSUYVKDSvPUnRLKmuxk9diJ6yS96r1TrAXzjTiBcCLAL" -->
// "0x017dfd85d4f6cb4dcd715a88101f7b1f06cd1e009b2327a0809d01eb9c91f231"
const toHexString = (byteArray: Uint8Array) => {
return Array.prototype.map
 .call(byteArray, function (byte) {
   return ("0" + (byte & 0xff).toString(16)).slice(-2);
 })
 .join("");
};
export const getBytes32FromIpfsHash = (ipfsListing: string) => {
return "0x" + toHexString(bs58.decode(ipfsListing).slice(2));
};

// Return base58 encoded ipfs hash from bytes32 hex string,
// E.g. "0x017dfd85d4f6cb4dcd715a88101f7b1f06cd1e009b2327a0809d01eb9c91f231"
// --> "QmNSUYVKDSvPUnRLKmuxk9diJ6yS96r1TrAXzjTiBcCLAL"

export const getIpfsHashFromBytes32 = (bytes32Hex: string) => {
// Add our default ipfs values for first 2 bytes:
// function:0x12=sha2, size:0x20=256 bits
// and cut off leading "0x"
const hashHex = "1220" + bytes32Hex.slice(2);
const hashBytes = Buffer.from(hashHex, "hex");
const hashStr = bs58.encode(hashBytes);
return hashStr;
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.