Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article explains how to develop smart contracts with WalletConnect in Remix, a browser-based smart contract development environment. The instructions are intended to be accessible even to readers without an engineering background.

This guide is written for non-engineers as well as developers. Some terms are therefore explained in simplified form rather than with their exact formal definitions. The emphasis is on accessibility. Keep that in mind while following the guide. The screenshots and interface descriptions reflect the original May 2024 walkthrough.

Open Remix

First, open the Remix website.

Use the URL above because its query parameters include settings such as the compiler version.

Opening Remix

The page should look like the screenshot above.

Opening Remix

Look at the sidebar on the left. The highlighted areas correspond to the following functions.

  1. Develop smart contracts.
  2. Compile the code into a format that the computer can execute.
  3. Deploy the contract.

Create a Solidity file

Create a Solidity source file.

Creating a Solidity file

Hover over the contracts directory shown above and click the file icon that appears. A new file is created, and you can enter its name.

After naming the file, click it to open it. The file is initially empty. Add the code as shown below.

Creating a Solidity file

Rather than writing the contract from scratch, copy the code provided below. Copy every line and paste the code into the file you just created.

You have now created a smart contract written in Solidity.

Understanding the smart contract

Now that the contract is created, examine how it works.

This section explains the contract in detail. If you prefer to start with practical exercises, skip to the following section.

License and compiler version

solidity
// SPDX-License-Identifier: MIT

This section declares the license.

The MIT license permits use, copying, modification, merging, publication, and distribution, subject to its license notice requirements.

solidity
pragma solidity 0.8.25;

This line declares the Solidity version. The example uses version 0.8.25.

Library imports

solidity
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ERC721Burnable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Base64} from "@openzeppelin/contracts/utils/Base64.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";

Several libraries and contracts are imported.

  • ERC721
    • Imports the ERC721 contract developed by OpenZeppelin.
    • This contract is commonly imported when creating an ERC721 NFT.
  • ERC721Burnable
    • An extension that enables ERC721 NFTs to be burned.
    • Burning permanently removes an NFT from circulation.
  • Ownable
    • A contract for managing contract ownership.
  • Base64
    • A library for encoding data into another representation.

A way to represent binary data using the 64 characters a–z, A–Z, 0–9, +, and /, with = used for padding.

https://wa3.i-3-i.info/word11338.html

  • Strings
    • A library for converting certain values into strings.

Contract declaration

solidity
contract JBANFT is ERC721, ERC721Burnable, Ownable {

The declaration above defines the contract name and specifies the contracts it inherits. Inheritance allows one contract to use functionality defined by another contract. Here, JBANFT inherits ERC721, ERC721Burnable, and Ownable, making the functionality of these three contracts available to it.

Variables

solidity
uint256 private _nextTokenId;

The declaration defines a variable called _nextTokenId. A variable is like a container that holds a value. Here, the container is named _nextTokenId and can store values of its declared type. uint256 specifies the kind of data the variable can hold, known as its type. uint256 represents integers from 00 to 2256−12^256 - 1. It may appear to contain no value because the declaration does not explicitly initialize it. However, Solidity initializes an unsigned integer state variable to 0 by default.

constructor

solidity
constructor(address initialOwner)
    ERC721("JBANFT", "JBAN")
    Ownable(initialOwner)
{}

The declaration defines a constructor, which executes only once when the contract is deployed. It takes an address named initialOwner as an argument (a value supplied when the function is invoked) and uses the functionality of Ownable to set the contract owner to that address. An address such as 0xabc123... is supplied as initialOwner. ERC721("JBANFT", "JBAN") calls the inherited ERC721 constructor to set the NFT collection name and symbol.

The mint function

solidity
function safeMint(address to) public {
    uint256 tokenId = _nextTokenId++;
    _safeMint(to, tokenId);
}

This function defines the operation that mints a new NFT. The function is named safeMint and accepts a recipient address called to. The public keyword specifies the function's visibility.

Visibility Description
external Exposed through the contract's external interface.
public Accessible through both external and internal calls.
internal Accessible internally, including from derived contracts.

These are three common visibility options for state-changing functions. Solidity also supports private visibility. An external function cannot be called directly as an internal function, but can be invoked through the external interface, for example from a frontend. A public function can be called directly by other functions inside the contract and through its external interface. An internal function can be called within the contract and its derived contracts, but is not exposed through the external interface.

Examine the body of the function. A variable named tokenId is assigned the result of _nextTokenId++. The expression _nextTokenId++ uses post-increment, increasing the stored value of _nextTokenId by 1. If _nextTokenId was 2, tokenId receives 2, and _nextTokenId becomes 3. This tokenId is one of the values that uniquely identifies an NFT within the collection. Because the counter increases by 1 on each mint, this minting mechanism does not reuse a tokenId.

The function then calls _safeMint, passing the recipient address to and the newly assigned tokenId. _safeMint is defined in the inherited ERC721 contract.

The _safeMint function

Examine the implementation of _safeMint.

Inspecting the _safeMint function

Hold down the Command key and click the highlighted section.

Inspecting the _safeMint function

This opens the ERC721 contract shown above. It is the ERC721 implementation inherited by the example contract.

The _safeMint function called earlier is defined around line 304 in this version.

solidity
function _safeMint(address to, uint256 tokenId) internal {
    _safeMint(to, tokenId, "");
}

It calls another function. In Solidity, functions can have the same name but different parameter lists. This is called function overloading. The _safeMint call inside the function takes three arguments, whereas the call made earlier takes two, so they refer to different overloads.

solidity
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
    _mint(to, tokenId);
    _checkOnERC721Received(address(0), to, tokenId, data);
}

