From be04cc54062d2439c0258d47bf369142b535168c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20=C4=86wirko?= Date: Sun, 11 Aug 2024 20:58:06 +0200 Subject: [PATCH] add new example --- README.md | 7 ++ create-nft.js | 187 ++++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 10 +-- package.json | 2 +- 4 files changed, 200 insertions(+), 6 deletions(-) create mode 100644 create-nft.js diff --git a/README.md b/README.md index 72d7a1e..69b4a77 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,13 @@ git checkout - **Article**: [Step-by-step guide to MultiversX smart contract interactions with JavaScript SDK](https://www.julian.io/articles/multiversx-js-sdk-sc-interactions.html) - **Video**: [Step-by-step guide to MultiversX smart contract interactions with JavaScript SDK](https://www.youtube.com/watch?v=TMDC5yxT4_c) +### Example 5: Create NFT + +- **Tag**: `smart-contract-interactions` +- **Description**: This example demonstrates how to create an NFT using the MultiversX JavaScript SDK on the devnet. +- **Article**: [Creating NFTs with MultiversX Blockchain Using JavaScript SDK](https://www.julian.io/articles/multiversx-js-sdk-create-nft.html) +- **Video**: [Creating NFTs with MultiversX Blockchain Using JavaScript SDK](https://www.youtube.com/watch?v=3I2ZEE4ntSA) + ## Security and Wallet Information The examples use a demo wallet with a hardcoded password. All interactions occur on the **devnet** (development network of MultiversX), ensuring that it is safe to expose the wallet credentials. The devnet is designed for testing and development, involving no real assets. Don't do this on the mainnet. diff --git a/create-nft.js b/create-nft.js new file mode 100644 index 0000000..b73dbc3 --- /dev/null +++ b/create-nft.js @@ -0,0 +1,187 @@ +import { + Address, + TokenManagementTransactionsFactory, + TransactionComputer, + TransactionsFactoryConfig, + TokenManagementTransactionsOutcomeParser, + TransactionsConverter, + TransactionWatcher, +} from "@multiversx/sdk-core"; +import { + syncAndGetAccount, + senderAddress, + getSigner, + apiNetworkProvider, +} from "./setup.js"; + +const collectionName = "NFTCollection"; +const collectionTicker = "TTTTT"; +const collectionId = "TTTTT-adfc1e"; // It will be the ticker + hash, you'll get it after issuance + +const parseOutcome = async (txHash, type) => { + console.log("Pending..."); + + // Get the transaction on network, we need to wait for results here, we use TransactionWatcher for that + const transactionOnNetwork = await new TransactionWatcher( + apiNetworkProvider + ).awaitCompleted(txHash); + + // Parse the outcome + const converter = new TransactionsConverter(); + const parser = new TokenManagementTransactionsOutcomeParser(); + const transactionOutcome = + converter.transactionOnNetworkToOutcome(transactionOnNetwork); + + let parsedOutcome; + + if (type === "issue") { + parsedOutcome = parser.parseIssueNonFungible(transactionOutcome); + + console.log(`Token identifier: ${parsedOutcome?.[0]?.tokenIdentifier}`); + } + if (type === "create") { + parsedOutcome = parser.parseNftCreate(transactionOutcome); + + console.log( + `Token identifier: ${parsedOutcome?.[0]?.tokenIdentifier} Nonce: ${parsedOutcome?.[0]?.nonce}` + ); + } +}; + +/** + * Common operation to process each transaction + */ +const processTransaction = async (transaction, type) => { + const user = await syncAndGetAccount(); + const computer = new TransactionComputer(); + const signer = await getSigner(); + + // Increase the nonce + transaction.nonce = user.getNonceThenIncrement(); + + // Serialize the transaction for signing + const serializedTransaction = computer.computeBytesForSigning(transaction); + + // Sign the transaction with our signer + transaction.signature = await signer.sign(serializedTransaction); + + // Broadcast the transaction + const txHash = await apiNetworkProvider.sendTransaction(transaction); + + await parseOutcome(txHash, type); + + console.log( + "Check in the Explorer: ", + `https://devnet-explorer.multiversx.com/transactions/${txHash}` + ); +}; + +const getTransactionFactory = () => { + const factoryConfig = new TransactionsFactoryConfig({ chainID: "D" }); + const factory = new TokenManagementTransactionsFactory({ + config: factoryConfig, + }); + return factory; +}; + +/** + * Issue an NFT collection + */ +const issueNftCollection = () => { + const factory = getTransactionFactory(); + + const transaction = factory.createTransactionForIssuingNonFungible({ + canAddSpecialRoles: true, + canChangeOwner: true, + canFreeze: true, + canPause: true, + canTransferNFTCreateRole: true, + canUpgrade: true, + canWipe: true, + sender: new Address(senderAddress), + tokenName: collectionName, + tokenTicker: collectionTicker, + }); + + processTransaction(transaction, "issue"); +}; + +/** + * Set special roles for the NFT collection + */ +const setSpecialRolesForNft = () => { + const factory = getTransactionFactory(); + + const transaction = + factory.createTransactionForSettingSpecialRoleOnNonFungibleToken({ + addRoleNFTCreate: true, + addRoleNFTBurn: true, + addRoleNFTAddURI: true, + addRoleNFTUpdateAttributes: true, + addRoleESDTTransferRole: false, + sender: new Address(senderAddress), + tokenIdentifier: collectionId, + user: new Address(senderAddress), // The owner of the role, in our case the same as sender + }); + + processTransaction(transaction); +}; + +/** + * create an actual NFT + */ +const createNft = () => { + const factory = getTransactionFactory(); + + const attributes = new TextEncoder().encode( + "metadata:bafybeihof6n2b4gkahn2nwfhcxe72kvms4o5uevcok5chvg6f2zpfsi6hq/33.json" + ); + const hash = ""; + + const transaction = factory.createTransactionForCreatingNFT({ + // You can read more about attributes in the docs. The data should be in the proper format to be picked up by MultiversX services like Explorer, etc. + attributes, + hash, // It can be any hash, for example hash of the attributes, images, etc. (not mandatory) + initialQuantity: 1n, // It will be always 1 (BigInt) for NFT + name: "Some NFT name for the token", + royalties: 500, // number from 0 to 10000 where 10000 is 100% + sender: new Address(senderAddress), + tokenIdentifier: collectionId, + uris: [ + "https://ipfs.io/ipfs/bafybeibimqon4pjm54x27n6we5qohx57gd6n2mnbkxu2r6nejp3nbenk7u/33.png", + "https://ipfs.io/ipfs/bafybeihof6n2b4gkahn2nwfhcxe72kvms4o5uevcok5chvg6f2zpfsi6hq/33.json", + ], + }); + + // Very custom gasLimit calculation. Sometimes (like in this case), the built-in gas calculation isn't enough + // Check docs for more info on how gas limits are calculated + // Anyway, you can define your own value through transaction.gasLimit + transaction.gasLimit = BigInt( + transaction.data.length * 1500 + + (attributes?.length || 0 + hash?.length || 0) * 50000 + ); + + processTransaction(transaction, "create"); +}; + +/** + * Here we will manage which function to call + */ +const nftManagement = () => { + const args = process.argv.slice(2); + const functionName = args[0]; + + const functions = { + issueNftCollection, + setSpecialRolesForNft, + createNft, + }; + + if (functionName in functions) { + functions[functionName](); + } else { + console.log("Function not found!"); + } +}; + +nftManagement(); diff --git a/package-lock.json b/package-lock.json index 21fa4dd..11e00da 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,9 +7,9 @@ "": { "name": "sdk-demo", "version": "1.0.0", - "license": "ISC", + "license": "MIT", "dependencies": { - "@multiversx/sdk-core": "^13.2.1", + "@multiversx/sdk-core": "^13.3.0", "@multiversx/sdk-network-providers": "^2.4.3", "@multiversx/sdk-wallet": "^4.5.0" } @@ -23,9 +23,9 @@ } }, "node_modules/@multiversx/sdk-core": { - "version": "13.2.1", - "resolved": "https://registry.npmjs.org/@multiversx/sdk-core/-/sdk-core-13.2.1.tgz", - "integrity": "sha512-qnC4Q2x+lc7jw5GYja5yvRhqKaJ+2m95txNS6FwLXPb/MxW0ZwRZsAt4qByxOF5hpx6m9v3bJnKFFZn9VrHcNw==", + "version": "13.3.0", + "resolved": "https://registry.npmjs.org/@multiversx/sdk-core/-/sdk-core-13.3.0.tgz", + "integrity": "sha512-P8/8KzMrWL58nhtxg/Ti+18V1dg4YYCn4tY8Gw9+Ke9mErz9Q2+rvWirwBqKgv6romZDMhUB+x7fME1W2PiIng==", "dependencies": { "@multiversx/sdk-transaction-decoder": "1.0.2", "bech32": "1.1.4", diff --git a/package.json b/package.json index 9f18e72..59e6adc 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "author": "", "license": "MIT", "dependencies": { - "@multiversx/sdk-core": "^13.2.1", + "@multiversx/sdk-core": "^13.3.0", "@multiversx/sdk-network-providers": "^2.4.3", "@multiversx/sdk-wallet": "^4.5.0" }