#  A contract code about NFT

By [521918.eth](https://paragraph.com/@521918-eth) · 2023-01-20

---

here is an example contract code for an NFT (non-fungible token) using the Solidity programming language for the Ethereum blockchain:

pragma solidity ^0.8.0;

contract NFT { // Events event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId);

    // Variables
    mapping(uint256 => address) public tokenOwner;
    mapping(uint256 => address) public tokenApproval;
    mapping(address => mapping(uint256 => bool)) public ownedTokens;
    mapping(address => mapping(uint256 => bool)) public approvedTokens;
    address public owner;
    
    // Functions
    constructor() public {
        owner = msg.sender;
    }
    
    function mint(address to, uint256 tokenId) public {
        require(msg.sender == owner, "Only owner can mint new tokens.");
        require(!tokenOwner[tokenId], "Token with this ID already exists.");
        
        tokenOwner[tokenId] = to;
        ownedTokens[to][tokenId] = true;
        emit Transfer(address(0), to, tokenId);
    }
    
    function transfer(address to, uint256 tokenId) public {
        require(tokenOwner[tokenId] == msg.sender, "You do not own this token.");
        require(to != address(0), "Cannot transfer to address 0x0.");
        
        clearApproval(tokenId);
        tokenOwner[tokenId] = to;
        ownedTokens[msg.sender][tokenId] = false;
        ownedTokens[to][tokenId] = true;
        emit Transfer(msg.sender, to, tokenId);
    }
    
    function approve(address approved, uint256 tokenId) public {
        require(tokenOwner[tokenId] == msg.sender, "You do not own this token.");
        
        tokenApproval[tokenId] = approved;
        approvedTokens[msg.sender][tokenId] = true;
        emit Approval(msg.sender, approved, tokenId);
    }
    
    function clearApproval(uint256 tokenId) public {
        require(tokenOwner[tokenId] == msg.sender, "You do not own this token.");
        
        tokenApproval[tokenId] = address(0);
        approvedTokens[msg.sender][tokenId] = false;
    }
    
    function takeOwnership(uint256 tokenId) public {
        require(tokenApproval[tokenId] == msg.sender, "You are not approved to take this token.");
        
        clearApproval(tokenId);
        tokenOwner[tokenId] = msg.sender;
        ownedTokens[tokenApproval[tokenId]][tokenId] = false;
        ownedTokens[msg.sender][tokenId] = true;
        emit Transfer(tokenApproval[tokenId], msg.sender, tokenId);
    }
    

}

This code creates a smart contract for an NFT that allows for minting new tokens, transferring ownership of tokens, approving other addresses to take ownership, and taking

---

*Originally published on [521918.eth](https://paragraph.com/@521918-eth/a-contract-code-about-nft)*
