Altszn.com
  • Home
  • Crypto
    • Altcoins
    • Bitcoin
    • Ethereum
    • Monero
    • XRP
    • Zcash
  • Web3
  • DeFi
  • NFTs
No Result
View All Result
Altszn.com
  • Home
  • Crypto
    • Altcoins
    • Bitcoin
    • Ethereum
    • Monero
    • XRP
    • Zcash
  • Web3
  • DeFi
  • NFTs
No Result
View All Result
Altszn.com
No Result
View All Result

IPFS Ethereum Tutorial โ€“ How to Use IPFS with Ethereum

Altszn.com by Altszn.com
February 7, 2023
in Web3
0
IPFS Ethereum Tutorial โ€“ How to Use IPFS with Ethereum
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


Want to upload files to a reliable blockchain storage solution and protect those files by deploying them to a blockchain? If so, this IPFS Ethereum tutorial is just for you! Follow along as we show how to use IPFS with Ethereum by utilizing the Moralis IPFS API, Solidity, MetaMask, and Etherscan. Plus, weโ€™ll also create a contract! While creating an IPFS Ethereum smart contract might sound challenging, weโ€™ll use less than 20 lines of code to create ours! Now, before we can deploy any smart contracts involving IPFS URLs, we must first upload files to IPFS. Fortunately, the following code snippet does all the heavy lifting related to that task:

const res = await Moralis.EvmApi.ipfs.uploadFolder({     abi: fileUploads })

If youโ€™ve worked with Moralis before, you know exactly how to implement the above code. However, if this is your first rodeo with the ultimate Web3 API provider, follow our lead as we tackle todayโ€™s IPFS Ethereum tutorial; all you need is a free Moralis account!

Use IPFS with Ethereum - Sign Up with Moralis Today

Overview

Todayโ€™s article includes two primary parts: our IPFS Ethereum tutorial and the theoretical background behind the topic. Weโ€™ll first focus on showing you how to use IPFS with Ethereum. Weโ€™ll do this by taking an example image file and uploading it to IPFS using a simple NodeJS dapp that incorporates the above-presented code. Along the way, youโ€™ll learn how to obtain your Moralis Web3 API key and work with the Moralis JS SDK. Then, weโ€™ll show you how to create, compile, deploy, and verify a simple IPFS Ethereum smart contract. This contract will enable you to store any uploaded fileโ€™s IPFS hash on the Ethereum blockchain, offering a high level of transparency and security.

As for the second part of the article, youโ€™ll have a chance to get your basics in order. Youโ€™ll learn what IPFS, Ethereum, and smart contracts are. With that knowledge, youโ€™ll understand exactly (in more detail) what an IPFS Ethereum smart contract is.   

White background with Ethereum, IPFS, Solidity, and Moralis logos

Tutorial โ€“ How to Use IPFS with Ethereum

The first stage of this IPFS Ethereum tutorial is all about uploading assets to IPFS using a simple NodeJS script. This is where youโ€™ll learn how to implement the code snippet from the intro. So, create a new project folder, name it โ€œipfsUploadsโ€, and open it in Visual Studio Code (VSC). Inside your project, youโ€™ll need three items: 

  • A โ€œ.envโ€ file to store your Web3 API key
  • A file that you want to store to IPFS (e.g., โ€œbeanBoy.pngโ€)  
  • An โ€œindex.jsโ€ file to create a simple script that will upload your file to IPFS
.env file to create new IPFS Ethereum project in Visual Studio Code

As the above screenshot indicates, you must get your Web3 API key and paste it under the โ€œMORALIS_KEYโ€ variable. So, in case you havenโ€™t created your free Moralis account yet, do so now. You can use the link in the intro or visit โ€œmoralis.ioโ€ and hit one of the โ€œStart for Freeโ€ buttons. With your account ready, youโ€™ll be able to access your admin area. From there, youโ€™ll be able to copy your Web3 API key with two clicks:

Web3 API landing page

With your Web3 API key in place, you can initialize a NodeJS project with the following command:

npm init -y 

The above command will generate a new โ€œpackage.jsonโ€ file for you:

IPFS Ethereum index.js file

Next, install all required dependencies with this command:

