How to Upload Files on IPFS using Solana?

Introduction

Uploading files to the InterPlanetary File System (IPFS) using Solana typically involves a few steps. You must upload your files to IPFS and then store the resulting IPFS hash on the Solana blockchain. Here's a detailed step on how to achieve this.

Solana

Upload Files to IPFS

You can use various tools and libraries to upload files to IPFS, such as IPFS Command Line Interface (CLI), Pinata, or NFT.Storage. Here we'll use Pinata.

Step 1. Create an Account on Pinata

  1. Go to Pinata and create an account.
  2. Verify and log in to your account.

You can either directly upload on the website and get the IPFS hash or can do this by code.

To get hash from the site, click the Upload button and upload the image or file. Once your file is uploaded, you can copy the hash.

Upload button

Or, you can also do this by code by following the below steps.

Step 2. Get API Keys

After logging in, go to the "API Keys" section. Initially, here we do not have any API Key.

Get API Keys

Click on the New Key, add the key name, and choose the scope and pinning according to your needs. And click on Generate API Key.

 New Key

And now our API key is generated. Copy All and save it somewhere.

Copy All

Step 3. Install Pinata SDK

If you're using Node.js, you can install the Pinata SDK.

npm install @pinata/sdk

Step 4. Upload a File using Pinata SDK

Create a Use the following Node.js script to upload a file to IPFS.

const pinataSDK = require('@pinata/sdk');
const fs = require('fs');
const pinata = pinataSDK('yourPinataApiKey', 'yourPinataApiSecret');

const readableStreamForFile = fs.createReadStream('path/to/your/file');
const options = {
     pinataMetadata: {
        name: 'MyFile'
      },
      pinataOptions: {
        cidVersion: 0
     }
};

pinata.pinFileToIPFS(readableStreamForFile, options).then((result) => {
    console.log(result);
    // The IPFS hash (CID) is in result.IpfsHash
}).catch((err) => {
    console.error(err);
});

This script uploads the file and logs the resulting IPFS hash (CID). In line number 3, replace 'yourPinataApiKey' with your API Key and 'yourPinataApiSecret' with your API Secret.

The output will be something like this.

{
  IpfsHash: 'Qm...abc',  // Your IPFS hash will appear here
  PinSize: 12345,
  Timestamp: '2024-05-22T00:00:00Z'
}

Store IPFS Hash on Solana Blockchain

Now that we have the file hash, let's store it on the Solana blockchain. Before this, make sure you have all the necessary tools installed. For this, read this article: How to Setup the Solana Development Environment?

Step 1. Install Solana Web3.js

Once you have the IPFS hash, you can store it on the Solana blockchain. You can use Solana's JavaScript API, `@solana/web3.js`, to achieve this.

npm install @solana/web3.js

Step 2. Store IPFS Hash on Solana Blockchain

const {
    Connection,
    PublicKey,
    clusterApiUrl,
    Keypair,
    Transaction,
    SystemProgram,
    LAMPORTS_PER_SOL,
    sendAndConfirmTransaction
} = require('@solana/web3.js');

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
const keypair = Keypair.generate(); // Replace with your wallet keypair

const storeIpfsHashOnSolana = async (ipfsHash) => {
    const transaction = new Transaction().add(
        SystemProgram.transfer({
            fromPubkey: keypair.publicKey,
            toPubkey: keypair.publicKey, // Replace with a program that stores data
            lamports: 1 // Amount of lamports to transfer (can be zero)
        }),
        {
           keys: [{ pubkey: keypair.publicKey, isSigner: true, isWritable: true }],
           data: Buffer.from(ipfsHash), // Data to store
           programId: new PublicKey('YOUR_PROGRAM_ID') // Replace with your program ID
         }
);

const signature = await sendAndConfirmTransaction(
      connection,
      transaction,
      [keypair]
);

console.log('Transaction successful with signature', signature);
};

storeIpfsHashOnSolana('yourIpfsHash');

You need a Solana program capable of handling arbitrary data storage. If you don't have one, you'll need to write and deploy one using Solana's development tools and then replace 'YOUR_PROGRAM_ID' with that program ID and 'yourIpfsHash' with the generated IPFS hash.

With that, you can save this hash on the Solana Blockchain.

Conclusion

You can successfully upload files to IPFS using Pinata and store the resulting IPFS hash on the Solana blockchain from the above steps. This process ensures that your files are securely stored in a decentralized manner and their references are immutably recorded on Solana. Set up an individual Solana program for data storage to handle IPFS hashes properly. This integration leverages the strengths of both IPFS and Solana, providing a robust solution for decentralized file storage and retrieval.