NFT & Marketplace Contracts with royalties and fungible token support. Sample React app included.

Related tags

nft-market
Overview

NFT Market Reference Implementation

A PoC backbone for NFT Marketplaces on NEAR Protocol.

Reference

Changelog

Changelog

Progress:

  • basic purchase of NFT with FT
  • demo pay out royalties (FTs and NEAR)
  • test and determine standards for markets (best practice?) to buy/sell NFTs (finish standard) with FTs (already standard)
  • demo some basic auction types, secondary markets and
  • frontend example
  • first pass / internal audit
  • connect with bridged tokens e.g. buy and sell with wETH/nDAI (or whatever we call these)

Known Issues / Implementation Details for Markets

  • approve NFT on marketplace A and B
  • it sells on B
  • still listed on A
  • user Alice goes to purchase on marketplace A but this will fail
  • the token has been transferred already and marketplace A has an incorrect approval ID for this NFT

There are 3 potential solutions:

  1. handle in market contract - When it fails because nft_transfer fails, marketplace could make promise call that checks nft_token owner_id is still sale owner_id and remove sale. This means it will still fail for 1 user.
  2. handle with backend - run a cron job to check sales on a regular interval. This potentially avoids failing for any user.
  3. remove from frontend (use frontend or backend) - for every sale, check that sale.owner_id == nft.owner_id and then hide these sale options in the frontend UI. Heavy processing for client side, so still needs a backend.
  4. let it fail client side then alert backend to remove sale. No cron. Still fails for 1 user.

Matt's opinion: Option (2/3) is the best UX and also allows your sale listings to be the most accurate and up to date. If you're implementing a marketplace, you most likely are running backend somewhere with the marketplace owner account. If you go with Option 3 you can simply update a list of "invalid sales" and filter these before you send the sales listings to the client. If you decided to go with 2, modify the marketplace remove_sale to allow your marketplace owner account to remove any sales.

Notes:

High level diagram of NFT sale on Market using Fungible Token: image

Remove the FT steps for NEAR transfers (but nft_transfer_payout and resolve_purchase still the same).

Differences from nft-simple NFT standard reference implementation:

  • anyone can mint an NFT
  • Optional token_type
  • capped supply by token_type
  • lock transfers by token_token
  • enumerable.rs

Working

Frontend App Demo: /test/app.test.js/

  • install, deploy, test yarn && yarn test:deploy
  • run app - yarn start

App Tests: /test/app.test.js/

  • install, deploy, test yarn && yarn test:deploy
  • if you update contracts - yarn test:deploy
  • if you update tests only - yarn test

NFT Specific Notes

Associated Video Demos (most recent at top)

Live App Review 25 - NFT Market Test and Deploy

Live App Review 29 - Consensus 2021 NEAR Protocol Eco-Friendly NFTs

Live App Review 31 - NFT Market Reduction to NFT Simple

Older Walkthrough Videos:

NEAR Protocol - Demo NFT Marketplace Walkthough

Live App Review 19 - NFT Marketplace with Fungible Token Transfers and Royalty Distribution

Some additional ideas around user onboarding:

NEAR Protocol - NFT Launcher & Easy User Onboarding Demo - Hackathon Starter Kit!

Detailed Installation / Quickstart

If you don't have Rust

Install Rust https://rustup.rs/

If you have never used near-cli

  1. Install near-cli: npm i -g near-cli
  2. Create testnet account: Wallet
  3. Login: near login

Installing and Running Tests for this Example

  1. Install everything: yarn && (cd server && yarn)
  2. Deploy the contract and run the app tests: yarn test:deploy
  3. (WIP) Start server and run server tests: cd server && yarn start then in another terminal from the root yarn test:server

Notes

  • If you ONLY change the JS tests use yarn test.
  • If you change the contract run yarn test:deploy again.
  • If you run out of funds in the dev account run yarn test:deploy again.
  • If you change the dev account (yarn test:deploy) the server should restart automatically, but you may need to restart the app and sign out/in again with NEAR Wallet.

Moar Context

