Code Monkey home page Code Monkey logo

wonka-js's Introduction

Wonka JS

Wonka JS is the easiest way to mint from Candy Machine and fetch NFTs through JS APIs. You can see an end to end example in Next.js demo project as well as debug using the command line testing tool.

For using Wonka's Solana NFT indexing APIs, checkout Windex Documentation.

FI3xQ2FVcAQO3wK

Once you have followed the instructions to upload your NFTs, you can use functions below to build your mint flow:

  • mintCandyMachineToken(..)
  • getCandyMachineMints(..)
  • getCandyMachineState(...)
  • getMintMetadata(...)
  • updateMintImage(...)

These commands are useful if you need to build a custom facing front end, and don't want to rely on the Candy Machine Minting Site.

Installation

npm install @wonka-labs/wonka-js

Wonka APIs

Getting Machine State

Returns info about currently available mints in Candy Machine, how many were already minted, how long is left for the auction, etc.

const getCandyMachineState = async () => {
  console.log("Getting candy machine state.")
  const provider = ...;
  const candyMachineId = process.env.REACT_APP_CANDY_MACHINE_ID!;
  const wonka = new Wonka(provider, candyMachineId)
  const candyMachineState = await wonka.getCandyMachineState()
  console.log(candyMachineState)
}

Getting Existing Mints

Returns a list of all existing mints on the given candy machine.

const getCandyMachineMints = async() => {
  console.log("Getting candy machine mints...")
  const provider = ...;
  const candyMachineId = process.env.REACT_APP_CANDY_MACHINE_ID!;
  const wonka = new Wonka(provider, candyMachineId)
  const candyMachineMints = await wonka.getCandyMachineMints()
  console.log(candyMachineMints)
}

Minting a new NFT

Mints an NFT; you either get an error with a message or the ID of the mint in return.

const mintCandyMachineToken = async(recipientWallet: PublicKey) => {
  const provider = ...;
  const candyMachineId = process.env.REACT_APP_CANDY_MACHINE_ID!;
  const wonka = new Wonka(provider, candyMachineId)
  const candyMachineMintId = await wonka.mintCandyMachineToken(recipientWallet)
  console.log(candyMachineMintId)
}

Fetching Mint Metadata

Sometimes you need to load one particular NFT's metadata, here is how you can do it:

const getMintMetadata = async(mintAddress: string) => {
  const provider = ...;
  const candyMachineId = process.env.REACT_APP_CANDY_MACHINE_ID!;
  const wonka = new Wonka(provider, candyMachineId)
  const mintMetadata = await wonka.getMintMetadata(mintAddress)
  console.log(`Fetched mint metadata:`);
  console.log(mintMetadata);
  
  // Can also fetch the data stored inside the metadata:
  const metadataDataURIData = await fetch(mintMetadata.uri);
  const metadataDataURIDataJSON = await metadataDataURIData.json();
  console.log(`Fetched mint metadata's URI data:`);
  console.log(metadataDataURIDataJSON);
}

Updating Mint Photo (Advanced)

This is a bit more advanced, but if you have a wallet with the update authority, you can actually update the NFT's png. Since this requires access to arweave's private key, it's probably better to create a backend API that uses these functions. Here is what's happening at a high-level:

  1. You create an ArweaveUploader with a private key that has enough money in it for uploading files.
  2. You create a wonka with a provider that's attached to a wallet that has permission to update the NFT's metadata.
  3. You give Wonka a base64 encoded PNG and a mint address. That's it!
const updateMintImage = async(mintAddress: PublicKey, b64image: string) => {
  console.log("Getting mint metadata...")
  const provider = ...;
  const candyMachineId = process.env.REACT_APP_CANDY_MACHINE_ID!;
  const wonka = new Wonka(provider, candyMachineId)
  const arweaveUploader = new ArweaveUploader(process.env.ARWEAVE_KEY!);
  const txn = await wonka.updateMintImage(
      b64image,
      arweaveUploader,
      provider.wallet,
      mintAddress,
      { image_updated: true }
    );
  }

Storing Ids & Keys

The question is where to store information like candy machine ID, etc. If you're using React or Next.js, you can easily use the .env file so that the code above looks more like:

const candyMachineId = process.env.NEXT_PUBLIC_CANDY_MACHINE_ID!; // For Next.js
const candyMachineId = process.env.REACT_APP_CANDY_MACHINE_ID!; // For React

Read more about these in the docs: React .env and Next.js .env.

Windex APIs

*โš ๏ธ The Windex service is being deprecated as of 10/17/2022. After that, all responses will return errors. See here for more information and alternatives

