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/.
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
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
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.
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.
Click Next.
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.
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.
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.
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.
(Optional) You can list the active account name with this command:
gcloud auth list
Click Authorize.
Output:
ACTIVE: *
ACCOUNT: {{{user_0.username | "ACCOUNT"}}}
To set the active account, run:
$ gcloud config set account `ACCOUNT`
(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
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.
Select the Sepolia network
Enter the address of your ethereum account
Click Receive tokens
Task 2. Create directory and install required packages
Create a new directory for your project:
mkdir nft_codelab && cd nft_codelab
Initialize node project. Accept all the defaults:
npm init
Install hardhat:
npm install hardhat
Initialize hardhat project, accept all the defaults:
npx hardhat init
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
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
Create a file called MyNFT.sol in the contracts directory:
touch contracts/MyNFT.sol
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
Create a file called MyNFT.js in the test directory:
touch test/MyNFT.js
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...
});
Run the test with the following command:
npx hardhat test test/MyNFT.js
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
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
Create a scripts directory and add a file called deployMyNft.js:
mkdir scripts && touch scripts/deployMyNFT.js
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;
});
Run the following to deploy your NFT contract:
npx hardhat run scripts/deployMyNFT.js --network sepolia
If the command is successful, you should see the following output in the terminal:
MyNFT deployed to address: <NEW CONTRACT ADDRESS>
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
Create a new folder called interact, then create a new file called mint.js within the interact folder.
Replace the nftContractAddres variable with the deploying contract address from Task 6 Step 4.
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.
Google Cloud has several cryptocurrencies in BigQuery public datasets. You can watch the interactions with your NFT on the Ethereum mainnet using the Ethereum dataset. Here are 2 queries to use:
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.
Labs create a Google Cloud project and resources for a fixed time
Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
On the top left of your screen, click Start lab to begin
Use private browsing
Copy the provided Username and Password for the lab
Click Open console in private mode
Sign in to the Console
Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
Accept the terms, and skip the recovery resource page
Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project
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.
Learn how to deploy your own NFT contract using the Google Cloud Web3 stack. You will receive starting code to build a base for your NFT contract, customize parameters, and launch to the Sepolia testnet.