npm i moralis fs dotenv

After finishing this initial setup, itโ€™s time for you to code the โ€œindex.jsโ€ script. 

Create a Script to Upload Files to IPFS

At the top, you need to import all of the above-installed dependencies:

const Moralis = require("moralis").default; const fs = require("fs"); require("dotenv").config();

Next, define an array that holds the โ€œendingโ€ path for IPFS locations and the content you want to store. For our example โ€œbeanBoy.pngโ€ file, the following lines of code get the job done:

const fileUploads = [   {       path: "beanBoy.png",       content: fs.readFileSync("./beanBoy.png", {encoding: "base64"})   } ] 

To actually execute the uploading, your script also needs a proper function:

async function uploadToIpfs(){      await Moralis.start({         apiKey: process.env.MORALIS_KEY     })      const res = await Moralis.EvmApi.ipfs.uploadFolder({         abi: fileUploads     })      console.log(res.result)  }  uploadToIpfs();

Looking at the lines above, you can see that the โ€œuploadToIpfsโ€ function initializes Moralis via โ€œMoralis.startโ€ and your Web3 API key. Next, you can see how to properly implement the โ€œMoralis.EvmApi.ipfs.uploadFolderโ€ method from the introduction. This method takes in the previously created array. Finally, the โ€œuploadToIpfsโ€ function console logs the result (provides you with the IPFS hash of the uploaded files). 

Note: You can use the above script for all sorts of files by tweaking the array to match those files.  

Now that your โ€œindex.jsโ€ script is ready, you need to run it with the following command:

node index.js

The above command will execute your code and upload your file(s) to IPFS. In response, you will see your fileโ€™s path in the terminal:

Ethereum IPFS smart contract file path

As you can see in the above screenshot, the file address consists of an IPFS hash with the โ€œendingโ€ path defined in your โ€œfileUploadsโ€ array. 

Note: If you decide to upload multiple files, theyโ€™d all have the same hash with different โ€œendingโ€ paths.

As far as the โ€œhttps://ipfs.moralis.io:2053/ipfs/โ€ part goes, itโ€™s just one of many public IPFS gateways. 

Ethereum logo

IPFS Ethereum Integration

For the sake of this tutorial, you donโ€™t want to waste real ETH. Therefore, we recommend focusing on one of Ethereumโ€™s testnets, such as Goerli, which is the network of our choice herein. As such, make sure to have your MetaMask with the Goerli network ready. Youโ€™ll also need some Goerli ETH to deploy your instance of our smart contract. For that, use a reliable Goerli faucet.  

Note: The process for deploying smart contracts to the Ethereum mainnet is the same, but instead of using Goerli ETH, you use real ETH.

With your MetaMask and Goerli ETH ready, we can head over to โ€œremix.ethereum.orgโ€œ, where you can use Remix. This online tool offers the simplest way to deploy smart contracts. Once you access the Remix IDE dashboard, click on the default โ€œcontractsโ€ folder and create a new โ€œ.solโ€ file. You can follow our lead and name it โ€œipfsContract.solโ€: 

IPFS Ethereum smart contract project initiated in Remix IDE

IPFS Ethereum Smart Contract Example

Like all Solidity smart contracts, make sure yours starts with the license and pragma lines:

// SPDX-License-Identifier: MIT pragma solidity ^0.8.6;

Next, you need to set up the contract by naming it and using the curly brackets for the rest of the logic:

contract ipfsContract{

You only want the contract owner (the address that deploys it) to be able to change the IPFS hash. So, you need to define the corresponding variables: โ€œownerโ€ and โ€œipfsHashโ€:

address public owner; string public ipfsHash;

With โ€œpublicโ€, you ensure that anyone can see who the owner of the contract is. Next, you need to add your contractโ€™s constructor function, which is the type of smart contract function thatโ€™s run only at deployment:  

constructor(){     ipfsHash = "NoHashStoredYet";     owner = msg.sender; }

Looking at the above lines of code, you see that when deployed, this smart contract will set the โ€œipfsHashโ€ variable to โ€œNoHashStoredYetโ€œ. So, youโ€™ll start without assigning any IPFS address to it. As for โ€œownerโ€, it will ensure the address that deploys the contract becomes its owner.

Finally, you can add the additional two functions, which will carry out the functionality of integrating an IPFS address to Ethereum. One function needs to be able to change the โ€œipfsHashโ€ variable. You want only the owner of the contract to be able to execute this function:

function changeHash(string memory newHash) public{     require(msg.sender == owner, "Not Owner of Contract");     ipfsHash = newHash; }

The second function needs to fetch the current hash, which enables everyone to view the current โ€œipfsHashโ€ variable: 

    function fetchHash() public view returns (string memory){         return (ipfsHash);     } }

