Create an NFT Whitelist Smart Contract on Celo with Python

Create an NFT Whitelist Smart Contract on Celo with Python https://celo.academy/uploads/default/optimized/2X/2/2d3860d09121ba11afcc653ed6d204adabe0b9ac_2_1024x576.png
none 0.0 0

What is a Whitelist

A whitelist is a set of items, entities, or individuals that are considered to be approved, trusted, or granted certain privileges or access rights. In the context of computer systems and networks, a whitelist is often used as a security measure to control and restrict access to specific resources.

When a whitelist is implemented, only the items or entities included in the list are allowed access, while all others are denied by default. For example, in network security, a whitelist may specify specific IP addresses, domain names, or email addresses that are permitted to access a particular network or service. Any requests or communications coming from sources not listed in the whitelist will be blocked or rejected.

Prerequisites

You’ll need to have a good understanding or have worked with, python, pip, and solidity , web3.py to get along and understand this article just fine.

What is an NFT Whitelist

In this context of an NFT, The whitelist would refer to a list of specific addresses or individuals who are granted privileged access or participation rights in relation to a particular non-fungible token (NFT) project or sale. The NFT whitelist is often used to manage and control the distribution, sale, or ownership of limited edition or exclusive NFTs.

When an NFT whitelist is implemented, only the addresses or individuals included in the list are given the opportunity to purchase or obtain the designated NFTs. This can be used to reward loyal supporters, early investors, or community members who have met specific criteria or requirements. By restricting access to a whitelist, NFT projects can create a sense of exclusivity and scarcity around their tokens.

The criteria for being included in an NFT whitelist can vary depending on the project. It may involve holding a specific amount of a particular cryptocurrency, participating in a pre-sale, being a member of a specific community or group, or fulfilling other conditions set by the project creators. The whitelist is typically managed through smart contracts on blockchain platforms, ensuring transparency and immutability of the whitelist process.

Setting up your Environment

  1. First create a workspace on your preferred code editor, and open a terminal to execute commands on the workspace.

  2. Inside the terminal run the code below

mkdir Celo_NFT_Whitelist
cd Celo_NFT_Whitelist
  1. Next to fire up (create and activate) a new virtual environment run the code below.
python3 -m venv venv
source venv/bin/activate
  1. Now, run the command below to download the frameworks you’ll need for compiling and deploying the your smart contract.
pip install python-dotenv web3 py-solc-x
  1. Next, run the commands below to start up the truffle.
npm install -g truffle
npm install -g truffle-flattener

The smart Contract

Here is the complete code for the whitelist smart contract. Navigate to the contract folder and create a new file whitelist.sol, where you’ll have the smart contract pasted below:

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;


contract Whitelist {

    // Max number of whitelisted addresses allowed
    uint8 public maxWhitelistedAddresses;

    // Create a mapping of whitelistedAddresses
    // if an address is whitelisted, we would set it to true, it is false by default for all other addresses.
    mapping(address => bool) public whitelistedAddresses;

    // numAddressesWhitelisted would be used to keep track of how many addresses have been whitelisted
    // NOTE: Don't change this variable name, as it will be part of verification
    uint8 public numAddressesWhitelisted;

    // Setting the Max number of whitelisted addresses
    // User will put the value at the time of deployment
    constructor(uint8 _maxWhitelistedAddresses) {
        maxWhitelistedAddresses =  _maxWhitelistedAddresses;
    }

    /**
        addAddressToWhitelist - This function adds the address of the sender to the
        whitelist
     */
    function addAddressToWhitelist() public {
        // check if the user has already been whitelisted
        require(!whitelistedAddresses[msg.sender], "Sender has already been whitelisted");
        // check if the numAddressesWhitelisted < maxWhitelistedAddresses, if not then throw an error.
        require(numAddressesWhitelisted < maxWhitelistedAddresses, "More addresses cant be added, limit reached");
        // Add the address which called the function to the whitelistedAddress array
        whitelistedAddresses[msg.sender] = true;
        // Increase the number of whitelisted addresses
        numAddressesWhitelisted += 1;
    }

}
  • The contract defines a maximum number of whitelisted addresses allowed (maxWhitelistedAddresses) and keeps track of the number of addresses that have been whitelisted (numAddressesWhitelisted).
  • It utilizes a mapping called whitelistedAddresses to associate addresses with a boolean value indicating whether they are whitelisted. By default, all addresses are set to false (not whitelisted).
  • The addAddressToWhitelist function allows the sender of the transaction to add their address to the whitelist. It performs checks to ensure that the sender has not already been whitelisted and that the maximum number of whitelisted addresses has not been reached.
  • If the checks pass, the sender’s address is added to the whitelistedAddresses mapping, and the count of whitelisted addresses (numAddressesWhitelisted) is incremented.