There's 3 main areas to explore:

  • frontend app - shows how to create guest accounts that are added to the app contract via the nodejs server. Guests can mind NFTs, put them up for sale and earn NEAR tokens. When the guest has NEAR they can upgrade their account to a full account.
  • app.test.js (demos frontend only tests)

Owner Account, Token Account, etc...

The tests are set up to auto generate the dev account each time you run test:deploy e.g. you will get a new NFT contract address each time you run a test.

This is just for testing. You can obviously deploy a token to a fixed address on testnet / mainnet, it's an easy config update.

Guests Account (key and tx gas sponsorship)

When you run app / server tests. There's a contract deployed and a special account created guests.OWNER_ACCOUNT_ID to manage the sponsored users (the ones you will pay for gas fees while onboarding). This special "guests" account is different from the test guest account bob.TOKEN_ID.OWNER_ACCOUNT_ID. It is an account, different from the owner or token accounts, that manages the guests keys.

Guest Accounts

The guest users can claim_drop, ft_transfer_guest and receive tokens from other users, e.g. in the server tests the owner transfers tokens to the guest account via API call and using client side code.

Then, following the server tests, the guest transfers tokens to alice (who is a real NEAR account e.g. she pays her own gas).

Finally, the guest upgrades themselves to a real NEAR account, something demoed in the video.

It's a lot to digest but if you focus on the /test/app.test.js you will start to see the patterns.

Background

One of the issues with onboarding new users to crypto is that they need to have crypto to do anything e.g. mint an NFT. A creator, artist or community might want to drop a bunch of free minting options to their fans for them to mint user generated content, but the audience has (1) no crypto to pay for fees (2) no wallet (3) no concept of crypto or blockchain; prior to the drop.

So let's solve these issues by allowing users to generate content the traditional Web2 way!

We do a demo of creating a "guest" named account for an app where the gas fees are sponsored by a special app account called "guests.APP_NAME.near". The guest account doesn't exist (sometimes called a virtual or contract account) until the user creates and sells and NFT that generates some NEAR tokens and then they can upgrade to a real account. Until then their name is reserved because only the app is able to create "USERNAME.APP_NAME.near".

This has many advantages for user onboarding, where users can use the app immediately and later can be upgraded to a full account. The users also don't have to move any assets - namely the fungible tokens they earned as a guest user.

Installation

Beyond having npm and node (latest versions), you should have Rust installed. I recommend nightly because living on the edge is fun.

https://rustup.rs/

Don't forget to install the wasm32 target:

rustup target add wasm32-unknown-unknown

Also recommend installing near-cli globally

npm i -g near-cli

Everything else can be installed via: yarn cd server && yarn

NEAR Config

There is only one config.js file found in src/config.js, this is also used for running tests.

Using src/config.js you can set up your different environments. Use REACT_APP_ENV to switch environments e.g. in package.json script deploy.

Running Tests

You can run unit tests in the Rust contracts themselves, but it may be more useful to JS tests against testnet itself.

Note: to run the app and server tests make sure you install and start the server.

  • cd server
  • yarn && yarn start

Commands:

  • test will simply run app tests against the contract already deployed. You can mess around with app.test.js and try different frontend stuff
  • test:deploy - will deploy a new dev account (/neardev) and deploy a new contract to this account, then run test
  • test:server - will test the server, make sure you start it (see "Note" above)
  • test:unit - runs the rust unit tests

If you've changed your contract or your dev account has run out of funds use test:deploy, if you're updating your JS tests only then use test.

Test Utils

There are helpers in test/test-utils.js that take care of:

  1. creating a near connection and establishing a keystore for the dev account
  2. creating test accounts each time a test is run
  3. establishing a contract instance so you can call methods

You can change the default funding amount for test accounts in src/config.js

Using the NEAR Config in your app

In src/state/near.js you will see that src/config.js is loaded as a function. This is to satisfy the jest/node test runner.

You can destructure any properies of the config easily in any module you import it in like this:

// example file app.js

import getConfig from '../config';
export const {
	GAS,
	networkId, nodeUrl, walletUrl, nameSuffix,
	contractName,
} = getConfig();