Note: Since the above smart contract defines the โ€œipfsHashโ€ variable as public, the second function is redundant. Herein, it serves educational purposes, and youโ€™ll get to play with one โ€œwriteโ€ and one โ€œreadโ€ function. 

Compile, Deploy, and Verify Your IPFS Ethereum Smart Contract

With the above lines of code inside the โ€œipfsContract.solโ€ script, you are ready to compile your smart contract. The green checkmark indicates that. So, click on that icon and hit the โ€œCompileโ€ button on that tab:

Compile button in Remix IDE for the IPFS Ethereum smart contract project

Next, you can deploy your smart contract via the โ€œDeployโ€ tab:

Deploy confirmation in MetaMask for the IPFS Ethereum smart contract

As the above screenshot indicates, the โ€œDeployโ€ button will prompt your MetaMask to confirm the on-chain transaction on the Goerli testnet. Once you click on the โ€œConfirmโ€ button, it will take some time for your example smart contract to go live on Goerli. The message at the bottom of Remix will let you know once your transaction is confirmed: 

Confirmation of executed IPFS Ethereum smart contract

Then, you can click on the โ€œview on etherscanโ€ link above, which will take you to your transactionโ€™s page:

Etherscan landing page of the smart contract for Ethereum

To access your smart contractโ€™s page, click on your smart contractโ€™s address as indicated in the above screenshot. Once on the smart contract page, youโ€™ll be able to verify your contract:

On the next page, select the details that you used in Remix and hit โ€œContinueโ€:

Then, you need to paste your entire smart contract code into the designated field: 

Finally, checkmark the โ€œIโ€™m not a robotโ€ box and click on the โ€œVerify and Publishโ€ button:

After successfully verifying your smart contract, you can use Etherscan to run your contractโ€™s functions:

If you select the โ€œWrite Contractโ€ tab and connect your MetaMask (with the same account you used to deploy the above contract), youโ€™ll be able to change the โ€œipfsHashโ€ variable to match your fileโ€™s hash:

Once the above transaction goes through, you can read the contractโ€™s โ€œfetchHashโ€ function again to see that your IPFS address is actually stored in your smart contract:

And, if any other address (not owner) tries to execute the โ€œchangeHashโ€ function, they will be blocked:

IPFS Ethereum Guide โ€“ Exploring IPFS and Ethereum

Itโ€™s time we cover the theory behind the above โ€œHow to Use IPFS with Ethereumโ€ tutorial. This means you get to find out what IPFS, Ethereum, and smart contracts are. Then, weโ€™ll tackle the โ€œwhat is an IPFS Ethereum smart contract?โ€ question. 

Title - IPFS Ethereum Tutorial Theory

What is IPFS?

InterPlanetary File System, or IPFS, is a peer-to-peer (P2P) decentralized protocol for storing and accessing content. Itโ€™s an open-source protocol, so anyone can use it to store and access data, websites, files, and applications. All in all, IPFS continues to be the most popular Web3 storage solution. It serves a wide range of use cases, including many IPFS NFT projects. However, itโ€™s worth pointing out that IPFS is technically not one of the blockchain storage companies as it doesnโ€™t employ blockchain technology.

Unlike Web2 storage solutions, IPFS utilizes โ€content-based addressingโ€. As such, data or content is fetched based on the content itself and not on the location of that content. Consequently, you donโ€™t need to know where the content is located before you wish to fetch it. For this type of addressing to work properly, IPFS assigns files and data with unique identifiers or content IDs (CIDs). CIDs are commonly known as IPFS hashes and are unique for every piece of content stored on IPFS. If you want to learn more about IPFS and how it works, visit the Moralis blog and search for โ€œwhat is IPFS?โ€.

