arrow_back

Develop an NFT with Google Cloud Web3

Sign in Join
Get access to 700+ labs and courses

Develop an NFT with Google Cloud Web3

Lab 1 hour 30 minutes universal_currency_alt 7 Credits show_chart Advanced
info This lab may incorporate AI tools to support your learning.
Get access to 700+ labs and courses

GSP1243

Overview

Google Cloud provides various tools specifically tailored for Web3 development. These tools streamline the process of deploying, managing, and monitoring your NFT contract. If you're a Web3 developer new to Google Cloud Web3, this lab is for you!

In this lab you will learn how to deploy your own NFT contract using the Google Cloud Web3 stack. You will receive the starting code to build a base for your NFT contract, then you'll customize the contract, and then launch it to the Ethereum Sepolia testnet.

You'll also be modifying an ERC-721 NFT contract, using Google's Blockchain Node Engine to deploy your code, and then using BigQuery to monitor it. ERC-721 is a popular standard for NFTs, where each token belonging to the smart contract can be unique. To learn more about NFTs see https://ethereum.org/en/nft/.

Objectives

In this lab you will learn how to:

Prerequisites

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left.

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

You need to install node.js to run hardhat, which is used to compile, test, deploy, and interact with your NFT smart contract.

In lab we have already one pre provisioned Virtual Machine created with the name: lab-setup

  • Navigate to the Compute Engine > Virtual Machine > lab_setup

  • In SSH run the following:

# installs NVM (Node Version Manager) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.profile # download and install Node.js nvm install stable # verifies the right Node.js version is in the environment node -v # verifies the right NPM version is in the environment npm -v

Read documentation for help installing the node.js https://nodejs.org/en/download/package-manager.

Task 1. Fund your Ethereum account

You need a small amount of Sepolia ETH to deploy your contract. Sepolia ETH is free, but it must be obtained from a public faucet.

Use the Cloud Web3 Sepolia Faucet to load testnet ETH on your Ethereum account for the Sepolia network.

  1. Select the Sepolia network
  2. Enter the address of your ethereum account
  3. Click Receive tokens

Task 2. Create directory and install required packages

  1. Create a new directory for your project:
mkdir nft_codelab && cd nft_codelab
  1. Initialize node project. Accept all the defaults:
npm init
  1. Install hardhat:
npm install hardhat
  1. Initialize hardhat project, accept all the defaults:
npx hardhat init
  1. Install OpenZeppelin:
npm install @openzeppelin/contracts

Click Check my progress to verify your performed tasks.

Create directory and install required packages

Task 3. Create your contract

  1. Enter the following information to customize your contract:
  • Enter a name for your NFT Collection: Collection-Name
  • Enter a symbol for your NFT Collection: Collection-Symbol
  • How many items in the collection would you like: Max-Number
  • Determine the max mint per user: Max-Mint
  1. Create a file called MyNFT.sol in the contracts directory:
