Nicht fungible Tokens (NFTs)
So erstellen Sie eine NFT
Um eine NFT zu erstellen, müssen Sie:
- Laden Sie das Bild zu Arweave oder IPFS hoch
- Laden Sie die json-Metadaten zu Arweave oder IPFS hoch
- Rufen Sie metaplex auf, um ein Konto für das NFT zu erstellen
Upload zu Arweave
import fs from "fs";
import Arweave from "arweave";
(async () => {
const arweave = Arweave.init({
host: "arweave.net",
port: 443,
protocol: "https",
timeout: 20000,
logging: false,
});
// Upload image to Arweave
const data = fs.readFileSync("./code/nfts/arweave-upload/lowres-dog.png");
const transaction = await arweave.createTransaction({
data: data,
});
transaction.addTag("Content-Type", "image/png");
const wallet = JSON.parse(fs.readFileSync("wallet.json", "utf-8"))
await arweave.transactions.sign(transaction, wallet);
const response = await arweave.transactions.post(transaction);
console.log(response);
const id = transaction.id;
const imageUrl = id ? `https://arweave.net/${id}` : undefined;
console.log("imageUrl", imageUrl);
// Upload metadata to Arweave
const metadata = {
name: "Custom NFT #1",
symbol: "CNFT",
description: "A description about my custom NFT #1",
seller_fee_basis_points: 500,
external_url: "https://www.customnft.com/",
attributes: [
{
trait_type: "NFT type",
value: "Custom",
},
],
collection: {
name: "Test Collection",
family: "Custom NFTs",
},
properties: {
files: [
{
uri: imageUrl,
type: "image/png",
},
],
category: "image",
maxSupply: 0,
creators: [
{
address: "CBBUMHRmbVUck99mTCip5sHP16kzGj3QTYB8K3XxwmQx",
share: 100,
},
],
},
image: imageUrl,
};
const metadataRequest = JSON.stringify(metadata);
const metadataTransaction = await arweave.createTransaction({
data: metadataRequest,
});
metadataTransaction.addTag("Content-Type", "application/json");
await arweave.transactions.sign(metadataTransaction, wallet);
console.log("metadata txid", metadataTransaction.id);
console.log(await arweave.transactions.post(metadataTransaction));
})();
// 1. Upload image to Arweave
const data = fs.readFileSync("./code/nfts/arweave-upload/lowres-dog.png");
const transaction = await arweave.createTransaction({
data: data,
});
transaction.addTag("Content-Type", "image/png");
const wallet = JSON.parse(fs.readFileSync("wallet.json", "utf-8"))
await arweave.transactions.sign(transaction, wallet);
const response = await arweave.transactions.post(transaction);
console.log(response);
const id = transaction.id;
const imageUrl = id ? `https://arweave.net/${id}` : undefined;
// 2. Upload metadata to Arweave
const metadataRequest = JSON.stringify(metadata);
const metadataTransaction = await arweave.createTransaction({
data: metadataRequest,
});
metadataTransaction.addTag("Content-Type", "application/json");
await arweave.transactions.sign(metadataTransaction, wallet);
await arweave.transactions.post(metadataTransaction);
from arweave.arweave_lib import Wallet, Transaction, API_URL
import json
# Load your arweave wallet
your_ar_wallet = Wallet('wallet.json')
with open('./code/nfts/arweave-upload/lowres-dog.png', 'rb') as f:
img_in_bytes = f.read()
# Upload image to Arweave
transaction = Transaction(your_ar_wallet, data=img_in_bytes)
transaction.add_tag('Content-Type', 'image/png')
transaction.sign()
transaction.send()
image_url = API_URL+"/"+transaction.id
# Define metadata
metadata = {
"name": "Custom NFT #1",
"symbol": "CNFT",
"description": "A description about my custom NFT #1",
"seller_fee_basis_points": 500,
"external_url": "https://www.customnft.com/",
"attributes": [
{
"trait_type": "NFT type",
"value": "Custom"
}
],
"collection": {
"name": "Test Collection",
"family": "Custom NFTs",
},
"properties": {
"files": [
{
"uri": image_url,
"type": "image/png",
},
],
"category": "image",
"maxSupply": 0,
"creators": [
{
"address": "CBBUMHRmbVUck99mTCip5sHP16kzGj3QTYB8K3XxwmQx",
"share": 100,
},
],
},
"image": image_url,
}
# Upload metadata to Arweave
meta_transaction = Transaction(your_ar_wallet, data=json.dumps(metadata))
meta_transaction.add_tag('Content-Type', 'text/html')
meta_transaction.sign()
meta_transaction.send()
metadata_url = API_URL+"/"+meta_transaction.id
print(metadata_url)
# 1. Load your arweave wallet
your_ar_wallet = Wallet('wallet.json')
# 2. Upload image to Arweave
with open('./code/nfts/arweave-upload/lowres-dog.png', 'rb') as f:
img_in_bytes = f.read()
transaction = Transaction(your_ar_wallet, data=img_in_bytes)
transaction.add_tag('Content-Type', 'image/png')
transaction.sign()
transaction.send()
image_url = API_URL+"/"+transaction.id
# 3. Upload metadata to Arweave
meta_transaction = Transaction(your_ar_wallet, data=json.dumps(metadata))
meta_transaction.add_tag('Content-Type', 'text/html')
meta_transaction.sign()
meta_transaction.send()
metadata_url = API_URL+"/"+meta_transaction.id
Minte das NFT
Wenn Sie das Bild und die Metadaten bereits hochgeladen haben, können Sie prägen die NFT mit dem folgenden Code.
import { Metaplex, keypairIdentity } from "@metaplex-foundation/js";
import {
Connection,
clusterApiUrl,
Keypair,
LAMPORTS_PER_SOL,
} from "@solana/web3.js";
import dotenv from "dotenv";
dotenv.config();
(async () => {
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
const keypair = Keypair.fromSecretKey(
Buffer.from(JSON.parse(process.env.SOLANA_KEYPAIR!.toString()))
);
const metaplex = new Metaplex(connection);
metaplex.use(keypairIdentity(keypair));
const feePayerAirdropSignature = await connection.requestAirdrop(
keypair.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(feePayerAirdropSignature);
const mintNFTResponse = await metaplex.nfts().create({
uri: "https://ffaaqinzhkt4ukhbohixfliubnvpjgyedi3f2iccrq4efh3s.arweave.net/KUAIIbk6p8oo4XHRcq0U__C2r0mwQaNl0gQow4Qp9yk",
maxSupply: 1,
});
console.log(mintNFTResponse);
})();
const mintNFTResponse = await metaplex.nfts().create({
uri: "https://ffaaqinzhkt4ukhbohixfliubnvpjgyedi3f2iccrq4efh3s.arweave.net/KUAIIbk6p8oo4XHRcq0U__C2r0mwQaNl0gQow4Qp9yk",
maxSupply: 1,
});
Note
Sie können keine NFT mit einem anderen Ersteller als Ihrer Brieftasche prägen. Wenn Sie auf Creator-Probleme stoßen, vergewissern Sie sich, dass Sie in Ihren Metadaten als Ersteller aufgeführt sind.
So erhalten Sie NFT-Metadaten
Metaplex NFTs haben Metadaten, die auf Arweave gespeichert sind. Um die Arweave-Metadaten zu erhalten, müssen Sie sich den Metaplex PDA besorgen und Kontodaten entschlüsseln.
import { Metaplex, keypairIdentity } from "@metaplex-foundation/js";
import { Connection, clusterApiUrl, Keypair, PublicKey } from "@solana/web3.js";
(async () => {
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const keypair = Keypair.generate();
const metaplex = new Metaplex(connection);
metaplex.use(keypairIdentity(keypair));
const mint = new PublicKey("Ay1U9DWphDgc7hq58Yj1yHabt91zTzvV2YJbAWkPNbaK");
const nft = await metaplex.nfts().findByMint(mint);
console.log(nft.metadata);
/*
{
name: 'SMB #139',
symbol: 'SMB',
description: 'SMB is a collection of 5000 randomly generated 24x24 pixels NFTs on the Solana Blockchain. Each SolanaMonkey is unique and comes with different type and attributes varying in rarity.',
seller_fee_basis_points: 600,
image: 'https://arweave.net/tZrNpbFUizSoFnyTqP4n2e1Tf7WvP3siUwFWKMMid_Q',
external_url: 'https://solanamonkey.business/',
collection: { name: 'SMB Gen2', family: 'SMB' },
attributes: [
{ trait_type: 'Attributes Count', value: 2 },
{ trait_type: 'Type', value: 'Solana' },
{ trait_type: 'Clothes', value: 'Orange Shirt' },
{ trait_type: 'Ears', value: 'None' },
{ trait_type: 'Mouth', value: 'None' },
{ trait_type: 'Eyes', value: 'Cool Glasses' },
{ trait_type: 'Hat', value: 'None' }
],
properties: {
files: [ [Object], [Object] ],
category: 'image',
creators: [ [Object] ]
}
}
*/
})();
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const keypair = Keypair.generate();
const metaplex = new Metaplex(connection);
metaplex.use(keypairIdentity(keypair));
const mint = new PublicKey("Ay1U9DWphDgc7hq58Yj1yHabt91zTzvV2YJbAWkPNbaK");
const nft = await metaplex.nfts().findByMint(mint);
console.log(nft.metadata);
So erhalten Sie den Besitzer eines NFT
Wenn Sie den Münzschlüssel (Token Address) eines NFT haben, können Sie seinen aktuellen Besitzer durch Sneak-Peeking auf das größte Token-Konto für diesen Mint-Key finden.
Denken Sie daran, dass NFTs einen Vorrat von 1 haben und unteilbar sind. was bedeutet, dass nur ein Token-Konto dieses Token zu einem beliebigen Zeitpunkt halten wird, während alle anderen Token-Konten für diesen Münzschlüssel, die dies tun einen Saldo von 0 haben.
Sobald das größte Token-Konto identifiziert ist, können wir seinen Besitzer abrufen.
import { Connection, PublicKey } from "@solana/web3.js";
(async () => {
const connection = new Connection("https://api.mainnet-beta.solana.com");
const tokenMint = "9ARngHhVaCtH5JFieRdSS5Y8cdZk2TMF4tfGSWFB9iSK";
const largestAccounts = await connection.getTokenLargestAccounts(
new PublicKey(tokenMint)
);
const largestAccountInfo = await connection.getParsedAccountInfo(
largestAccounts.value[0].address
);
console.log(largestAccountInfo.value.data.parsed.info.owner);
/*
PublicKey {
_bn: <BN: 6ddf6e1d765a193d9cbe146ceeb79ac1cb485ed5f5b37913a8cf5857eff00a9>
}
*/
})();
const connection = new Connection("https://api.mainnet-beta.solana.com");
const tokenMint = "9ARngHhVaCtH5JFieRdSS5Y8cdZk2TMF4tfGSWFB9iSK";
const largestAccounts = await connection.getTokenLargestAccounts(
new PublicKey(tokenMint)
);
const largestAccountInfo = await connection.getParsedAccountInfo(
largestAccounts.value[0].address
);
console.log(largestAccountInfo.value.data.parsed.info.owner);
So erhalten Sie NFT Mint-Adressen
Wenn Sie den öffentlichen Schlüssel der Candy Machine kennen, können Sie mit dem folgenden Code die Liste aller NFT-Mint-Adressen abrufen, die von dieser Candy Machine generiert wurden. Beachten Sie, dass wir den folgenden memcmp
-Filter verwenden können, da in v1 der erste Ersteller immer die Adresse der Candy Machine ist.
Candy Machine V1
import { Connection, clusterApiUrl, PublicKey } from "@solana/web3.js";
import bs58 from "bs58";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const MAX_NAME_LENGTH = 32;
const MAX_URI_LENGTH = 200;
const MAX_SYMBOL_LENGTH = 10;
const MAX_CREATOR_LEN = 32 + 1 + 1;
const MAX_CREATOR_LIMIT = 5;
const MAX_DATA_SIZE =
4 +
MAX_NAME_LENGTH +
4 +
MAX_SYMBOL_LENGTH +
4 +
MAX_URI_LENGTH +
2 +
1 +
4 +
MAX_CREATOR_LIMIT * MAX_CREATOR_LEN;
const MAX_METADATA_LEN = 1 + 32 + 32 + MAX_DATA_SIZE + 1 + 1 + 9 + 172;
const CREATOR_ARRAY_START =
1 +
32 +
32 +
4 +
MAX_NAME_LENGTH +
4 +
MAX_URI_LENGTH +
4 +
MAX_SYMBOL_LENGTH +
2 +
1 +
4;
const TOKEN_METADATA_PROGRAM = new PublicKey(
"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
);
const candyMachineId = new PublicKey("ENTER_YOUR_CANDY_MACHINE_ID_HERE");
const getMintAddresses = async (firstCreatorAddress: PublicKey) => {
const metadataAccounts = await connection.getProgramAccounts(
TOKEN_METADATA_PROGRAM,
{
// The mint address is located at byte 33 and lasts for 32 bytes.
dataSlice: { offset: 33, length: 32 },
filters: [
// Only get Metadata accounts.
{ dataSize: MAX_METADATA_LEN },
// Filter using the first creator.
{
memcmp: {
offset: CREATOR_ARRAY_START,
bytes: firstCreatorAddress.toBase58(),
},
},
],
}
);
return metadataAccounts.map((metadataAccountInfo) =>
bs58.encode(metadataAccountInfo.account.data)
);
};
getMintAddresses(candyMachineId);
const getMintAddresses = async (firstCreatorAddress: PublicKey) => {
const metadataAccounts = await connection.getProgramAccounts(
TOKEN_METADATA_PROGRAM,
{
// The mint address is located at byte 33 and lasts for 32 bytes.
dataSlice: { offset: 33, length: 32 },
filters: [
// Only get Metadata accounts.
{ dataSize: MAX_METADATA_LEN },
// Filter using the first creator.
{
memcmp: {
offset: CREATOR_ARRAY_START,
bytes: firstCreatorAddress.toBase58(),
},
},
],
}
);
return metadataAccounts.map((metadataAccountInfo) =>
bs58.encode(metadataAccountInfo.account.data)
);
};
getMintAddresses(candyMachineId);
Candy Machine V2
Wenn Sie eine Candy Machine v2 verwenden, müssen Sie zuerst auf die Adresse "Candy Machine Creator" zugreifen, bei der es sich um einen einfachen PDA handelt, der candy_machine
und die Adresse der Candy Machine v2 als Seeds verwendet. Sobald Sie die Creator-Adresse haben, können Sie sie auf die gleiche Weise verwenden, wie wir es für v1 getan haben.
import { Connection, clusterApiUrl, PublicKey } from "@solana/web3.js";
import bs58 from "bs58";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const MAX_NAME_LENGTH = 32;
const MAX_URI_LENGTH = 200;
const MAX_SYMBOL_LENGTH = 10;
const MAX_CREATOR_LEN = 32 + 1 + 1;
const MAX_CREATOR_LIMIT = 5;
const MAX_DATA_SIZE =
4 +
MAX_NAME_LENGTH +
4 +
MAX_SYMBOL_LENGTH +
4 +
MAX_URI_LENGTH +
2 +
1 +
4 +
MAX_CREATOR_LIMIT * MAX_CREATOR_LEN;
const MAX_METADATA_LEN = 1 + 32 + 32 + MAX_DATA_SIZE + 1 + 1 + 9 + 172;
const CREATOR_ARRAY_START =
1 +
32 +
32 +
4 +
MAX_NAME_LENGTH +
4 +
MAX_URI_LENGTH +
4 +
MAX_SYMBOL_LENGTH +
2 +
1 +
4;
const TOKEN_METADATA_PROGRAM = new PublicKey(
"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
);
const CANDY_MACHINE_V2_PROGRAM = new PublicKey(
"cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ"
);
const candyMachineId = new PublicKey("ENTER_YOUR_CANDY_MACHINE_ID_HERE");
const getMintAddresses = async (firstCreatorAddress: PublicKey) => {
const metadataAccounts = await connection.getProgramAccounts(
TOKEN_METADATA_PROGRAM,
{
// The mint address is located at byte 33 and lasts for 32 bytes.
dataSlice: { offset: 33, length: 32 },
filters: [
// Only get Metadata accounts.
{ dataSize: MAX_METADATA_LEN },
// Filter using the first creator.
{
memcmp: {
offset: CREATOR_ARRAY_START,
bytes: firstCreatorAddress.toBase58(),
},
},
],
}
);
return metadataAccounts.map((metadataAccountInfo) =>
bs58.encode(metadataAccountInfo.account.data)
);
};
const getCandyMachineCreator = async (
candyMachine: PublicKey
): Promise<[PublicKey, number]> =>
PublicKey.findProgramAddress(
[Buffer.from("candy_machine"), candyMachine.toBuffer()],
CANDY_MACHINE_V2_PROGRAM
);
(async () => {
const candyMachineCreator = await getCandyMachineCreator(candyMachineId);
getMintAddresses(candyMachineCreator[0]);
})();
const getCandyMachineCreator = async (
candyMachine: PublicKey
): Promise<[PublicKey, number]> =>
PublicKey.findProgramAddress(
[Buffer.from("candy_machine"), candyMachine.toBuffer()],
CANDY_MACHINE_V2_PROGRAM
);
const candyMachineCreator = await getCandyMachineCreator(candyMachineId);
getMintAddresses(candyMachineCreator[0]);
Wie bekomme ich alle NFTs aus einem Wallet?
Wenn Sie alle NFTs aus einer Brieftasche abrufen, müssen Sie alle Token-Konten abrufen und dann analysieren, welche NFTs sind. Dies alles kann mit findDataByOwner
von Metaplex JS Bibliotheken durchgeführt werden.
import { Metaplex, keypairIdentity } from "@metaplex-foundation/js";
import { Connection, clusterApiUrl, Keypair, PublicKey } from "@solana/web3.js";
(async () => {
const connection = new Connection(clusterApiUrl("mainnet-beta"), "confirmed");
const keypair = Keypair.generate();
const metaplex = new Metaplex(connection);
metaplex.use(keypairIdentity(keypair));
const owner = new PublicKey("2R4bHmSBHkHAskerTHE6GE1Fxbn31kaD5gHqpsPySVd7");
const allNFTs = await metaplex.nfts().findAllByOwner(owner);
console.log(allNFTs);
})();
const connection = new Connection(clusterApiUrl("mainnet-beta"), "confirmed");
const keypair = Keypair.generate();
const metaplex = new Metaplex(connection);
metaplex.use(keypairIdentity(keypair));
const owner = new PublicKey("2R4bHmSBHkHAskerTHE6GE1Fxbn31kaD5gHqpsPySVd7");
const allNFTs = await metaplex.nfts().findAllByOwner(owner);
console.log(allNFTs);
Candy Machine v2
Das Metaplex JS SDK unterstützt jetzt das Erstellen und Aktualisieren von Candy Machine v2 per Code. Es ermöglicht den Entwicklern, mit dem Candy Machine v2-Programm zu interagieren und Candy Machines zu erstellen, zu aktualisieren und zu löschen sowie NFTs mit ihnen zu prägen.
Wie erstelle ich eine Candy Machine?
import {
keypairIdentity,
Metaplex,
sol,
toBigNumber,
} from "@metaplex-foundation/js";
import { Keypair, Connection, LAMPORTS_PER_SOL } from "@solana/web3.js";
const createCandyMachine = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const payer = Keypair.generate();
// request airdrop
const airdropSignature = await connection.requestAirdrop(
payer.publicKey,
2 * LAMPORTS_PER_SOL
);
console.log(`Airdrop signature - ${airdropSignature}`);
// creating metaplex instance with payer as the authority
const metaplex = Metaplex.make(connection).use(keypairIdentity(payer));
// creating a candy machine
const { candyMachine } = await metaplex.candyMachinesV2().create({
sellerFeeBasisPoints: 5, // 0.05% royalties
price: sol(0.0001), // 0.0001 SOL
itemsAvailable: toBigNumber(5), // 5 items available
});
console.log(`Candy Machine ID - ${candyMachine.address.toString()}`);
};
createCandyMachine();
const { candyMachine } = await metaplex.candyMachinesV2().create({
sellerFeeBasisPoints: 5, // 0.05% royalties
price: sol(0.0001), // 0.0001 SOL
itemsAvailable: toBigNumber(5), // 5 items available
});
/**
* #1 Candy Machine ID - HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR
*/
Wie Sie eine Candy Machine löschen
import {
Metaplex,
keypairIdentity,
sol,
toBigNumber,
} from "@metaplex-foundation/js";
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
const deleteCandyMachine = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const payer = Keypair.generate();
// request airdrop
const airdropSignature = await connection.requestAirdrop(
payer.publicKey,
2 * LAMPORTS_PER_SOL
);
console.log(`Airdrop signature - ${airdropSignature}`);
// creating metaplex instance with payer as the authority
const metaplex = Metaplex.make(connection).use(keypairIdentity(payer));
// creating a candy machine
const { candyMachine } = await metaplex.candyMachinesV2().create({
sellerFeeBasisPoints: 5, // 0.05% royalties
price: sol(0.0001), // 0.0001 SOL
itemsAvailable: toBigNumber(5), // 5 items available
});
console.log(`Candy Machine ID - ${candyMachine.address.toString()}`);
// deleting the candy machine
const { response } = await metaplex.candyMachinesV2().delete({
candyMachine,
});
console.log(`Delete Candy Machine signature - ${response.signature}`);
};
deleteCandyMachine();
// creating a candy machine
const { candyMachine } = await metaplex.candyMachinesV2().create({
sellerFeeBasisPoints: 5, // 0.05% royalties
price: sol(0.0001), // 0.0001 SOL
itemsAvailable: toBigNumber(5), // 5 items available
});
console.log(`Candy Machine ID - ${candyMachine.address.toString()}`);
// deleting the candy machine
const { response } = await metaplex.candyMachinesV2().delete({
candyMachine,
});
So finden Sie die Candy Machine Autorität
Um alle Candy Machines zu finden, deren Autorität ein bestimmter öffentlicher Schlüssel ist, haben wir die Funktion findAllBy
verwendet mit dem type
-Parameter als authority
import { Connection, PublicKey } from "@solana/web3.js";
import { Metaplex } from "@metaplex-foundation/js";
const findCandyMachineViaAuthority = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const metaplex = new Metaplex(connection);
const authority = new PublicKey(
"9pr8wNxphx2PhBRbHKuH7YhPs5zbDuxx62UcDiayXxrw"
);
const candyMachines = await metaplex.candyMachinesV2().findAllBy({
type: "authority",
publicKey: authority,
});
candyMachines.map((candyMachine, index) => {
console.log(`#${index + 1} Candy Machine ID - ${candyMachine.address}`);
});
/**
* #1 Candy Machine ID - HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR
*/
};
findCandyMachineViaAuthority();
const candyMachines = await metaplex.candyMachinesV2().findAllBy({
type: "authority",
publicKey: authority,
});
candyMachines.map((candyMachine, index) => {
console.log(`#${index + 1} Candy Machine ID - ${candyMachine.address}`);
});
/**
* #1 Candy Machine ID - HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR
*/
So finden Sie Candy Machine mit der Wallet-Adresse
Um das Candy Machine-Objekt über seine Wallet-Adresse abzurufen, haben wir die Funktion findAllBy
zusammen mit dieser geben Sie den Parameter als „Wallet“ ein. Die Wallet-Adresse der Candy Machine können Sie dem Reiter „Ankerdaten“ im Explorer entnehmen.
import { Connection, PublicKey } from "@solana/web3.js";
import { Metaplex } from "@metaplex-foundation/js";
const findCandyMachineViaWallet = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const metaplex = new Metaplex(connection);
const wallet = new PublicKey("9pr8wNxphx2PhBRbHKuH7YhPs5zbDuxx62UcDiayXxrw");
const candyMachines = await metaplex.candyMachinesV2().findAllBy({
type: "wallet",
publicKey: wallet,
});
candyMachines.map((candyMachine, index) => {
console.log(`#${index + 1} Candy Machine ID - ${candyMachine.address}`);
});
/**
* #1 Candy Machine ID - HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR
*/
};
findCandyMachineViaWallet();
const candyMachines = await metaplex.candyMachinesV2().findAllBy({
type: "wallet",
publicKey: wallet,
});
candyMachines.map((candyMachine, index) => {
console.log(`#${index + 1} Candy Machine ID - ${candyMachine.address}`);
});
So finden Sie Candy Machine anhand seiner Adresse
Um einen Candy Machine anhand seiner Adresse zu finden, müssen wir die Funktion findByAddress
verwenden.
import { Connection, PublicKey } from "@solana/web3.js";
import { Metaplex } from "@metaplex-foundation/js";
const findCandyMachineViaAddress = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const metaplex = new Metaplex(connection);
const candyMachineId = new PublicKey(
"HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR"
);
const candyMachine = await metaplex.candyMachinesV2().findByAddress({
address: candyMachineId,
});
};
findCandyMachineViaAddress();
const candyMachine = await metaplex.candyMachinesV2().findByAddress({
address: candyMachineId,
});
So finden Sie geprägte NFTs von einer Candy Machine
import { Connection, PublicKey } from "@solana/web3.js";
import { Metaplex } from "@metaplex-foundation/js";
const findCandyMachineMintedNfts = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const metaplex = new Metaplex(connection);
const candyMachineId = new PublicKey(
"HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR"
);
const candyMachine = await metaplex.candyMachinesV2().findMintedNfts({
candyMachine: candyMachineId,
});
};
findCandyMachineMintedNfts();
const candyMachine = await metaplex.candyMachinesV2().findMintedNfts({
candyMachine: candyMachineId,
});
So fügen Sie Artikel in einer Candy Machine bei
import { Connection, PublicKey } from "@solana/web3.js";
import { Metaplex } from "@metaplex-foundation/js";
const insertItems = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const metaplex = new Metaplex(connection);
const candyMachineId = new PublicKey(
"HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR"
);
await metaplex.candyMachines().insertItems({
candyMachineId,
items: [
{ name: "My NFT #1", uri: "https://example.com/nft1" },
{ name: "My NFT #2", uri: "https://example.com/nft2" },
{ name: "My NFT #3", uri: "https://example.com/nft3" },
],
});
};
insertItems();
await metaplex.candyMachines().insertItems({
candyMachineId,
items: [
{ name: "My NFT #1", uri: "https://example.com/nft1" },
{ name: "My NFT #2", uri: "https://example.com/nft2" },
{ name: "My NFT #3", uri: "https://example.com/nft3" },
],
});
Wie man einen NFT von einer Candy Machine prägt
Standardmäßig wäre der Eigentümer des geprägten NFT metaplex.identity().publicKey
. Wenn Sie die NFT an eine andere Wallet prägen möchten, übergeben Sie diesen öffentlichen Schlüssel zusammen mit dem Parameter "newOwner".
import { Connection, PublicKey } from "@solana/web3.js";
import { Metaplex } from "@metaplex-foundation/js";
const mintNft = async () => {
const connection = new Connection(
"https://api.devnet.solana.com/",
"confirmed"
);
const metaplex = new Metaplex(connection);
const candyMachineId = new PublicKey(
"HSZxtWx6vgGWGsWu9SouXkHA2bAKCMtMZyMKzF2dvhrR"
);
// by default, the owner of the minted nft would be `metaplex.identity().publicKey`. if you want to mint the nft to some other wallet, pass that public key along with the `newOwner` parameter
const candyMachine = await metaplex.candyMachinesV2().mint({
candyMachine: candyMachineId,
// newOwner: new PublicKey("some-other-public-key");
});
};
mintNft();
// by default, the owner of the minted nft would be `metaplex.identity().publicKey`. if you want to mint the nft to some other wallet, pass that public key along with the `newOwner` parameter
const candyMachine = await metaplex.candyMachinesV2().mint({
candyMachine: candyMachineId,
// newOwner: new PublicKey("some-other-public-key");
});