Hi @novaknole, I’ve added basic docs in docs: cid conversion by lidel · Pull Request #734 · ipfs/ipfs-docs · GitHub but posting below in case there are follow-up questions. Hopefully this will help reduce complexity of your code.
CID itself should provide you with everything you need. You can represent it as text or binary.
CIDv1 in the text representation is self-describing and includes info about base encoding,:
In case of smart contract you describe, binary representation indeed makes more sense.
In JS you can leverage the
cids library to normalize any v0 to v1 and extract raw bytes as Uint8Array from the entire CIDv1:
let cid = new CID('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi').toV1()
const binaryCid = cid.bytes
Those are the bytes after the multibase prefix (it is only present in the text form). See cid spec for more details.
I suggest including explicit normalization step via
.toV1() because it removes any ambiguity when older CIDv0 is used, and you only worry about supporting v1 in your codebase (which will become default soon).
Be mindful that if CID comes from a third party, it can use custom hashing function and the length may vary – your code responsible for storing binary representation should account for that.
PS. If you really want CID as HEX (eg. to show in this for for debug), you can either convert
Uint8Array) to HEX by hand, or… (this one is bit silly, but fun) use built-in support for
base16 encoding and skip the
f (multibase prefix):
'01701220c3c4733ec8affd06cf9e9ff50ffc6bcd2ec85a6170004bb709669c31de94391a' // "cid as hex"
If you want to convert such HEX to a valid CID, prepend it with
f (if all lowercase) or
F (if all uppercase). You can also use
cids lib for converting it to
base32 to get the original text representation (does not matter in practice, both point at the same multihash)