By default, fetching NFTs by Wallet, Collection, or ID requires fetching a series of Solana accounts and external JSON metadata, which can be slow and bandwidth intensive. The Wonka Index (windex) is a backend cache that enables blazing fast metadata fetches. You can use the following queries to easily fetch NFTs. For more details, visit WINDEX.md.

Fetching NFTs by Candy Machine or Collection ID

To display all NFTs in a collection, you can query Windex by Candy Machine ID or Collection ID (the collection id is the first verified creator in the NFT's metadata).

const fetchNFTsByCandyMachine = async(candyMachineId: PublicKey) => {
  const nfts = await Windex.fetchNFTsByCandyMachineID(candyMachineId, 20, Windex.DEVNET_ENDPOINT);
  console.log(`Retrieved ${nfts.length} NFTs!`);
}

const fetchNFTsByCollection = async(collectionId: PublicKey) => {
  const nfts = await Windex.fetchNFTsByCollectionID(collectionId, 20, Windex.DEVNET_ENDPOINT);
  console.log(`Retrieved ${nfts.length} NFTs!`);
}

Fetching NFTs in a Wallet Address

const fetchNFTsByWallet = async(walletAddress: PublicKey) => {
  const nfts = await Windex.fetchNFTsByWallet(walletAddress, 20, Windex.DEVNET_ENDPOINT);
  console.log(`Retrieved ${nfts.length} NFTs in ${walletAddress}'s wallet!`);
}

Fetching an NFT by Mint Address

const fetchNFTsByMintAddress = async(mintAddress: PublicKey) => {
  const nft = await Windex.fetchNFTByMintAddress(mintAddress, Windex.DEVNET_ENDPOINT);
  if (!nft) {
    console.log("nft not found!");
  } else {
    console.log(`Fetched ${nft.address}: ${nft.name}`);
  }
}

wonka-js's People

Contributors

kunalmodi avatar zkhalapyan 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

Watchers

 avatar  avatar  avatar  avatar

wonka-js's Issues

Error in mint function when whitelistSettings is set

I've been having no problems with Candy Machine configs without whitelistMintSettings, but with the following config, I always get an error (despite having isPresale = false). I was able to successfully mint outside of using Wonka, so I don't think there's something wrong with the config itself.

Candy Machine state:

{
[0]   itemsAvailable: 100,
[0]   itemsRedeemed: 1,
[0]   itemsRemaining: 99,
[0]   isSoldOut: false,
[0]   isActive: false,
[0]   isPresale: false,
[0]   isWhitelistOnly: false,
[0]   goLiveDate: <BN: 61c65f00>,
[0]   treasury: PublicKey {
[0]     _bn: <BN: d4f379958bfeb33c56e5237ec468b219433ea67e01113137b2577cac4b9091e9>
[0]   },
[0]   tokenMint: null,
[0]   gatekeeper: null,
[0]   endSettings: null,
[0]   whitelistMintSettings: {
[0]     mode: { burnEveryTime: {} },
[0]     mint: PublicKey {
[0]       _bn: <BN: 44064c130117785053dc01351b6411c5b9b13fad6d24b1a460b4f3f69f78c9e>
[0]     },
[0]     presale: true,
[0]     discountPrice: <BN: 7a1200>
[0]   },
[0]   hiddenSettings: null,
[0]   price: <BN: 989680>
[0] }

Error:

[0] error is  SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 4: Program failed to complete
[0]     at Connection.sendEncodedTransaction (/Users/edwardsun/Sites/paper-web/node_modules/@solana/web3.js/lib/index.cjs.js:6820:13)
[0]     at runMicrotasks (<anonymous>)
[0]     at processTicksAndRejections (node:internal/process/task_queues:96:5)
[0]     at async Connection.sendRawTransaction (/Users/edwardsun/Sites/paper-web/node_modules/@solana/web3.js/lib/index.cjs.js:6775:20)
[0]     at async sendAndConfirmRawTransaction (/Users/edwardsun/Sites/paper-web/node_modules/@solana/web3.js/lib/index.cjs.js:9098:21)
[0]     at async Provider.send (/Users/edwardsun/Sites/paper-web/node_modules/@project-serum/anchor/dist/cjs/provider.js:85:22) {
[0]   logs: [
[0]     'Program 11111111111111111111111111111111 invoke [1]',
[0]     'Program 11111111111111111111111111111111 success',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]',
[0]     'Program log: Instruction: InitializeMint',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 2457 of 200000 compute units',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success',
[0]     'Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL invoke [1]',
[0]     'Program log: Transfer 2039280 lamports to the associated token account',
[0]     'Program 11111111111111111111111111111111 invoke [2]',
[0]     'Program 11111111111111111111111111111111 success',
[0]     'Program log: Allocate space for the associated token account',
[0]     'Program 11111111111111111111111111111111 invoke [2]',
[0]     'Program 11111111111111111111111111111111 success',
[0]     'Program log: Assign the associated token account to the SPL Token program',
[0]     'Program 11111111111111111111111111111111 invoke [2]',
[0]     'Program 11111111111111111111111111111111 success',
[0]     'Program log: Initialize the associated token account',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]',
[0]     'Program log: Instruction: InitializeAccount',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 3297 of 179576 compute units',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success',
[0]     'Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL consumed 24370 of 200000 compute units',
[0]     'Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL success',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]',
[0]     'Program log: Instruction: MintTo',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 2611 of 200000 compute units',
[0]     'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success',
[0]     'Program cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ invoke [1]',
[0]     'Program log: Instruction: MintNft',
[0]     'Program log: recent_blockhashes is deprecated and will break soon',
[0]     "Program log: panicked at 'index out of bounds: the len is 0 but the index is 0', src/lib.rs:159:44",
[0]     'Program cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ consumed 36109 of 200000 compute units',
[0]     'Program failed to complete: BPF program panicked',
[0]     'Program cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ failed: Program failed to complete'
[0]   ]
[0] }

