Giter VIP home page Giter VIP logo

erc721's Introduction

Build Status codecov NPM Version Bug Bounty

ERC-721 Token — Reference Implementation

NOTICE: This repository has been transferred from 0xcert to Nibbstack and thus renamed from 0xcert/ethereum-erc721 to @nibbstack/erc721.

This is the complete reference implementation of the ERC-721 non-fungible token standard for the Ethereum and Wanchain blockchains. It is also compatible with other EVM compatible chains like Binance Smart Chain (BSC), Avalanche (AVAX) etc. This is an open-source project, complete with Hardhat testing.

The purpose of this implementation is to provide a good starting point for anyone who wants to use and develop non-fungible tokens on the Ethereum and Wanchain blockchains. Instead of re-implementing the ERC-721 yourself you can use this code which has gone through multiple audits and we hope it will be extensively used by the community in the future. Note that this implementation is more restrictive then the ERC-721 standard since it does not support payable function calls out of the box. You are however free to add this yourself.

If you are looking for a more feature-rich and advanced ERC-721 implementation, then check out the 0xcert Framework.

Structure

All contracts and tests are in the src folder. There are multiple implementations and you can select between:

  • nf-token.sol: This is the base ERC-721 token implementation (with support for ERC-165).
  • nf-token-metadata.sol: This implements optional ERC-721 metadata features for the token contract. It implements a token name, a symbol and a distinct URI pointing to a publicly exposed ERC-721 JSON metadata file.
  • nf-token-enumerable.sol: This implements optional ERC-721 support for enumeration. It is useful if you want to know the total supply of tokens, to query a token by index, etc.

Other files in the tokens and utils directories named erc*.sol are interfaces and define the respective standards.

Mock contracts showing basic contract usage are available in the mocks folder.

There are also test mocks that can be seen here. These are specifically made to test different edge cases and behaviours and should NOT be used as a reference for implementation.

Requirements

  • NodeJS 12+ is supported
  • Windows, Linux or macOS

Installation

npm

This is the recommended installation method if you want to use this package in your JavaScript project.

This project is released as an npm module. You must install it using the npm command:

$ npm install @nibbstack/[email protected]

Source

This is the recommended installation method if you want to improve the nibbstack/erc721 project.

Clone this repository and install the required npm dependencies:

$ git clone [email protected]:nibbstack/erc721.git
$ cd ethereum-erc721
$ npm install

Make sure that everything has been set up correctly:

$ npm run test

Usage

npm

To interact with this package's contracts within JavaScript code, you simply need to require this package's .json files:

const contract = require("@nibbstack/erc721/abi/NFTokenEnumerable.json");
console.log(contract);

Remix IDE (Ethereum only)

You can quickly deploy a contract with this library using Remix IDE. Here is one example.

You have created and have possession of unique glass-blown artwork (each having a serial/lot number) which you would like to sell using the Ethereum or Wanchain mainnet. You will sell non-fungible tokens and the buyers would be able to trade those to other people. One token per piece of artwork. You commit to anybody holding these tokens that they may redeem their token and take physical possession of the art.

To do this, simply paste the code below into Remix and deploy the smart contract. You will "mint" a token for each new piece of artwork you want to see. Then you will "burn" that token when you surrender physical possession of the piece.

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

import "https://github.com/nibbstack/erc721/src/contracts/tokens/nf-token-metadata.sol";
import "https://github.com/nibbstack/erc721/src/contracts/ownership/ownable.sol";

/**
 * @dev This is an example contract implementation of NFToken with metadata extension.
 */
contract MyArtSale is
  NFTokenMetadata,
  Ownable
{

  /**
   * @dev Contract constructor. Sets metadata extension `name` and `symbol`.
   */
  constructor()
  {
    nftName = "Frank's Art Sale";
    nftSymbol = "FAS";
  }

  /**
   * @dev Mints a new NFT.
   * @param _to The address that will own the minted NFT.
   * @param _tokenId of the NFT to be minted by the msg.sender.
   * @param _uri String representing RFC 3986 URI.
   */
  function mint(
    address _to,
    uint256 _tokenId,
    string calldata _uri
  )
    external
    onlyOwner
  {
    super._mint(_to, _tokenId);
    super._setTokenUri(_tokenId, _uri);
  }

}

You should contact a lawyer before holding an auction, or selling anything. Specifically, laws for auctions vary wildly by jurisdiction. This application is provided only as an example of the technology and is not legal advice.

Validation

You can check the validity of the smart contract, the correctness of the implementation and the supported functions of the respective smart contract using the online validator at https://erc721validator.org/.

Playground

Ethereum - Ropsten testnet