The snippet above shows the three-argument overload of _safeMint. It calls a function named _mint.

This walkthrough does not cover _checkOnERC721Received(address(0), to, tokenId, data); in detail.

solidity
function _mint(address to, uint256 tokenId) internal {
    if (to == address(0)) {
        revert ERC721InvalidReceiver(address(0));
    }
    address previousOwner = _update(to, tokenId, address(0));
    if (previousOwner != address(0)) {
        revert ERC721InvalidSender(address(0));
    }
}

The snippet above is the _mint function invoked earlier. Examine how it works.

solidity
if (to == address(0)) {
    revert ERC721InvalidReceiver(address(0));
}

This code performs a conditional check. Conditional logic selects different behavior depending on whether a condition is satisfied. Here, the condition is to == address(0). It checks whether the address receiving the newly minted NFT is address(0). The == operator tests equality. address(0) is called the zero address and is used as a sentinel value. The zero address is not an ordinary usable NFT recipient.

During a burn, ERC721 uses the zero address to represent removal of ownership.

If the zero address is supplied as to, the function reverts with ERC721InvalidReceiver.

solidity
address previousOwner = _update(to, tokenId, address(0));

The code then calls another function named _update.

solidity
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
    address from = _ownerOf(tokenId);

    // Perform (optional) operator check
    if (auth != address(0)) {
        _checkAuthorized(from, auth, tokenId);
    }

    // Execute the update
    if (from != address(0)) {
        // Clear approval. No need to re-authorize or emit the Approval event
        _approve(address(0), tokenId, address(0), false);

        unchecked {
            _balances[from] -= 1;
        }
    }

    if (to != address(0)) {
        unchecked {
            _balances[to] += 1;
        }
    }

    _owners[tokenId] = to;

    emit Transfer(from, to, tokenId);

    return from;
}

This function contains several steps. Its arguments are to (the NFT recipient), tokenId (the token ID being minted), and auth (the address whose authority over that token is to be checked). auth identifies the account whose authorization must be checked when required. Here, minting uses the zero address to skip that authorization check.

solidity
address from = _ownerOf(tokenId);

The code calls _ownerOf to obtain the current owner of the NFT identified by tokenId. Because the token has not yet been minted, the zero address is returned. The zero address can therefore also indicate the absence of a value.

solidity
if (auth != address(0)) {
    _checkAuthorized(from, auth, tokenId);
}

If auth is not the zero address, the code checks whether that account is authorized to operate on the NFT by its current owner.

solidity
if (from != address(0)) {
    // Clear approval. No need to re-authorize or emit the Approval event
    _approve(address(0), tokenId, address(0), false);

    unchecked {
        _balances[from] -= 1;
    }
}

The code above handles the ownership update involved in an NFT transfer, such as sending an NFT from address A to address B.

solidity
if (to != address(0)) {
    unchecked {
        _balances[to] += 1;
    }
}

Because the example mints a new NFT, the code above is the main balance-update step. The to argument contains the NFT recipient address, which is different from address(0). The != operator tests inequality. The expression _balances[to] += 1; increases the number of NFTs owned by to by 1. The += operator adds the right-hand value to the value on the left.

solidity
mapping(address owner => uint256) private _balances;

_balances is a mapping declared as shown above. In simple terms, it associates a uint256 value with each owner address.

  • 0x123abc... -> 2
  • 0x456def... -> 5
  • 0x789hij... -> 1