Ability to mint multiple tokens at once?

Just curious, would it be possible to add a quantity argument to mintCandyMachineToken and be able to batch mint more than one token at a time?

Thanks,
Edward

Not sure what "provider" parameter is supposed to be. Getting error.

I'm not quiet sure of what the provider parameter is expecting. Can someone please help? I've tried putting in devnet but getting below.

TypeError: Cannot read properties of undefined (reading '_buildArgs') at Function.<anonymous> (C:\Users\Marii\devprivate\solana\DiscordBotSimple\node_modules\@metaplex-foundation\mpl-core\dist\src\Program.js:40:37) at Generator.next (<anonymous>) at C:\Users\Marii\devprivate\solana\DiscordBotSimple\node_modules\@metaplex-foundation\mpl-core\dist\src\Program.js:8:71 at new Promise (<anonymous>) at __awaiter (C:\Users\Marii\devprivate\solana\DiscordBotSimple\node_modules\@metaplex-foundation\mpl-core\dist\src\Program.js:4:12) at Function.getProgramAccounts (C:\Users\Marii\devprivate\solana\DiscordBotSimple\node_modules\@metaplex-foundation\mpl-core\dist\src\Program.js:23:16) at C:\Users\Marii\devprivate\solana\DiscordBotSimple\node_modules\@triton-labs\wonka\lib\utils\metadata-utils.js:19:73 at Generator.next (<anonymous>) at C:\Users\Marii\devprivate\solana\DiscordBotSimple\node_modules\@triton-labs\wonka\lib\utils\metadata-utils.js:8:71 at new Promise (<anonymous>)

Issue Minting on Devnet

Trying to dynamically mint on devnet

Getting this error in this line:
const candyMachineMintId = await wonka.mintCandyMachineToken(recipientWallet) where recipient wallet is the wallet string
have also tried generating a Public Key off of that string

var recWallet = new PublicKey(recipientWallet)

error: Error: failed to get info about account CggtNXgCye2qk7fLohonNftqaKT35GkuZJwHrRghEvSF: Error: 401 Unauthorized:

Handle candy machine program errors better

When minting an NFT with insufficient balance, I get the following error:

Transaction simulation failed: Error processing Instruction 4: custom program error: 0x1778 
    Program 11111111111111111111111111111111 invoke [1]
    Program 11111111111111111111111111111111 success
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]
    Program log: Instruction: InitializeMint
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 2457 of 200000 compute units
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success
    Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL invoke [1]
    Program log: Transfer 2039280 lamports to the associated token account
    Program 11111111111111111111111111111111 invoke [2]
    Program 11111111111111111111111111111111 success
    Program log: Allocate space for the associated token account
    Program 11111111111111111111111111111111 invoke [2]
    Program 11111111111111111111111111111111 success
    Program log: Assign the associated token account to the SPL Token program
    Program 11111111111111111111111111111111 invoke [2]
    Program 11111111111111111111111111111111 success
    Program log: Initialize the associated token account
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]
    Program log: Instruction: InitializeAccount
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 3297 of 174518 compute units
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success
    Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL consumed 29428 of 200000 compute units
    Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL success
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]
    Program log: Instruction: MintTo
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 2611 of 200000 compute units
    Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success
    Program cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ invoke [1]
    Program log: Instruction: MintNft
    Program log: recent_blockhashes is deprecated and will break soon
    Program log: Custom program error: 0x1778
    Program cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ consumed 36701 of 200000 compute units
    Program cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ failed: custom program error: 0x1778

This is the list of Candy Machine error codes: https://github.com/metaplex-foundation/metaplex-program-library/blob/master/candy-machine/program/src/lib.rs#L1043. Ideally we could return the right error code for clients to handle

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.