We already deployed some contracts to the Ropsten network. You can play with them RIGHT NOW. No need to install the software. In this test version of the contract, anybody can mint or burn tokens, so don't use it for anything important.

Contract Token address Transaction hash
nf-token.sol 0xd8bbf8ceb445de814fb47547436b3cfeecadd4ec 0xaac94c9ce15f5e437bd452eb1847a1d03a923730824743e1f37b471db0f16f0c
nf-token-metadata.sol 0x5c007a1d8051dfda60b3692008b9e10731b67fde 0x1e702503aff40ea44aa4d77801464fd90a018b7b9bad670500a6e2b3cc281d3f
nf-token-enumerable.sol 0x130dc43898eb2a52c9d11043a581ce4414487ed0 0x8df4c9b73d43c2b255a4038eec960ca12dae9ba62709894f0d85dc90d3938280

Wanchain - testnet

We already deployed some contracts to testnet network. You can play with them RIGHT NOW. No need to install software. In this test version of the contract, anybody can mint or burn tokens, so don't use it for anything important.

Contract Token address Transaction hash
nf-token.sol 0x6D0eb4304026116b2A7bff3f46E9D2f320df47D9 0x9ba7a172a50fc70433e29cfdc4fba51c37d84c8a6766686a9cfb975125196c3d
nf-token-metadata.sol 0xF0a3852BbFC67ba9936E661fE092C93804bf1c81 0x338ca779405d39c0e0f403b01679b22603c745828211b5b2ea319affbc3e181b
nf-token-enumerable.sol 0x539d2CcBDc3Fc5D709b9d0f77CaE6a82e2fec1F3 0x755886c9a9a53189550be162410b2ae2de6fc62f6791bf38599a078daf265580

Contributing

See CONTRIBUTING.md for how to help out.

Bug bounty

You are somebody that reads the documentation of smart contracts and understands how the ERC-721 Token Reference Implementation works. So you have unique skills and your time is valuable. We will pay you for your contributions to this project in the form of bug reports.

If your project depends on ERC-721 or you want to help improve the assurance of this project then you can pledge a bounty. This means you will commit to paying researchers that demonstrate a problem. Contact us at [email protected] if interested. Thank you.

Read the full bug bounty program.

Licence

See LICENSE for details.

erc721's People

Contributors

chiefpulpo avatar dafky2000 avatar flockonus avatar fulldecent avatar lknix avatar mg6maciej avatar momannn avatar nikhildesai27 avatar tchajed avatar xpepermint avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

erc721's Issues

Update and refactor tests

Tests should be testing a single unit (function). Currently we don't test all functions directly since some of them are tested through other functions. This doesn't follow the best practices because it's misleading when tests start to fail and it leaves out edge cases. Ideally, tests should:

  1. Every test should test a single unit.
  2. Every test should set up the required contract state directly prior to testing.
  3. Every unit should be fully covered.

Bug bounty program for ERC-721 smart contracts (v1)

The 0xcert team has decided to provide a valid and secure ERC-721 implementation for the Ethereum community. We recognize the need and necessity of a security audit in order to keep all further usage safe and secure. In this light, a bug bounty program is being launched and we would love if the community can help find and disclose security issues and vulnerabilities.

About implementation

ERC-721 is a standard interface for non-fungible tokens on the Ethereum blockchain, invented by Dieter Shirley and written by William Entriken. The 0xcert development team decided to build the fully compatible implementation, which is going to be open-source and available to everyone.

Scope & rules

This bug bounty program will run from 2018-05-16 at 00:01 CET to 2018-07-16 at 23:59 CET. All of the discussions and code in this bug bounty program are publicly available in this repository. Help us find any problems with the ERC-721 implementation and you will be rewarded.

  • Be descriptive and detailed when describing your issue.
  • Fix it and recommend a way to solve the problem.
  • Include a truffle or detailed test case that we can reproduce.
  • Issues that have already been published here or are already disclosed to the 0xcert team are not eligible for rewards.
  • Social engineering, XKCD#538 attacks, bringing down Ropsten/Metamask/Infura are not in scope and will NOT be paid a reward.
  • Only the contracts regarding the ERC-721 are in scope, our website is not in scope.
  • GitHub issues is the only way to report issues and request rewards.
  • The 0xcert team has a complete and final judgment on the acceptability of issue reports.

Rewards

  • We will distribute up to 5 ETH among all participants that reported a unique high severity bug.
  • Reports for medium and low bugs will receive our 0xcert t-shirt and an honorable mention.
Severity Examples
High Allowing tokens to get lost, stolen, or become unusable.
Medium An undocumented function, documentation of a user-facing function that does not completely explain what is happening from the user’s perspective (i.e. unspecified side effects).
Low Any typo that does not affect program functionality. Recommended changes to functionality which are helpful and optimize the code.