Motherboard showing IPFS and Ethereum components for a IPFS Ethereum smart contract

What is Ethereum?

Ethereum is the most popular and widely used programmable blockchain. It was the first blockchain to support smart contracts and, in turn, gave birth to altcoins/crypto tokens (fungible and non-fungible), DeFi applications, and countless other decentralized applications (dapps). Anyone with internet access and an Ethereum address (Web3 wallet) can interact with this chain and applications built on top of it. 

Like all layer-one (L1) blockchains, Ethereum has its native cryptocurrency: ether (ETH). The latter provides the networkโ€™s security through the proof-of-stake (PoS) consensus mechanism and covers transaction fees. If you wish to explore Ethereum further, visit the Moralis blog and search for โ€œwhat is Ethereum?โ€ or enroll in the โ€œEthereum Fundamentalsโ€ course at Moralis Academy.      

Title - Ethereum Smart Contract and IPFS

Ethereum and Smart Contracts

We mentioned above that Ethereum was the first blockchain network that supported smart contracts. This was a real game-changer compared to the options that Bitcoin offered at that time. After all, smart contracts are on-chain pieces of software that automatically execute predefined actions when predefined conditions are met. As such, smart contracts offer limitless options and can help automate and execute transparent processes. 

Currently, ERC-20, ERC-721, and ERC-1155 smart contracts focusing on creating and managing tokens are the most common ones. However, there are countless other standardized and non-standardized smart contracts on Ethereum. 

IPFS Ethereum Tutorial Graph

What is an IPFS Ethereum Smart Contract?

An IPFS Ethereum smart contract is a smart contract that includes an IPFS hash and is deployed on the Ethereum network. These kinds of contracts can come in all sorts of forms. However, due to the increased popularity of NFTs in the last couple of years, ERC-721 and ERC-1155 contracts are currently the most common examples of IPFS Ethereum smart contracts. Of course, thatโ€™s only true when the projects they serve use IPFS to store NFT metadata files. With that in mind, if you decide to proceed with Web3 contract development, youโ€™ll most likely deploy all sorts of IPFS Ethereum smart contracts.  

How to Use IPFS with Ethereum Sequence Graph

IPFS Ethereum Tutorial โ€“ How to Use IPFS with Ethereum โ€“ Summary

Throughout the above sections, you learned how to use IPFS with Ethereum. We first showed you how to utilize the power of the Moralis IPFS API to upload files to that decentralized storage solution. By completing our tutorial, you also learned how to write, compile, deploy, and verify a simple IPFS Ethereum smart contract. As a result, you were able to upload files to IPFS to get their IPFS hash and then store that hash on Ethereum via your smart contract. You also had a chance to cover the theoretical aspects of todayโ€™s topic. Hence, you were able to learn what IPFS, Ethereum, smart contracts, and IPFS Ethereum smart contracts are.  

Itโ€™s worth pointing out that the skills obtained herein apply to all EVM-compatible chains. Moreover, that means you can use the same enterprise blockchain solutions you used throughout our tutorial for many leading and emerging development blockchains. Whether you want to create your own smart contracts or use existing ones, your end goal should be to create killer dapps. This is where using the best blockchain infrastructure companies, such as Moralis, makes a difference. 

Aside from the ultimate Web3 Data API, Moralis also provides the best Web3 Authentication API and the top Notify API alternative: the Moralis Streams API. The latter makes Web3 libraries obsolete in many ways. In addition, Moralis offers countless useful resources, including the best gwei to ETH converter and many reliable crypto faucets (Aptos testnet faucet, Polygon Mumbai faucet, Sepolia testnet faucet, etc.). You can also join the Web3 revolution confidently by diving into Web3 programming on the Moralis YouTube channel, crypto blog, and at Moralis Academy. If you are committed to using Web3 storage solutions, make sure to explore โ€œwhat is web3.storage?โ€. 



Read More: moralis.io

Tags: EthereumIPFSTutorialweb 3.0Web3
ADVERTISEMENT

Recent