This contract provides a basic implementation of a whitelist, allowing for the controlled inclusion of addresses based on predefined limits.

Now create a new file, truffle-config.js in the root directory, and paste the javascript code below into the file.

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*",
    },
  },
  compilers: {
    solc: {
      version: "0.8.0",
    },
  },
};

  • Next, run the command,
    truffle-flattener Whitelist.sol > FlattenedWhitelist.sol, which will create a flattened version of your smart contract, in the FlattenedWhitelist.sol file.

  • Head over to your deploy.js script and replace the entire code there with the following deploy script below:

import json
import os
from solcx import compile_standard, install_solc
from dotenv import load_dotenv
from web3.middleware import geth_poa_middleware
from web3 import Web3
load_dotenv()
# Install specific Solidity compiler version
install_solc("0.8.0")
# Set up web3 connection
provider_url = os.environ.get("CELO_PROVIDER_URL")
w3 = Web3(Web3.HTTPProvider(provider_url))
assert w3.is_connected(), "Not connected to a Celo node"
# Set deployer account and private key
deployer = os.environ.get("CELO_DEPLOYER_ADDRESS")
private_key = os.environ.get("CELO_DEPLOYER_PRIVATE_KEY")
with open("FlattenedWhitelist.sol", "r") as file:
    solidity_code = file.read()
# Add Geth POA middleware to handle extraData field in Celo transactions
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
# Compile the Solidity smart contract
compiled_sol = compile_standard({
    "language": "Solidity",
    "sources": {
        "FlattenedWhitelist.sol": {
            "content": solidity_code
        }
    },
    "settings": {
        "outputSelection": {
            "*": {
                "*": ["metadata", "evm.bytecode", "evm.deployedBytecode", "abi"]
            }
        },
        "optimizer": {
            "enabled": True,
            "runs": 200
        }
    }
})
# Get the bytecode, contract data, and ABI
contract_data = compiled_sol['contracts']['FlattenedWhitelist.sol']['Whitelist']
bytecode = contract_data['evm']['bytecode']['object']
abi = json.loads(contract_data['metadata'])['output']['abi']
# Deploy the contract
nonce = w3.eth.get_transaction_count(deployer)
transaction = {
    'nonce': nonce,
    'gas': 2000000,
    'gasPrice': w3.eth.gas_price,
    'data': bytecode,
}
signed_txn = w3.eth.account.sign_transaction(transaction, private_key)
transaction_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
transaction_receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)
# Get the contract address
contract_address = transaction_receipt['contractAddress']
print(f"Contract deployed at address: {contract_address}")
  • Finally, run the command python deploy.py
    and you’ll have your whitelist contract deployed on the Celo blockchain.

Next Step

Here is a list of a similar article to help you delve deeper into the world of NFTs:

  1. Build an NFT Marketplace for Tech Artisans on Celo

  2. Creating a Celo-based Non-Fungible Token

  3. Creating, Deploying, and Minting your ERC1155 Token on Celo

Conclusion

This article explored the process of creating an NFT whitelist smart contract on Celo using Python. By leveraging the Celo blockchain and Python programming language, as a developer, you can implement a secure and customizable whitelist functionality for NFTs. You have learned essential concepts such as smart contract deployment, address whitelisting, and access restriction through modifiers. By following the step-by-step guide, developers can gain a deeper understanding of how to build a whitelist smart contract and adapt it to their specific NFT projects on the Celo platform. With this knowledge, NFT ecosystems can prioritize controlled access and enhance the user experience for participants.

About the Author

Mayowa Julius Ogungbola

A Software Engineer and Technical writer always open to working on new ideas. I enjoy working on GitHub and you could also find out what I tweet about and connect with me on LinkedIn.

Reference

  1. Source code

  2. Web3.py Documentation

3 Likes

Approved for you to get started. You can manage the tutorial here by changing the category to Proposals > In Progress then Proposals > Review as you complete the tutorial. Thanks!

Hey @Phenzic, I will be reviewing your piece in 1 to 2 days.

@Phenzic - please replace the proposal with your content. Thanks!

Thanks, @Celo_Academy I couldn’t update the proposal earlier before the update you made.

3 Likes

Great work @Phenzic your article is well detailed, and everything works fine.
Prerequisites > Setting up your Environment
change to:

  1. First, create a workspace on your preferred code editor, and open a terminal to execute commands on the workspace.
    Conclusion > NextStep
    Remove the first “About the Author”

I’ve made the changes you suggested @kinyichukwu

2 Likes

Great job :fireworks:
I’ll be moving your article to publish.