Note that if the EIP standard is amended then an issue will be Low severity if it points this out to us. We will support the updated standard.

Additional bounty

We are providing another bounty for a token that builds on top of this implementation called Xcert. If you are interested in participating in that bounty you can check it out here: 0xcert/ethereum-xcert#24

Token naming suggestions

How about if we change current naming that:

  1. ERC721.sol (interface) -> ERC721Interface.sol or ERC721Standard.sol and ERC721implementation.sol -> ERC721.sol;
  2. Alternatively we move interfaces in tokens/interfaces and name both ERC721.sol (interface and implementation).

If the plan is that our implementation gets reused then we need to have simpler names. ERC721implementation is way too long and verbose. Thoughts?

Add selling points

Every GitHub project needs selling points

  • Complete implementation (all functions implemented)
  • XX% code coverage Truffle testing
  • It is subclassable so you can add your own features while relying on our base work
  • The code is verified by the community and has an active bug bounty

ERC 721: incomplete case for _mint

There is currently only internal _mint function, which can't be used. Either we complete it with some external function for minting or add a comment describing this is by default NOT implemented / used. We probably want to keep it since it has the code which shows how to properly mint a token using our implementation.

Deploy main net

Just for fun, could you please:

Then you can add to the README:

We deployed a contract you can play with RIGHT NOW. No need to install software. In this test version of the contract, anybody can mint or burn tokens, so don't use it for anything important.

Mainnet address: xxxxx
Ropsten address: xxxxx

Add LICENSE file

README.md includes the line Licence (MIT).

Can you please add the appropriate LICENSE file to the repo.

Metadata extension is not compliant

Currently metadata is not compliant with the standard. Standard is pure, implementation is view.

Will consider to change the standard because everyone is doing this. But for now this should be noted.

`clearApproval` should not fire event

Because this function is called only from _burn and _transfer in which cases also Transfer is emitted, clearApproval should only set state to 0 (might be more gas efficient to do it conditionally).

According to spec (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md)

    ///  When a Transfer event emits, this also indicates that the approved
    ///  address for that NFT (if any) is reset to none.
    event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);

OZ also does it incorrectly, but "slightly" better.
https://github.com/OpenZeppelin/openzeppelin-solidity/blob/07020e954475a4fdd36e0252e88717b60f790b71/contracts/token/ERC721/ERC721BasicToken.sol#L300-L303

Gas use optimization - removing `ownerToNFTokenCount`

If you move implementation of tokenOfOwnerByIndex and related fields (ownerToIds and idToOwnerIndex) to NFToken, you can remove ownerToNFTokenCount and use ownerToIds[_owner].length in balanceOf. This saves gas on two updates of ownerToNFTokenCount every time token is transferred and one when minted or burned.

This doesn't break compatibility with ERC721 spec, as you may leave ERC721 and ERC721Enumerable as they are now.
This has drawback of slightly more expensive deploy and transfers for simpler NFToken, but is cheaper for full NFTokenEnumerable (+ NFTokenMetadata) and assuming OpenSea and others will require enumeration and developers will want to be listed there, this makes it cheaper in most cases. Also additional, non-standard funcitonality provided by tokenOfOwnerByIndex in basic NFToken might be a good thing.

Remove truffle compilation warnings

After updating to the latest version of solidity we can see the warnings below:

Compilation warnings encountered:

/Users/xpeper/Work/0xcert.org/repositories/ethereum-erc721/contracts/tokens/ERC721.sol:142:3: Warning: Functions in interfaces should be declared external.
  function getApproved(
  ^ (Relevant source part starts here and spans across multiple lines).
,/Users/xpeper/Work/0xcert.org/repositories/ethereum-erc721/contracts/mocks/NFTokenMetadataEnumerableMock.sol:6:1: Warning: Base constructor arguments given twice.
contract NFTokenMetadataEnumerableMock is NFTokenEnumerable, NFTokenMetadata {
^ (Relevant source part starts here and spans across multiple lines).
/Users/xpeper/Work/0xcert.org/repositories/ethereum-erc721/contracts/tokens/NFTokenEnumerable.sol:35:5: First constructor call is here:
    NFToken()
    ^-------^
/Users/xpeper/Work/0xcert.org/repositories/ethereum-erc721/contracts/tokens/NFTokenMetadata.sol:35:5: Second constructor call is here:
    NFToken()
    ^-------^

Error getting while executing transferFrom function calling

Hi,
When I am trying to execute
const { abi } = require('./build/contracts/MyNFToken.json');

const account0 = '0x294a4c67667565765668e3329a2b219a1f3d8c22'; // for eg: owner address
const account1 = '0x294a4c67670c0dae6ce8e3329a2b219a1f3d8c22'; // another account (you can create it)
const MyNFTokenContract = web3.eth.contract(abi);
const MyNFTokenInstance = MyNFTokenContract.at();
MyNFTokenInstance.transferFrom(account0,account1,"1234");
Error: invalid address
at SolidityFunction.execute (/usr/local/lib/node_modules/truffle/build/webpack://web3/lib/web3/function.js:256:1)
at SolidityFunction.sendTransaction (/usr/local/lib/node_modules/truffle/build/webpack:/
/web3/lib/web3/function.js:170:1)
at Eth.send [as sendTransaction] (/usr/local/lib/node_modules/truffle/build/webpack://web3/lib/web3/method.js:139:1)
at Method.toPayload (/usr/local/lib/node_modules/truffle/build/webpack:/
/web3/lib/web3/method.js:114:1)
at Method.formatInput (/usr/local/lib/node_modules/truffle/build/webpack://web3/lib/web3/method.js:88:1)
at Array.map ()
at /usr/local/lib/node_modules/truffle/build/webpack:/
/web3/lib/web3/method.js:89:1
at inputTransactionFormatter (/usr/local/lib/node_modules/truffle/build/webpack://web3/lib/web3/formatters.js:100:1)
at inputAddressFormatter (/usr/local/lib/node_modules/truffle/build/webpack:/
/web3/lib/web3/formatters.js:274:1)
Why its showing like that? (mint,balanceof,safeTransferfrom is working but for approval,setApproveForAll etc is not working...showing same error only);
I have done in PrivateNet.
Help me to resolve this issue...

How will i fetch .json files from build folder in truffle using truffle console?

Hi,
How will I call .json files from build folder Truffle...?Truffle migration successfully completed..I worked in Privatenet...Then I tried


truffle console
truffle(development)> const { abi } = require('./build/contracts/MyNFT.json');
**Undefined**

Please help me to figured out this issue? Why it's showing undefined?

ERC721 Enumerable: purpose of idToIndex?

We set it in _mint function and don't use it anywhere.

contracts/tokens/ERC721EnumerableImplementation.sol:  mapping(uint256 => uint256) internal idToIndex;
contracts/tokens/ERC721EnumerableImplementation.sol:    idToIndex[_id] = tokens.length;

[bug] Resetting of value to non-zero when burning last token

When burn is called on the last token, code in removeNFToken will not clear idToOwnerIndex for it.
Order of these statements should be changed, but even better to use check for last token mentioned in previous issue #104.

    idToOwnerIndex[_tokenId] = 0;
    idToOwnerIndex[lastToken] = tokenToRemoveIndex;

[optimization] Gas use in `removeNFToken`

These two lines don't need to be executed when tokenToRemoveIndex == lastTokenIndex.

    ownerToIds[_from][tokenToRemoveIndex] = lastToken;
    ownerToIds[_from][lastTokenIndex] = 0;

Next line covers clearing it:

    ownerToIds[_from].length--;

Consider providing enumerable + metadata token

I believe name of NFToken could be misleading as users might think this is the one they would want to use. I suggest renaming it to NFTokenBasic and adding new one NFToken (or NFTokenFull) that only extends NFTokenEnumarable and NFTokenMetadata.

PrivateNet Integration

Hi,
Is this code only worked in Ropsten? I just want to integrate this code to my private Net.
I saw one command : npm run migrate -- --network Ropsten ( works in Ropsten) instead of this I used
npm run migrate -- --network localhost:8545. But it's not connecting. How will I resolved my issue?
My network id : 54 ( That i gave to truffle.js).

ERC 721: canTransfer should modify _transfer function

I think canTransfer modifier should be moved to private _transfer function instead of other wrapping functions. If somebody decides to build upon our implementation then decoupling these could pose a serious risk: one just needs to add another function which calls _transfer and forget to add the modifier. Or changes _transfer to external.

Comply with 165

The NFToken constructor should invoke the SupportsInterface constructor.

5300 Gas Cost for Unnecessary State Change

In the removeNFToken function in the NFTokenEnumerable.sol file ownerToIds[_from][lastTokenIndex] is set to 0 twice instead of once. This is redundant and costs about 5300 extra gas.

Here is the code I am talking about:

 ownerToIds[_from][lastTokenIndex] = 0;
 
 ownerToIds[_from].length--;

The first line obviously sets ownerToIds[_from][lastTokenIndex] to 0. Reducing the length of the array also sets ownerToIds[_from][lastTokenIndex] to 0.

So it makes sense to get rid of this line: ownerToIds[_from][lastTokenIndex] = 0;.

ERC 721: Code reuse

If issue #9 gets accepted then _safeTransferFrom should just call transferFrom before checking if recipient is a contract.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.