All articles
blockchain

Store IPFS Hash as Bytes32 in Smart Contracts

Share this article

Share on LinkedIn Share on X (formerly Twitter)

Convert IPFS Hash to bytes32 format

If you are using bs58 version 4.0.0, do the following

const bs58 = require('bs58'); // version - `4.0.0`
 
const hash = 'Qmc5gCcjYypU7y28oCALwfSvxCBskLuPKWpK4qpterKC7z';
const toBytes32 = (hash) => '0x' + bs58.decode(hash).slice(2).toString('hex');
 
console.log(toBytes32(hash)); // "0xcc2d976220820d023b7170f520d3490e811ed988ae3d6221474ee97e559b0361"

If you are using bs58 version 5.0.0, do the following

const bs58 = require('bs58'); // version - `5.0.0`
 
const hash = 'Qmc5gCcjYypU7y28oCALwfSvxCBskLuPKWpK4qpterKC7z';
const toBytes32 = (hash) => {
  return (
    '0x' +
    bs58
      .decode(hash)
      .slice(2)
      .toString()
      .split(',')
      .map((x) => Number(x).toString(16))
      .map((x) => String(x).padStart(2, '0'))
      .join('')
  );
};
 
console.log(toBytes32(hash)); // "0xcc2d976220820d023b7170f520d3490e811ed988ae3d6221474ee97e559b0361"

Or you can instead use Buffer which is available in NodeJS environment

const bs58 = require('bs58'); // version - `5.0.0`
 
const hash = 'Qmc5gCcjYypU7y28oCALwfSvxCBskLuPKWpK4qpterKC7z';
const toBytes32 = (hash) => {
  return '0x' + Buffer.from(bs58.decode(hash).slice(2)).toString('hex');
};
 
console.log(toBytes32(hash)); // "0xcc2d976220820d023b7170f520d3490e811ed988ae3d6221474ee97e559b0361"

Convert bytes32 to IPFS Hash format

If you are using bs58 version 5.0.0 or 4.0.0, do the following

const bs58 = require('bs58'); // version - `5.0.0` or `4.0.0`
 
const hashBytes32 = '0xcc2d976220820d023b7170f520d3490e811ed988ae3d6221474ee97e559b0361';
const fromBytes32 = (bytes32) => bs58.encode(Buffer.from('1220' + bytes32.slice(2), 'hex'));
 
console.log(fromBytes32(hashBytes32)); // "Qmc5gCcjYypU7y28oCALwfSvxCBskLuPKWpK4qpterKC7z"

Comments