Note the export const in the destructuring?

Now you can import these like so:

//example file Component.js
import { GAS } from '../app.js'
...
await contract.withdraw({ amount: parseNearAmount('1') }, GAS)
...

React 17, Parcel with useContext and useReducer

  • Bundled with Parcel 2.0 (@next) && eslint
  • Minimal all-in-one state management with async/await support

Getting Started: State Store & useContext

The following steps describe how to use src/utils/state to create and use your own store and StateProvider.

  1. Create a file e.g. /state/app.js and add the following code
import { State } from '../utils/state';

// example
const initialState = {
	app: {
		mounted: false
	}
};

export const { store, Provider } = State(initialState);
  1. Now in your index.js wrap your App component with the StateProvider
import { Provider } from './state/app';

ReactDOM.render(
    <Provider>
        <App />
    </Provider>,
    document.getElementById('root')
);
  1. Finally in App.js you can useContext(store)
const { state, dispatch, update } = useContext(store);

Usage in Components

Print out state values

<p>Hello {state.foo && state.foo.bar.hello}</p>

Update state directly in component functions

const handleClick = () => {
    update('clicked', !state.clicked);
};

Dispatch a state update function (action listener)

const onMount = () => {
    dispatch(onAppMount('world'));
};
useEffect(onMount, []);

Dispatched Functions with context (update, getState, dispatch)

When a function is called using dispatch, it expects arguments passed in to the outer function and the inner function returned to be async with the following json args: { update, getState, dispatch }

Example of a call:

dispatch(onAppMount('world'));

All dispatched methods and update calls are async and can be awaited. It also doesn't matter what file/module the functions are in, since the json args provide all the context needed for updates to state.

For example:

import { helloWorld } from './hello';

export const onAppMount = (message) => async ({ update, getState, dispatch }) => {
	update('app', { mounted: true });
	update('clicked', false);
	update('data', { mounted: true });
	await update('', { data: { mounted: false } });

	console.log('getState', getState());

	update('foo.bar', { hello: true });
	update('foo.bar', { hello: false, goodbye: true });
	update('foo', { bar: { hello: true, goodbye: false } });
	update('foo.bar.goodbye', true);

	await new Promise((resolve) => setTimeout(() => {
		console.log('getState', getState());
		resolve();
	}, 2000));

	dispatch(helloWorld(message));
};

Prefixing store and Provider

The default names the State factory method returns are store and Provider. However, if you want multiple stores and provider contexts you can pass an additional prefix argument to disambiguate.

export const { appStore, AppProvider } = State(initialState, 'app');

Performance and memo

The updating of a single store, even several levels down, is quite quick. If you're worried about components re-rendering, use memo:

import React, { memo } from 'react';

const HelloMessage = memo(({ message }) => {
	console.log('rendered message');
	return <p>Hello { message }</p>;
});

export default HelloMessage;

Higher up the component hierarchy you might have:

const App = () => {
	const { state, dispatch, update } = useContext(appStore);
    ...
	const handleClick = () => {
		update('clicked', !state.clicked);
	};

	return (
		<div className="root">
			<HelloMessage message={state.foo && state.foo.bar.hello} />
			<p>clicked: {JSON.stringify(state.clicked)}</p>
			<button onClick={handleClick}>Click Me</button>
		</div>
	);
};

When the button is clicked, the component HelloMessage will not re-render, it's value has been memoized (cached). Using this method you can easily prevent performance intensive state updates in further down components until they are neccessary.

Reference:

Issues
  • Build Failed

    Build Failed

    https://github.com/Fayyr-Organization/nft-market/commit/387510135f12a3ee4e7980db4b69fbbb9f8ca8da

    I was trying to run the rust tests for the NFT-Simple contract and the build failed as shown below:

    PS C:\Users\Benjamin\Desktop\School\Fayyr\Repos\nft-market\contracts\nft-simple> cargo test -- --nocapture --color always Compiling proc-macro2 v1.0.24 Compiling unicode-xid v0.2.1 Compiling autocfg v1.0.1 Compiling syn v1.0.57 Compiling serde_derive v1.0.118 Compiling serde v1.0.118 Compiling ahash v0.4.7 Compiling version_check v0.9.2 Compiling typenum v1.12.0 Compiling ryu v1.0.5 Compiling serde_json v1.0.62 Compiling itoa v0.4.7 Compiling memchr v2.3.4 Compiling block-padding v0.2.1 Compiling opaque-debug v0.3.0 Compiling once_cell v1.5.2 Compiling cfg-if v1.0.0 Compiling regex-syntax v0.6.22 Compiling cpuid-bool v0.1.2 Compiling hex v0.4.2 Compiling lazy_static v1.4.0 Compiling winapi v0.3.9 Compiling Inflector v0.11.4 Compiling base64 v0.11.0 Compiling bs58 v0.4.0 Compiling wee_alloc v0.4.5 Compiling keccak v0.1.0 Compiling byteorder v1.4.2 Compiling memory_units v0.4.0 Compiling cfg-if v0.1.10 Compiling base64 v0.13.0 Compiling hashbrown v0.9.1 Compiling generic-array v0.14.4 Compiling indexmap v1.6.1 Compiling num-traits v0.2.14 Compiling num-integer v0.1.44 Compiling num-bigint v0.3.1 Compiling num-rational v0.3.2 Compiling thread_local v1.1.3 Compiling quote v1.0.8 Compiling aho-corasick v0.7.15 Compiling block-buffer v0.9.0 Compiling digest v0.9.0 Compiling regex v1.4.3 Compiling sha2 v0.9.3 Compiling sha3 v0.9.1 Compiling near-runtime-utils v3.0.0 Compiling borsh-derive-internal v0.8.1 Compiling borsh-schema-derive-internal v0.8.1 Compiling near-sdk-core v3.0.1 Compiling derive_more v0.99.11 Compiling near-sdk-macros v3.0.1 Compiling toml v0.5.8 Compiling near-rpc-error-core v0.1.0 Compiling proc-macro-crate v0.1.5 Compiling near-rpc-error-macro v0.1.0 Compiling borsh-derive v0.8.1 Compiling borsh v0.8.1 Compiling near-primitives-core v0.1.0 Compiling near-vm-errors v3.0.0 Compiling near-vm-logic v3.0.0 Compiling near-sdk v3.0.1 Compiling nft_simple v0.1.0 (C:\Users\Benjamin\Desktop\School\Fayyr\Repos\nft-market\contracts\nft-simple) error[E0061]: this function takes 5 arguments but 4 arguments were supplied --> src\lib.rs:209:18 | 209 | contract.nft_transfer( | ^^^^^^^^^^^^ expected 5 arguments 210 | ValidAccountId::try_from(bob()).unwrap(), | ---------------------------------------- 211 | "0".to_string(), | --------------- 212 | None, | ---- 213 | Some("my memo".to_string()), | --------------------------- supplied 4 arguments | note: associated function defined here --> src\nft_core.rs:11:8 | 11 | fn nft_transfer( | ^^^^^^^^^^^^

    error[E0061]: this function takes 5 arguments but 4 arguments were supplied --> src\lib.rs:226:18 | 226 | contract.nft_transfer( | ^^^^^^^^^^^^ expected 5 arguments 227 | ValidAccountId::try_from(bob()).unwrap(), | ---------------------------------------- 228 | "0".to_string(), | --------------- 229 | Some(U64::from(0u64)), | --------------------- 230 | Some("my memo".to_string()), | --------------------------- supplied 4 arguments | note: associated function defined here --> src\nft_core.rs:11:8 | 11 | fn nft_transfer( | ^^^^^^^^^^^^

    error[E0061]: this function takes 5 arguments but 4 arguments were supplied --> src\lib.rs:273:18 | 273 | contract.nft_transfer( | ^^^^^^^^^^^^ expected 5 arguments 274 | ValidAccountId::try_from(alice()).unwrap(), | ------------------------------------------ 275 | "0".to_string(), | --------------- 276 | Some(U64::from(0u64)), | --------------------- 277 | Some("thanks for allowing me to take it".to_string()), | ----------------------------------------------------- supplied 4 arguments | note: associated function defined here --> src\nft_core.rs:11:8 | 11 | fn nft_transfer( | ^^^^^^^^^^^^

    error[E0061]: this function takes 5 arguments but 4 arguments were supplied --> src\lib.rs:310:18 | 310 | contract.nft_transfer( | ^^^^^^^^^^^^ expected 5 arguments 311 | ValidAccountId::try_from(bob()).unwrap(), | ---------------------------------------- 312 | "0".to_string(), | --------------- 313 | Some(U64::from(1u64)), | --------------------- 314 | Some("I am trying to hack you.".to_string()), | -------------------------------------------- supplied 4 arguments | note: associated function defined here --> src\nft_core.rs:11:8 | 11 | fn nft_transfer( | ^^^^^^^^^^^^

    error: aborting due to 4 previous errors

    For more information about this error, try rustc --explain E0061. error: could not compile nft_simple

    To learn more, run the command again with --verbose. warning: build failed, waiting for other jobs to finish... error: build failed

    opened by BenKurrek 2
  • nft-market/contracts/nft-simple/src/lib.rs  measure_min_token_storage_cost some error?

    nft-market/contracts/nft-simple/src/lib.rs measure_min_token_storage_cost some error?

    code position: https://github.com/near-apps/nft-market/blob/50cd0e27bafbce2e8b17737bb1b12f8ec45d4209/contracts/nft-simple/src/lib.rs#L117

    I think, the extra cost should be owner_id.len () - tmp_account_id.len (). Should be

     let owner_id_extra_cost_in_bytes = (self.owner_id.len() - tmp_account_id.len()) as u64;
    
    opened by wisarmy 2
  • Can't accept offer due to error 'Exceeded the prepaid gas'

    Can't accept offer due to error 'Exceeded the prepaid gas'

    I deployed this contract using the commandyarn test:deploy and it's successfuly deployed and all tests work great. And I lanched my API to Azure serverless that calls the functions of this contract and I am experiencing an issue named Exceeded the prepaid gas. when I call the accept_offer function. The other function calls are working well such as nft_mint nft_approve update_price offer but when I am going to accept the offer, it shows this error. https://explorer.testnet.near.org/transactions/DsVy8wRTgfyfAC3cVEC3a92AAtQczGP6im3YrBFbMun2

    await account.functionCall({
    contractId: marketId,
      methodName: 'accept_offer',
      args: {
        nft_contract_id: contractId,
        token_id,
        ft_token_id: 'near'
      },
      gas: GAS
    });
    

    GAS is 200TG like here. https://github.com/near-apps/nft-market/blob/main/src/config.js#L17

    opened by hanyibai 1
  • clippy, fmt

    clippy, fmt

    opened by thor314 0
  • Live review

    Live review

    Fixes

    opened by evgenykuzyakov 0
  • update config.js

    update config.js

    • Updated config.js to use testnet as default is now deprecated.
    • Changed contractName variable to CONTRACT_NAME.
    • Formatting
    opened by thisisjoshford 0
  • Fix accept offer flow

    Fix accept offer flow

    Couldn't get it to work without these fixes: pass the account to handleAcceptOffer and map the bids.

    opened by devey 0
Releases(v1.0.8)
Owner
NEAR App Examples
git clone and go, generator fodder, boilerplates for tutorials - a more informal and less "how to code" version of near-examples
NEAR App Examples
C++ `std::unique_ptr` that represents each object as an NFT on the Ethereum blockchain

C++ `std::unique_ptr` that represents each object as an NFT on the Ethereum blockchain

null 1.4k Sep 15, 2021
Rust client to Opensea's APIs and Ethereum smart contracts

opensea.rs Rust bindings & CLI to the Opensea API and Contracts CLI Usage Run cargo r -- --help to get the top level help menu: opensea-cli 0.1.0 Choo

Georgios Konstantopoulos 102 Sep 9, 2021
The Mullvad VPN client app for desktop and mobile

Mullvad VPN desktop and mobile app Welcome to the Mullvad VPN client app. This repository contains all the source code for the desktop and mobile vers

Mullvad VPN 1.7k Sep 18, 2021
Drop-in Access Control via NFT Ownership

niftygate - Signature-Based Authenticating Proxy What is it? niftygate is a proxy for HTTP services, that validates signatures, providing an AuthN lay

Chris Olstrom 31 Sep 14, 2021
Substrate NFT !ink smart contract base

Substrate !ink NFT simple implementation This is a simple working version of base NFT smart contract written using latest (as of this date) !ink 3.0.0

POLK4.NET 7 Sep 1, 2021
Smart contracts for Ref Finance

Ref Finance Contracts This mono repo contains the source code for the smart contracts of Ref Finance on NEAR. Contracts Contract Reference Description

Ref Finance 31 Sep 15, 2021
A fully-featured lexer generator, implement as a proc macro

lexgen: A fully-featured lexer generator, implemented as a proc macro lexer! { // First line specifies name of the lexer and the token type return

Ömer Sinan Ağacan 18 Jun 18, 2021
Substrate Node for Anmol Network

Anmol Substrate Node ?? ??️ ?? Anmol is the First Cross-Chain NFT Toolkit, on Polkadot. Introducing: Moulds NFT Breeding Multi-Chain NFT Migration ink

Anmol Network 10 Sep 7, 2021
deductive verification of Rust code. (semi) automatically prove your code satisfies your specifications!

Le marteau-pilon, forges et aciéries de Saint-Chamond, Joseph-Fortuné LAYRAUD, 1889 About Creusot is a tool for deductive verification of Rust code. I

Xavier Denis 179 Sep 14, 2021
HyperCube is a free and open source blockchain project for everyone to use.

XPZ Public Chain HyperCube is a free and open source blockchain project for everyone to use. 日本語 简体中文 正體中文 HyperCube Wiki Wha is HyperCube HyperCube i

null 336 Sep 12, 2021
Source project for the Internet Computer software

The Internet Computer is the world’s first blockchain that runs at web speed and can increase its capacity without bound. Like the Internet (which is composed of many machines adhering to TCP/IP protocol) and blockchain protocols (such as Bitcoin and Ethereum).

DFINITY 727 Sep 17, 2021
Dank - The Internet Computer Decentralized Bank - A collection of Open Internet Services - Including the Cycles Token (XTC)

Dank - The Internet Computer Decentralized Bank Dank is a collection of Open Internet Services for users and developers on the Internet Computer. In t

Psychedelic 26 Sep 6, 2021
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.3k Sep 18, 2021
Use Touch ID / Secure Enclave for SSH Authentication!

SeKey About SeKey is a SSH Agent that allow users to authenticate to UNIX/Linux SSH servers using the Secure Enclave How it Works? The Secure Enclave

SeKey 2.2k Sep 10, 2021
Replicating Fastly Varnish locally

Fastly VCL Interpreters in Rust A tree-walk interpreter for Fastly VCL Install project Install rust - curl https://sh.rustup.rs -sSf | sh Clone projec

Jake Champion 4 Aug 23, 2021
A temporary repo for ETH connector to be used by EVM

ETH connector for Rainbow bridge Definitions bridgedETH - NEP-141 fungible-token representation of ETH inside Near. nETH - native ETH inside Near EVM.

Project Aurora 33 Aug 29, 2021
Reference client for NEAR Protocol

Reference implementation of NEAR Protocol About NEAR NEAR's purpose is to enable community-driven innovation to benefit people around the world. To ac

NEAR 1k Sep 17, 2021
A modern TLS library in Rust

Rustls is a modern TLS library written in Rust. It's pronounced 'rustles'. It uses ring for cryptography and libwebpki for certificate verification. S

ctz 2.9k Sep 15, 2021
Skyward Finance smart-contracts

Build and Init ./build.sh near dev-deploy res/skyward.was export CONTRACT_ID=skyward.testnet near call $CONTRACT_ID new --account_id=$CONTRACT_ID Regi

Skyward Finance 823 Sep 11, 2021