touch contracts/MyNFT.sol
  1. Add the following code to the MyNFT.sol file:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract {Collection-Name} is ERC721, Ownable { uint256 private _tokenIdCounter; uint256 public MAX_SUPPLY = {Max-Number}; // set max total supply uint256 public maxMintsPerUser = {Max-Mint}; // max mints per user string public baseTokenURI; mapping(address => uint256) private _mintsPerUser; constructor() ERC721("{Collection-Name}", "{Collection-Symbol}") Ownable(msg.sender) {} function mintTo(address to) public payable returns (uint256) { require(_tokenIdCounter < MAX_SUPPLY, "max NFTs already minted"); require(_mintsPerUser[to] < maxMintsPerUser, "exceeded max"); _tokenIdCounter++; _safeMint(to, _tokenIdCounter); _mintsPerUser[to]++; return _tokenIdCounter; } function setMaxMintsPerUser(uint256 maxMints) external onlyOwner { maxMintsPerUser = maxMints; } function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner { baseTokenURI = _baseTokenURI; } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } }

Click Check my progress to verify your performed tasks.

Create your contract

Task 4. Compile your contract

To compile your contract, run the following:

npx hardhat compile

Task 5. Test your contract

  1. Create a file called MyNFT.js in the test directory:
touch test/MyNFT.js
  1. Add the following code to the MyNFT.js file:
const { loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { expect } = require("chai"); describe("MyNFT", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployMyNFTFixture() { // Contracts are deployed using the first signer/account by default const [owner] = await ethers.getSigners(); const MyNFT = await ethers.getContractFactory("{Collection-Name}"); const myNFT = await MyNFT.deploy(); return { myNFT, owner }; } describe("Deployment", function () { it("Should set the right owner", async function () { const { myNFT, owner } = await loadFixture(deployMyNFTFixture); expect(await myNFT.owner()).to.equal(owner.address); }); }); // TODO: Add more tests... });
  1. Run the test with the following command:
npx hardhat test test/MyNFT.js
  1. In a production environment you would write more tests. For this lab, use just this one.

Click Check my progress to verify your performed tasks.

Test your contract

Task 6. Deploy the contract to the Sepolia network

Next you will set up the config so the hardhat program can deploy the contract to the Sepolia network.

  • The url field is specifying the URL of the node.
  • The node is what the program uses to connect with the blockchain network.
  • The accounts list is a list of the user's private keys
  1. Update the contents of the hardhat.config.js file, replace the values currently marked as TODO. The solidity version in your config may be more up-to-date, do not downgrade it to the version in the code snippet or you may encounter compilation issues. The file contents should be similar to below:
require("@nomicfoundation/hardhat-toolbox"); // The JSON-RPC endpoint of a Sepolia Ethereum node. This endpoint is from a pre-existing Blockchain Node Engine (BNE) node created for your use during this lab. const CW3_BNE_SEPOLIA_JSON_RPC_ENDPOINT = "json-rpc.9a56dnsidc61qiluwvdaci6zd.blockchainnodeengine.com"; // The API key for your Blockchain Node Engine node. const BNE_API_KEY = "AIzaSyAwKGxfcVRFQyPRaUqCoFx79FrpLkMk5aM"; // Replace this private key with your Sepolia account private key // To export your private key from Metamask, open Metamask and // go to Account Details > Export Private Key // To export your private key from Coinbase Wallet, go to // Settings > Developer Settings > Show private key // Beware: NEVER put real Ether into testing accounts const SEPOLIA_PRIVATE_KEY = "TODO"; /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.24", networks: { sepolia: { url: `https://${CW3_BNE_SEPOLIA_JSON_RPC_ENDPOINT}?key=${BNE_API_KEY}`, accounts: [SEPOLIA_PRIVATE_KEY] } } };

The solidity version in your code may be more up-to-date, do not downgrade it to the version in the code snippet or you may encounter compilation issues.

Click Check my progress to verify your performed tasks.

Deploy the contract to the Sepolia network
  1. Create a scripts directory and add a file called deployMyNft.js:
mkdir scripts && touch scripts/deployMyNFT.js
  1. Add the following content to deployMyNFT.js:
const hre = require("hardhat"); const CONTRACT_NAME = "{Collection-Name}"; async function main() { const [deployer] = await hre.ethers.getSigners(); console.log(`Deploying contract with the account: ${deployer.address}`); const myNFT = await hre.ethers.deployContract(CONTRACT_NAME); await myNFT.waitForDeployment(); console.log(`MyNFT deployed to address: ${myNFT.target}`); } main().catch((error) => { console.error(error); process.exitCode = 1; });
  1. Run the following to deploy your NFT contract:
npx hardhat run scripts/deployMyNFT.js --network sepolia
  1. If the command is successful, you should see the following output in the terminal:
MyNFT deployed to address: <NEW CONTRACT ADDRESS>
  1. Save the contract address of your NFT collection for future reference.

Note: If you lose the contract address you can use a block explorer like https://sepolia.etherscan.io/ to find it in the transactions of your account.

Task 7. Mint an NFT on the Sepolia network

  1. Create a new folder called interact, then create a new file called mint.js within the interact folder.
  2. Add the following code to interact/mint.js:
const hre = require("hardhat"); async function main() { const mintee = "TODO"; const nftContractAddress = "TODO"; const myContract = await hre.ethers.getContractAt("{Collection-Name}", nftContractAddress); const mintTokenTxn = await myContract.mintTo(mintee); console.log("Txn hash for NFT mint:", mintTokenTxn.hash); } main().catch((error) => { console.error(error); process.exitCode = 1; });
  1. Replace the nftContractAddres variable with the deploying contract address from Task 6 Step 4.
  2. Replace the mintee variable with the address you saved in Task 6 Step 4 to mint an NFT. You can interact with the onlyOwner functions like setMaxMintsPerUser and setBaseTokenURI in the same way, but the caller must be the same address that you used to deploy the contract.

To mint an NFT, run:

npx hardhat run interact/mint.js --network sepolia

Congratulations!

You have learned how to deploy your own NFT contract using the Google Cloud Web3 stack.

Next Steps / Learn more

Once you are done experimenting with your NFT smart contract and have tested any new features, you are ready to deploy your NFT contract to the Ethereum mainnet. Deploying to the mainnet has the following benefits:

  • Real value and permanence: Transactions and applications on the mainnet use real cryptocurrency and have permanent effects. This is crucial for things like NFTs (non-fungible tokens) where ownership and value matter. A testnet NFT wouldn't hold any real value.
  • Network security: Testnets might have weaker security measures compared to the mainnet. Deploying on the mainnet leverages the full security of the blockchain to protect your application and users' assets.
  • Wider audience: The mainnet allows your application to reach a wider audience of users and interact with the actual blockchain ecosystem.

To deploy to the Ethereum mainnet, you will need to create your own Blockchain Node Engine node running on the Ethereum mainnet. Once this node is fully synced, add a new mainnet object in the networks object in the hardhat.config.js file (see Step 6). The mainnet config should be similar to the existing Sepolia config, but should use the JSON-RPC URL of your mainnet node. You may also wish to use a separate ethereum address for testing and production.

Raw transaction data

SELECT * FROM `bigquery-public-data.goog_blockchain_ethereum_mainnet_us.transactions` WHERE to_address = LOWER("{your-nft-contract-address}") AND DATE(block_timestamp) > CURRENT_DATE() - 1 ORDER BY block_timestamp;

View transfers

SELECT transaction_hash, block_timestamp, from_address, to_address, token_id FROM `bigquery-public-data.goog_blockchain_ethereum_mainnet_us.token_transfers` WHERE token = LOWER("{your-nft-contract-address}") GROUP BY account ORDER BY balance DESC LIMIT 100;

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated: April 9, 2024

Lab Last Tested: April 9, 2024

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

This content is not currently available

We will notify you via email when it becomes available

Great!

We will contact you via email if it becomes available

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.