Skip to content

5. The Collection Module

These are the functions used to view or manipulate the NFT Collection module.

5.1 nft_collection(nft_module)

This is the main function of the NFT collection module. It will prompt you to select the action that you want to do on the NFT collection module. Then it will call the corresponding function and that function takes on.

Source code in modules/collection.py
def nft_collection(nft_module):
    """
    This is the main function of the NFT collection module. It will prompt you to select the action that you want to do on the NFT collection module. Then it will call the corresponding function and that function takes on. 
    """

    # This is the list of the actions that you can do on the NFT collection module.
    actions = prompt([
        {
            'type': 'list',
            'name': 'action',
            'message': 'What do you want to do?',
            'choices': [
                Separator('-- Actions --'),
                {
                    'name': 'Mint an NFT',
                    'value': 'mint',
                    'short': 'Mint'
                },
                {
                    'name': 'Transfer an NFT',
                    'value': 'transfer',
                    'short': 'Transfer'
                },
                {
                    'name': 'View an NFT',
                    'value': 'view',
                    'short': 'View'
                },
                {
                    'name': 'View all NFTs of a specific owner',
                    'value': 'view_by_owner',
                    'short': 'View By Owner'
                },
                {
                    'name': 'Burn an NFT',
                    'value': 'burn',
                    'short': 'Burn'
                }
            ]
        }
    ])

    # Calling the corresponding function based on the action that you selected.
    if actions['action'] == 'mint':
        from .nft_collection.mint import mint_prompt
        mint_prompt(nft_module=nft_module)

    elif actions['action'] == 'transfer':
        from .nft_collection.transfer import transfer_prompt
        transfer_prompt(nft_module=nft_module)

    elif actions['action'] == 'view':
        from .nft_collection.view import view
        view(nft_module=nft_module)

    elif actions['action'] == 'burn':
        from .nft_collection.burn import burn
        burn(nft_module=nft_module)

    elif actions['action'] == 'view_by_owner':
        from .nft_collection.view_by_owner import view_by_owner
        view_by_owner(nft_module=nft_module)

    else:
        print(colored('No Action Selected', 'red'))
        sys.exit(1)

5.2 burn(nft_module)

The function is used to burn an NFT.

Source code in nft_collection/burn.py
def burn(nft_module) -> None:
    """
    The function is used to burn an NFT.
    """

    # Getting the NFT to burn
    burn_data = prompt([
        {
            'type': 'input',
            'name': 'id',
            'message': 'Enter the NFT ID',
            'default': "0",
        },
        {
            'type': 'confirm',
            'name': 'confirmation',
            'message': 'Do you want to burn the selected NFT?',
            'default': False,
        },

    ])

    # Fetching the NFT id
    id = int(burn_data['id'])

    # Confirming the burn
    if burn_data['confirmation']:
        try:
            # Burning the NFT
            nft_module.burn(id)
            print(colored('NFT burned successfully!', 'green'))

        except Exception as e:
            # Printing the error
            print(colored('NFT could not be burned. \n' + e, 'red'))

    else:
        # Reporting if cancelled
        print(colored('NFT not burned!', 'blue'))

5.3 mint(nft_module, name, description, image_uri, image_format='JPEG', properties={})

This function is used to mint an NFT.

Source code in nft_collection/mint.py
def mint(nft_module, name: str, description: str, image_uri: str, image_format='JPEG', properties={}) -> str:
    """
    This function is used to mint an NFT.
    """
    # Checking if the image_uri is a local file or a remote file.
    if image_format != 'URL':
        try:
            if image_uri == '':
                byte_im = b''
            else:
                try:
                    # If the image_uri is a local file, then we will read the file and convert it to a byte array.
                    im = Image.open(image_uri)
                    byte_im = io.BytesIO()
                    im.save(byte_im, format=image_format)
                    byte_im = byte_im.getvalue()
                    nft_module.mint(MintArg(name=name,
                                            description=description,
                                            image_uri=byte_im,
                                            properties=properties))
                    im_resize = im.resize((500, 500))
                    buf = io.BytesIO()
                    im_resize.save(buf, format=image_format)
                    byte_im = buf.getvalue()

                except FileNotFoundError:
                    # File not found error.
                    print('File not found')
                    return  

            # Minting the NFT
            nft_module.mint(MintArg(name=name,
                                    description=description,
                                    image_uri=byte_im,
                                    properties=properties))

        except requests.exceptions.ReadTimeout:
            return 'A time out has occured. But, in most cases this is not a problem and the NFT is minted anyway. So, try to cross check before trying again.\n'

    else:
        # If the image_uri is a URL, then we will pass it straight on.
        nft_module.mint(MintArg(name=name,
                                    description=description,
                                    image_uri=image_uri,
                                    properties=properties))

    return 'NFT minted successfully!\n'

5.4 transfer_prompt(nft_module)