Each address has a recorded NFT balance. Accessing _balances[to], where to holds an address such as 0x456def..., retrieves a value such as 5.

Because a new NFT is being minted, the recipient's balance is increased by 1.

solidity
_owners[tokenId] = to;

The code above records the owner address associated with a particular tokenId.

solidity
mapping(uint256 tokenId => address) private _owners;

As with _balances, the ownership information is stored in a mapping.

  • 1 -> 0x123abc...
  • 2 -> 0x456def...
  • 3 -> 0x789hij...
  • ...

The mapping tracks the current owner of the NFT identified by each tokenId.

Because the NFT is newly minted, the owner of the supplied tokenId is set to to.

solidity
emit Transfer(from, to, tokenId);

Finally, emit a Transfer event so frontends and other clients can observe that the mint occurred.

That is the complete minting process described in this example.

tokenURI

The tokenURI function returns the NFT's metadata URI.

Metadata contains detailed information describing an NFT. It can define the NFT's name, description, image, video, and other properties such as attributes.

Inspecting tokenURI

Inspecting tokenURI

The metadata provides information like that displayed by OpenSea in the screenshots above.

solidity
function tokenURI(uint256 tokenId)
        public
        view
        override
        returns (string memory)
    {

The function accepts tokenId as an argument and declares several other properties. As explained for the mint function, public makes a function accessible internally and through the external interface. view marks a read-only function that does not modify contract state. override indicates that the function replaces an inherited function with the same signature, here the tokenURI implementation inherited from ERC721. Overriding allows the derived contract to define its own behavior.

The returns (string memory) declaration specifies the type returned by the function. The function returns text, so its return type is string. memory specifies a temporary data location used during function execution. Unlike persistent storage, memory does not write data permanently to the blockchain. Memory operations still consume gas during on-chain execution, although an ordinary off-chain read does not require a paid transaction.

solidity
require(
    tokenId <= _nextTokenId,
    "ERC721Metadata: URI query for nonexistent token"
);

The code checks whether the specified tokenId has already been minted. If the token does not exist, the operation reverts.

solidity
// string memory uri = "https://ipfs.io/ipfs/QmXbBSeMWZd3wSxAKMhMSs5m5ZzJJDUHdSimnUmEx8BuEp?filename=JBAN.png";
        string memory uri = "https://arweave.net/pP9Rw4hx-Ki8m1R1A5EotbpZW2MAJlenmXbAtTa93Gc"; // You can substitute an image of your choice here

This sets the URL of the NFT image. NFT images can differ by tokenId, but this example uses the same image for every token.

solidity
return
            string(
                abi.encodePacked(
                    "data:application/json;base64,",
                    Base64.encode(
                        bytes(
                            abi.encodePacked(
                                '{"name": "JBANFT #',
                                Strings.toString(tokenId),
                                '", "description": "JBA NFT", "image": "',
                                uri,
                                '"}'
                            )
                        )
                    )
                )
            );

Finally, the code assembles the metadata.

json
{
	"name": "JBANFT #0",
	"description": "JBANFT NFT",
	"image": "https://arweave.net/pP9Rw4hx-Ki8m1R1A5EotbpZW2MAJlenmXbAtTa93Gc"
}

Without going into every implementation detail, the code assembles JSON like the example above and returns the following Base64-encoded value.

bash
data:application/json;base64,eyJuYW1lIjogIkpCQU5GVCAjMCIsICJkZXNjcmlwdGlvbiI6ICJKQkEgTkZUIiwgImltYWdlIjogImh0dHBzOi8vYXJ3ZWF2ZS5uZXQvcFA5Unc0aHgtS2k4bTFSMUE1RW90YnBaVzJNQUpsZW5tWGJBdFRhOTNHYyJ9

Base64 is not a mandatory default for NFT metadata, but it can be useful for embedding metadata directly in a data URI.

  • Base64 makes binary or structured content representable as text; it does not inherently reduce on-chain storage size.
  • Many kinds of data can be encoded using Base64.
  • A self-contained data URI allows a client to retrieve the encoded metadata without requiring a separate metadata server.

This completes the explanation of the functions defined in the example contract. Compile the contract next.

Compile the contract

Compile the contract. Solidity contracts are written in a human-readable source language that the execution environment cannot execute directly. Compilation converts that source code into executable bytecode.

Follow the steps below to compile the contract.

Compiling the contract

Click the middle icon in the sidebar, then click Compile Nft.sol. The compiler icon displays a progress indicator. Compilation has succeeded when it shows a checkmark. These are the steps needed to compile the example.

Compiling the contract

Deploy the contract

Deploy the contract next. Deployment makes a contract available in the selected execution environment so its functions can be invoked. This section deploys to Remix's local environment rather than Ethereum mainnet or a public testnet. Other users cannot interact with the local deployment, but you can test the behavior of the contract you created.

Deploying the contract

  1. Click the second icon from the bottom of the sidebar.
  2. Click the copy button next to the account address.
    • This is a temporary local account address.
  3. Paste the copied address into the constructor argument field.
  4. Click Deploy to deploy the contract.

Follow these steps to deploy the contract.

Deploying the contract

When deployment succeeds, the deployed contract and its functions appear as shown above.

Deploying the contract

The contract address is displayed at the top. Orange buttons invoke state-changing functions, while blue buttons invoke read-only functions.

Execute contract functions

Try calling the functions of the deployed contract.

Prerequisites

Use the account address copied from the area shown below.

Copying the test account address

NFT information

Start by retrieving information about the NFT.

Reading NFT information

Call the three functions shown above and verify that each returns the expected information.

  • name
    • NFT contract name.
    • JBANFT
  • owner
    • Address supplied when clicking Deploy.
  • symbol
    • NFT collection symbol.
    • JBAN

safeMint

Mint an NFT next.

Calling safeMint

Paste the copied address into the highlighted input field on the right and click safeMint on the left.

Calling safeMint

The operation succeeds if the console at the bottom right displays a successful transaction, as shown above.

balanceOf

Call balanceOf to check the number of NFTs held by a particular address.

Calling balanceOf

Enter the address that received the NFT in the field on the right, then click balanceOf. The expected output is 1. Call safeMint again and click balanceOf once more. Because balanceOf returns the number of NFTs held by the account, the expected result is now 2.

ownerOf

Call ownerOf to check the owner address of an NFT with a particular tokenId.

Calling ownerOf

Enter a token ID in the input field. First, enter 0 and click ownerOf. The output should be the address that received the NFT when safeMint was called. Then enter 1. The same owner address should appear.

If you enter 2 or a higher value at this point, an error appears in the console.

Calling ownerOf

This is because the supplied tokenId does not exist.

tokenURI

Finally, call tokenURI to retrieve the metadata URI.

Inspecting tokenURI

Enter 0. A long encoded string like the one shown above indicates success. The content is encoded as Base64 and must be decoded to inspect the JSON.

Open the link above and copy the data after the data:application/json;base64, prefix.

Inspecting tokenURI

Paste it as shown and click Convert (the Japanese label in the screenshot). The output should look like the following.

json
{
	"name": "JBANFT #0",
	"description": "JBANFT NFT",
	"image": "https://arweave.net/pP9Rw4hx-Ki8m1R1A5EotbpZW2MAJlenmXbAtTa93Gc"
}
  • name
    • The NFT name, JBANFT #0, is displayed.
  • description
    • The NFT description, JBANFT NFT, is displayed.
  • image
    • Contains the NFT image URL.

Open the URL in the image field.

https://arweave.net/pP9Rw4hx-Ki8m1R1A5EotbpZW2MAJlenmXbAtTa93Gc

Inspecting tokenURI

The image should appear as shown above.

This completes the local execution walkthrough.

Deploy to a testnet with WalletConnect

Use WalletConnect to deploy the contract to a public testnet.

WalletConnect is a protocol for connecting applications to desktop or mobile wallet applications. It makes it easier to connect to DApps using a mobile wallet, even when the user does not have a browser-extension wallet.

Prerequisites

Remove the deployed contract instance from Remix

First, remove the previously deployed instance from the Remix interface.

Removing the local contract instance

Click the trash icon shown above to remove the instance from Remix's list. This does not delete an on-chain contract.

Obtain testnet tokens

The original walkthrough suggests about 0.5 Sepolia ETH, which should be sufficient for its example.

This example uses Sepolia, so you need Sepolia test ETH.

If you do not have Sepolia test ETH, the following faucet was used in the original walkthrough. Availability and requirements may have changed since May 2024.

Obtaining testnet tokens

Connect a wallet through Connect Wallet and link a GitHub account if you have one.

Obtaining testnet tokens

Select the option labeled Ethereum Sepolia, enter the recipient address in Claim your test ETH, and click the button beside Ethereum Sepolia. The test ETH should arrive in the wallet after the faucet processes the request.

If you do not have a GitHub account, the original walkthrough also listed a faucet providing 0.05 test ETH.

Connect with WalletConnect

Connect the wallet using WalletConnect.

Connecting through WalletConnect

Click ENVIRONMENT and select WalletConnect, as shown above.

Connecting through WalletConnect

When the Wallet Connect tab opens, click Connect Wallet.

Although the interface uses both Wallet Connect and Connect Wallet as labels, they refer to different steps in this connection process.

Connecting through WalletConnect

There are two connection options.

The following walkthrough primarily uses a smartphone. The same general operations apply when using a desktop wallet.

PC

For a desktop wallet, select either Metamask or Browser Wallet in the blue highlighted area.

Connecting a desktop wallet

Select the wallet you wish to connect, scroll to the bottom, and click Next.

Connecting a desktop wallet

Then click Connect.

Connecting a desktop wallet

Return to Remix. The connection has succeeded if the connected account appears in the highlighted area.

Mobile

For a mobile wallet, click WalletConnect in the red highlighted area. The example uses the MetaMask mobile app.

Connecting a mobile wallet

Scan the displayed QR code with the smartphone camera. Follow the prompt to open the MetaMask app.

Connecting a mobile wallet

When the connection request appears, click Connect in the bottom-right corner.

Connecting a mobile wallet

After connecting, the account address appears in the highlighted area as shown.

Connecting a mobile wallet

If the connection fails, select Sepolia Test Network from the network selector at the top of the app. If it still fails, try restarting the camera or MetaMask app, or reloading Remix.

Check the wallet balance

The walkthrough uses the Sepolia testnet. If the connected wallet does not hold Sepolia test ETH, send test ETH to that wallet.

Checking the wallet balance

After the transfer, reload the page. The highlighted area displays the connected wallet's Sepolia test ETH balance.

Checking the wallet balance

Deploy the contract

Deploy the contract to Sepolia using the procedure practiced in the local environment.

Deploying the contract

Copy the connected wallet address and paste it into the field to the right of Deploy. Then click Deploy.

Deploying the contract

The MetaMask mobile app displays a transaction confirmation. Check the network, account, and transaction details, then tap Confirm.

Deploying the contract

The highlighted deployment result indicates that the contract has been deployed. Click view on etherscan to inspect the Sepolia deployment transaction.

Mint an NFT

Mint an NFT on the testnet.

Minting an NFT

Enter the connected wallet address as shown and click safeMint.

Minting an NFT

MetaMask displays a confirmation request. Check the transaction and tap Confirm.

Minting an NFT

Minting an NFT

The status appears at the bottom of the app. A message indicating that the transaction completed means the mint has succeeded.

Minting an NFT

A successful transaction in the Remix console also confirms the result.

Click view on etherscan in the console to inspect the mint transaction.

Minting an NFT

The contract address appears in the screenshot above. Click the copy icon to copy the contract address.

After copying it, open the link above. The site used in the original walkthrough is OpenSea, an NFT marketplace. It allows users to trade NFTs. Because the contract is deployed on a testnet, the original guide uses OpenSea's historical testnet site. Its current availability is not established here.

Minting an NFT

Paste the copied contract address into the highlighted search field. In the Collections section, select the deployed collection named JBANFT.

Minting an NFT

When the collection opens, select the NFT named JBANFT #0.

Minting an NFT

The NFT detail page appears as shown above. This is the NFT minted in the preceding steps.

Verify the NFT

Finally, call balanceOf, ownerOf, and tokenURI to check the NFT data.

Verifying the NFT

Enter the wallet address for balanceOf and 0 for both ownerOf and tokenURI, as shown above.

  • balanceOf
    • 1
  • ownerOf
    • Wallet address.
  • tokenURI
    • data:application/json;base64,eyJuYW1lIjogIkpCQU5GVCAjMCIsICJkZXNjcmlwdGlvbiI6ICJKQkEgTkZUIiwgImltYWdlIjogImh0dHBzOi8vaXBmcy5pby9pcGZzL1FtWGJCU2VNV1pkM3dTeEFLTWhNU3M1bTVaekpKRFVIZFNpbW5VbUV4OEJ1RXA/ZmlsZW5hbWU9SkJBTi5wbmcifQ==

The operation is successful if the expected values are returned.

For instructions on inspecting the contents of tokenURI, refer to the tokenURI section linked below.

Conclusion

This article demonstrated how to deploy an NFT contract in Remix using WalletConnect. The walkthrough aimed to make the deployment process accessible even to readers without an engineering background.

I also publish articles on the following platforms.

https://chaldene.net/