fetchNFTsByCollection.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Demonstrate the use of a few of the Metaplex Read API methods,
  3. * (needed to fetch compressed NFTs)
  4. */
  5. // imports from other libraries
  6. import { PublicKey } from "@solana/web3.js";
  7. // import custom helpers for demos
  8. import { printConsoleSeparator } from "./utils/helpers";
  9. // local import of the connection wrapper, to help with using the ReadApi
  10. import { WrapperConnection } from "./ReadApi/WrapperConnection";
  11. import { RPC_PATH } from "./cnft-burn";
  12. export async function getcNFTsFromCollection(
  13. collectionMint: PublicKey,
  14. owner: string
  15. ) {
  16. // load the stored PublicKeys for ease of use
  17. // let keys = loadPublicKeysFromFile();
  18. // ensure the primary script was already run
  19. // if (!keys?.collectionMint)
  20. // return console.warn("No local keys were found, specifically `collectionMint`");
  21. // convert the locally saved keys to PublicKeys
  22. // const collectionMint: PublicKey = keys.collectionMint;
  23. console.log("Collection mint:", collectionMint.toBase58());
  24. //////////////////////////////////////////////////////////////////////////////
  25. //////////////////////////////////////////////////////////////////////////////
  26. // load the env variables and store the cluster RPC url
  27. const CLUSTER_URL = RPC_PATH;
  28. // create a new rpc connection, using the ReadApi wrapper
  29. const connection = new WrapperConnection(CLUSTER_URL);
  30. printConsoleSeparator("Getting all assets by the 'collection' group...");
  31. const assets = await connection
  32. .getAssetsByGroup({
  33. groupKey: "collection",
  34. groupValue: collectionMint.toBase58(),
  35. sortBy: {
  36. sortBy: "recent_action",
  37. sortDirection: "asc",
  38. },
  39. })
  40. .then((res) => {
  41. console.log("Total assets returned:", res.total);
  42. // loop over each of the asset items in the collection
  43. const assetsIds = res.items?.map((asset) => {
  44. // display a spacer between each of the assets
  45. console.log("\n===============================================");
  46. // print the entire asset record to the console
  47. // console.log(asset);
  48. // print some useful info
  49. console.log("assetId:", asset.id);
  50. console.log("ownership:", asset.ownership);
  51. console.log("compression:", asset.compression);
  52. if (asset.ownership?.owner === owner) {
  53. console.log("assetId:", asset.id);
  54. return asset.id;
  55. }
  56. });
  57. return assetsIds;
  58. });
  59. return assets;
  60. }