Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Last active December 29, 2022 05:24
Show Gist options
  • Save mattdesl/33cd28ffd37749db8dc68a3c936d86a8 to your computer and use it in GitHub Desktop.
Save mattdesl/33cd28ffd37749db8dc68a3c936d86a8 to your computer and use it in GitHub Desktop.

NFT Basics

Pseudo-code for an NFT contract that:

  • Allows "minting" (creation of a token)
  • Allows "transfer" (moving token from wallet A to B)
  • Allows querying the "current owner of a token"
  • Allows querying the "metadata" of a token (often just a IPFS hash which points to media + info)

This example is meant to illustrate some of the core concepts behind ERC 721, which is the basis for most NFTs we trade today.

Metadata

Usually the metadata is a single hash string such as 13ZcYQ53Fh9ESxbiuE827QkvikG6NK8n25cdmWHsKCtF61, which is the output from hashing a metadata JSON, roughly something like:

{
  "name": "My Cool NFT",
  "description": "Description of the coolest NFT", 
  "media": "ipfs://QmWc6YHE815F8kExchG9kd2uSsv7ZF1iQNn23bt5iKC6K3"
}
// Global Token ID counter
Counter = 0
// Mapping from Token ID to user wallet address
Database = Map<int, address>{}
// Mapping from Token ID to its associated metadata
TokenMetadatas = Map<int, string>{}
// Mint/create a NFT and assign it to a new wallet address
function CreateToken (ownerAddress, metadata) {
// Optional: restrictions such as who can mint, enforce limited edition or 1/1, etc
if (Query.address != Artist) {
throw "Only the Artist can create a new Token"
}
// Get a unique ID for the Token and increment global Counter
id = Counter
Counter += 1
// Assign the unique Token ID to its new owner
Database[id] = ownerAddress
// Associate the token with data, eg: IPFS URI which describes media + info
TokenMetadatas[id] = metadata
}
// Query the metadata (eg: IPFS URI) for the given Token ID
function TokenMetadata (id) {
return TokenMetadatas[id]
}
// Query the wallet address that currently owns the specified Token ID
function OwnerOf (id) {
return Database[id]
}
// Allow owner to transfer their token (NFT) from one wallet to another
function TransferToken (id, newOwnerAddress) {
// Limit so that only the owner of that token can query this function
if (Query.address != Database[id]) {
throw "Only the current Token Owner can transfer their Token"
}
// Assign the Token ID to its new wallet address
Database[id] = newOwnerAddress
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment