fetchNFTsByCollection.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 type { 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(collectionMint: PublicKey, owner: string) {
  13. // load the stored PublicKeys for ease of use
  14. // let keys = loadPublicKeysFromFile();
  15. // ensure the primary script was already run
  16. // if (!keys?.collectionMint)
  17. // return console.warn("No local keys were found, specifically `collectionMint`");
  18. // convert the locally saved keys to PublicKeys
  19. // const collectionMint: PublicKey = keys.collectionMint;
  20. console.log('Collection mint:', collectionMint.toBase58());
  21. //////////////////////////////////////////////////////////////////////////////
  22. //////////////////////////////////////////////////////////////////////////////
  23. // load the env variables and store the cluster RPC url
  24. const CLUSTER_URL = RPC_PATH;
  25. // create a new rpc connection, using the ReadApi wrapper
  26. const connection = new WrapperConnection(CLUSTER_URL);
  27. printConsoleSeparator("Getting all assets by the 'collection' group...");
  28. const assets = await connection
  29. .getAssetsByGroup({
  30. groupKey: 'collection',
  31. groupValue: collectionMint.toBase58(),
  32. sortBy: {
  33. sortBy: 'recent_action',
  34. sortDirection: 'asc',
  35. },
  36. })
  37. .then((res) => {
  38. console.log('Total assets returned:', res.total);
  39. // loop over each of the asset items in the collection
  40. const assetsIds = res.items?.map((asset) => {
  41. // display a spacer between each of the assets
  42. console.log('\n===============================================');
  43. // print the entire asset record to the console
  44. // console.log(asset);
  45. // print some useful info
  46. console.log('assetId:', asset.id);
  47. console.log('ownership:', asset.ownership);
  48. console.log('compression:', asset.compression);
  49. if (asset.ownership?.owner === owner) {
  50. console.log('assetId:', asset.id);
  51. return asset.id;
  52. }
  53. });
  54. return assetsIds;
  55. });
  56. return assets;
  57. }