In this example we're using Metamask wallet to interact with ethereum blockchain.
What we have done in this example:
- Configure RaribleSDK
- Create Lazy mint NFT item
- Create sell order
- Purchase (buy item) an order
- Get your own NFT from your current wallet
Lets start new react ts project and add dependencies
npx create-react-app protocol-example --template typescript
yarn add web3
yarn add -D @rarible/protocol-ethereum-sdkcreate-react-app - creates blank react app project. Learn more about command options on their
github CRA repo
For this example we use simple non styled .tsx template and local state management. full example of app you can find
in src/ folder in root of repository in App.tsx and Dashboard.tsx components.
Let's create a new function in the App.tsx file named handleInit. Which serves to check the presence of the Metamask
provider in the browser and create an instance of the SDK.
functionhandleInit(){const{ ethereum }=windowasany;if(ethereum&ðereum.isMetaMask){console.log('Ethereum successfully detected!');// set thereum provider into state to connet to wallet in next stepssetProvider(ethereum)// add listener on accountsChanged event to render actual addressethereum.on('accountsChanged',function(accounts: string[]){setAccounts(accounts)});// configure web3constweb3=newWeb3(ethereum)// configure raribleSdkconstraribleSdk=createRaribleSdk(newWeb3Ethereum({ web3 }),network)// set created Rarible SDK into statesetSdk(raribleSdk)// set current account if already connectedweb3.eth.getAccounts().then(e=>{setAccounts(e)})}else{console.log('Please install MetaMask!');}}Now we will create a hook that will be launched when the App component is mounted, and add to it a simple check for the
presence of the provider object in the browser and run the previously created handleInit function if it exists.
useEffect(()=>{if((windowasany).ethereum){handleInit();}else{window.addEventListener('ethereum#initialized',handleInit,{once: true,});setTimeout(handleInit,3000);}},[])Now we need some nft object to interact with it. the code below shows how you can create lazy-mint ERC721 token nft
using SDK. Create a new async function inside our Dashboard.tsx component called lazyMint
constlazyMint=async()=>{constitem=awaitsdk?.nft.mintLazy({'@type': 'ERC721',// type of NFT to mintcontract: toAddress('0x6ede7f3c26975aad32a475e1021d8f6f39c89d82'),// rinkeby default Rarible collectionuri: "/ipfs/QmWLsBu6nS4ovaHbGAXprD1qEssJu4r5taQfB74sCG51tp",// tokenUri, url to media that nft storescreators: [{account: toAddress(accounts[0]),value: 10000}],// list of creatorsroyalties: [],// royalties})if(item){/** * Get minted nft through SDK */consttoken=awaitsdk?.apis.nftItem.getNftItemById({itemId: item.id})if(token){setCreateOrderForm({
...createOrderForm,contract: token.contract,tokenId: token.tokenId,})}}}What it's going on?
sdk.nft.mintLazy- create lazy minted NFT tokensdk.apis.nftItem.getNftItemById- returns the created token object byitemIdfrom the server (there is no need to use it here because methodsdk.nft.mintLazyreturns the same object, we will use it for example only)
Function below creates a order for sale.
constcreateSellOrder=async()=>{if(createOrderForm.contract&&createOrderForm.tokenId&&createOrderForm.price){// Create an orderconstresultOrder=awaitsdk?.order.sell({makeAssetType: {assetClass: "ERC721",contract: toAddress(createOrderForm.contract),tokenId: toBigNumber(createOrderForm.tokenId),},// asset type, must includes contract address and tokenIdamount: 1,// amount to sell, in our case for ERC721 always will be 1maker: toAddress(accounts[0]),// who sell an itemoriginFees: [],// fees descriptionpayouts: [],// payoutsprice: toBigNumber(createOrderForm.price),takeAssetType: {assetClass: "ETH"},// for what currency}).then(a=>a.runAll())if(resultOrder){setOrder(resultOrder)setPurchaseOrderForm({ ...purchaseOrderForm,hash: resultOrder.hash})}}}consthandlePurchaseOrder=async()=>{if(order){awaitsdk?.order.fill(order,{amount: parseInt(purchaseOrderForm.amount)}).then(a=>a.runAll())}}sdk.order.fill takes the order object (which we got in the previous step) and the amount to buy as arguments, and
returns hash of transaction
consthandleGetMyNfts=async()=>{constitems=awaitsdk?.apis.nftItem.getNftItemsByOwner({owner: accounts[0]})setOwnedItems(items?.items)}