This function is used to transfer an NFT.

Source code in nft_collection/transfer.py
def transfer_prompt(nft_module) -> None:
    """
    This function is used to transfer an NFT.
    """
    # Getting the NFT to transfer
    transfer_args = prompt([
        {
            'type': 'input',
            'name': 'to',
            'message': 'Who should receive the NFT?',
        },
        {
            'type': 'input',
            'name': 'id',
            'message': 'NFT Token ID',
            'default': '0'
        },
    ])
    try:
        # Trying to execute the transfer
        nft_module.transfer(to_address=transfer_args['to'],
                            token_id=transfer_args['id'],)
    except ContractLogicError:
        # Printing the error if the transfer failed
        print(colored(
            'Error: Either you do not own the NFT or some other error has occurred.', 'red'))
        return

    # Printing the success message
    print(colored('NFT transferred successfully!\n', 'green'))

5.5 view_by_owner(nft_module)

This function is used to view all NFTs of a specific owner.

Source code in nft_collection/view_by_owner.py
def view_by_owner(nft_module) -> None:
    """
    This function is used to view all NFTs of a specific owner.
    """

    # Getting the owner address
    view_data = prompt([
        {
            'type': 'input',
            'name': 'owner',
            'message': 'Enter the Owners\'s Address',
        }, {
            'type': 'list',
            'name': 'Print or Write to file?',
            'message': 'Do you want to print the NFT metadata or write it to a file?',
            'choices': [
                Separator('-- Print or Write to file --'),
                {
                    'name': 'Print',
                    'value': 'print',
                    'short': 'Print'
                },
                {
                    'name': 'Write to file',
                    'value': 'write',
                    'short': 'Write'
                }
            ]
        },
        {
            'type': 'input',
            'name': 'file_name',
            'message': 'Enter the file name (should be .json)',
            'default': "nft_metadata.json",
            'when': lambda answers: answers['Print or Write to file?'] == 'write',
            'validate': lambda answer: 'Please enter a valid file name' if not answer.endswith('.json') else True
        }
    ])

    # Fetching the owner address
    owner = view_data['owner']
    data = nft_module.get_owned(owner)

    # Printing the NFT metadata
    if view_data['Print or Write to file?'] == 'print':
        print(colored('NFTs owned by ' + owner + ':', 'green'))
        for i in range(len(data)):
            print(colored(
                f'{data[i].id}: Name: {data[i].name}, Description: { data[i].description }, Image: { data[i].image }, URL: { data[i].uri }', 'blue'))

    # Writing the NFT metadata to a file
    elif view_data['Print or Write to file?'] == 'write':
        data_dict = {}

        for i in range(len(data)):
            data_dict[str(i)] = {"ID": str(data[i].id), "Name": data[i].name, "Description": data[i].description, "Image": str(
                data[i].image), "uri": data[i].uri, "Properties": data[i].properties}

        with open(view_data['file_name'], 'w') as f:
            f.write(json.dumps(data_dict, indent=4))

5.6 view(nft_module)

This function is used to view an NFT.

Source code in nft_collection/view.py
def view(nft_module) -> None:
    """
    This function is used to view an NFT.
    """

    # Getting the NFT to view
    view_data = prompt([
        {
            'type': 'input',
            'name': 'id',
            'message': 'Enter the NFT ID',
            'default': "0",
        },
        {
            'type': 'list',
            'name': 'Print or Write to file?',
            'message': 'Do you want to print the NFT metadata or write it to a file?',
            'choices': [
                Separator('-- Print or Write to file --'),
                {
                    'name': 'Print',
                    'value': 'print',
                    'short': 'Print'
                },
                {
                    'name': 'Write to file',
                    'value': 'write',
                    'short': 'Write'
                }
            ]
        },
        {
            'type': 'input',
            'name': 'file_name',
            'message': 'Enter the file name (should be .json)',
            'default': "nft_metadata.json",
            'when': lambda answers: answers['Print or Write to file?'] == 'write',
            'validate': lambda answer: 'Please enter a valid file name' if not answer.endswith('.json') else True
        }
    ])
    # Retreiving the NFT data
    id = int(view_data['id'])
    data = nft_module.get(id)
    data_dict = {"ID": str(id), "Name": data.name, "Description": data.description, "Image": str(
        data.image), "uri": data.uri, "Properties": data.properties}

    # Printing the NFT metadata
    if view_data['Print or Write to file?'] == 'print':
        print(colored('NFT Data:', 'green'))
        for key, value in data_dict.items():
            print(colored(f'{key}: {value}', 'blue'))

    # Writing the NFT metadata to a file
    else:
        with open(view_data['file_name'], 'w') as f:
            f.write(json.dumps(data_dict))
        print(colored('NFT Metadata written to file successfully!', 'green'))

Last update: 2022-01-25
Authors: Arpan Pandey