Danger signs for Bitcoin as retail abandons it to institutions: Sky Wee

Danger signs for Bitcoin as retail abandons it to institutions: Sky Wee

May 14, 2025
Crypto VC deals drop in Q1, but funding more than doubles: PitchBook

Crypto VC deals drop in Q1, but funding more than doubles: PitchBook

May 14, 2025
Ether Nears $2.7K, Dogecoin Zooms 9% to Keep Cheery Mood Ongoing

Ether Nears $2.7K, Dogecoin Zooms 9% to Keep Cheery Mood Ongoing

May 14, 2025

Categories

  • Bitcoin (4,858)
  • Blockchain (11,412)
  • Crypto (9,352)
  • Dark Web (549)
  • DeFi (8,397)
  • Ethereum (4,905)
  • Metaverse (7,530)
  • Monero (290)
  • NFT (1,481)
  • Solana (5,047)
  • Web3 (20,703)
  • Zcash (509)

Category

Select Category

    Advertise

    Advertise your site, company or product to millions of web3, NFT and cryptocurrency enthusiasts. Learn more

    Useful Links

    Advertise
    DMCA
    Contact Us
    Privacy Policy
    Shipping & Returns
    Terms of Use

    Resources

    Exchanges
    Changelly
    Web3 Jobs

    Recent News

    Danger signs for Bitcoin as retail abandons it to institutions: Sky Wee

    Danger signs for Bitcoin as retail abandons it to institutions: Sky Wee

    May 14, 2025
    Crypto VC deals drop in Q1, but funding more than doubles: PitchBook

    Crypto VC deals drop in Q1, but funding more than doubles: PitchBook

    May 14, 2025

    ยฉ 2022 Altszn.com. All Rights Reserved.

    No Result
    View All Result
    • Home
      • Home โ€“ Layout 1
      • Home โ€“ Layout 2
      • Home โ€“ Layout 3

    ยฉ Altszn.com. All Rights Reserved.

    • bitcoinBitcoin (BTC) $ 103,021.00
    • ethereumEthereum (ETH) $ 2,591.77
    • tetherTether (USDT) $ 1.00
    • xrpXRP (XRP) $ 2.54
    • bnbBNB (BNB) $ 649.05
    • solanaSolana (SOL) $ 176.04
    • usd-coinUSDC (USDC) $ 0.999933
    • dogecoinDogecoin (DOGE) $ 0.233530
    • cardanoCardano (ADA) $ 0.794868
    • tronTRON (TRX) $ 0.274024
    • staked-etherLido Staked Ether (STETH) $ 2,589.70
    • wrapped-bitcoinWrapped Bitcoin (WBTC) $ 102,940.00
    • suiSui (SUI) $ 3.88
    • chainlinkChainlink (LINK) $ 16.91
    • wrapped-stethWrapped stETH (WSTETH) $ 3,117.89
    • avalanche-2Avalanche (AVAX) $ 24.59
    • stellarStellar (XLM) $ 0.304354
    • shiba-inuShiba Inu (SHIB) $ 0.000016
    • hedera-hashgraphHedera (HBAR) $ 0.204599
    • hyperliquidHyperliquid (HYPE) $ 24.83
    • leo-tokenLEO Token (LEO) $ 8.89
    • the-open-networkToncoin (TON) $ 3.24
    • bitcoin-cashBitcoin Cash (BCH) $ 400.92
    • litecoinLitecoin (LTC) $ 100.58
    • polkadotPolkadot (DOT) $ 4.93
    • usdsUSDS (USDS) $ 0.999848
    • wethWETH (WETH) $ 2,591.21
    • moneroMonero (XMR) $ 341.90
    • pi-networkPi Network (PI) $ 0.847776
    • wrapped-eethWrapped eETH (WEETH) $ 2,767.90
    • pepePepe (PEPE) $ 0.000014
    • bitget-tokenBitget Token (BGB) $ 4.74
    • binance-bridged-usdt-bnb-smart-chainBinance Bridged USDT (BNB Smart Chain) (BSC-USD) $ 1.00
    • ethena-usdeEthena USDe (USDE) $ 1.00
    • coinbase-wrapped-btcCoinbase Wrapped BTC (CBBTC) $ 103,006.00
    • whitebitWhiteBIT Coin (WBT) $ 30.27
    • uniswapUniswap (UNI) $ 6.69
    • bittensorBittensor (TAO) $ 456.58
    • nearNEAR Protocol (NEAR) $ 3.04
    • daiDai (DAI) $ 1.00
    • aptosAptos (APT) $ 5.77
    • aaveAave (AAVE) $ 229.06
    • okbOKB (OKB) $ 54.69
    • ondo-financeOndo (ONDO) $ 1.01
    • jito-staked-solJito Staked SOL (JITOSOL) $ 211.55
    • kaspaKaspa (KAS) $ 0.120268
    • ethereum-classicEthereum Classic (ETC) $ 19.81
    • internet-computerInternet Computer (ICP) $ 5.62
    • crypto-com-chainCronos (CRO) $ 0.101303
    • tokenize-xchangeTokenize Xchange (TKX) $ 36.18
    • bitcoinBitcoin (BTC) $ 103,021.00
    • ethereumEthereum (ETH) $ 2,591.77
    • tetherTether (USDT) $ 1.00
    • xrpXRP (XRP) $ 2.54
    • bnbBNB (BNB) $ 649.05
    • solanaSolana (SOL) $ 176.04
    • usd-coinUSDC (USDC) $ 0.999933
    • dogecoinDogecoin (DOGE) $ 0.233530
    • cardanoCardano (ADA) $ 0.794868
    • tronTRON (TRX) $ 0.274024
    • staked-etherLido Staked Ether (STETH) $ 2,589.70
    • wrapped-bitcoinWrapped Bitcoin (WBTC) $ 102,940.00
    • suiSui (SUI) $ 3.88
    • chainlinkChainlink (LINK) $ 16.91
    • wrapped-stethWrapped stETH (WSTETH) $ 3,117.89
    • avalanche-2Avalanche (AVAX) $ 24.59
    • stellarStellar (XLM) $ 0.304354
    • shiba-inuShiba Inu (SHIB) $ 0.000016
    • hedera-hashgraphHedera (HBAR) $ 0.204599
    • hyperliquidHyperliquid (HYPE) $ 24.83
    • leo-tokenLEO Token (LEO) $ 8.89
    • the-open-networkToncoin (TON) $ 3.24
    • bitcoin-cashBitcoin Cash (BCH) $ 400.92
    • litecoinLitecoin (LTC) $ 100.58
    • polkadotPolkadot (DOT) $ 4.93
    • usdsUSDS (USDS) $ 0.999848
    • wethWETH (WETH) $ 2,591.21
    • moneroMonero (XMR) $ 341.90
    • pi-networkPi Network (PI) $ 0.847776
    • wrapped-eethWrapped eETH (WEETH) $ 2,767.90
    • pepePepe (PEPE) $ 0.000014
    • bitget-tokenBitget Token (BGB) $ 4.74
    • binance-bridged-usdt-bnb-smart-chainBinance Bridged USDT (BNB Smart Chain) (BSC-USD) $ 1.00
    • ethena-usdeEthena USDe (USDE) $ 1.00
    • coinbase-wrapped-btcCoinbase Wrapped BTC (CBBTC) $ 103,006.00
    • whitebitWhiteBIT Coin (WBT) $ 30.27
    • uniswapUniswap (UNI) $ 6.69
    • bittensorBittensor (TAO) $ 456.58
    • nearNEAR Protocol (NEAR) $ 3.04
    • daiDai (DAI) $ 1.00
    • aptosAptos (APT) $ 5.77
    • aaveAave (AAVE) $ 229.06
    • okbOKB (OKB) $ 54.69
    • ondo-financeOndo (ONDO) $ 1.01
    • jito-staked-solJito Staked SOL (JITOSOL) $ 211.55
    • kaspaKaspa (KAS) $ 0.120268
    • ethereum-classicEthereum Classic (ETC) $ 19.81
    • internet-computerInternet Computer (ICP) $ 5.62
    • crypto-com-chainCronos (CRO) $ 0.101303
    • tokenize-xchangeTokenize Xchange (TKX) $ 36.18