Skip to content

Instantly share code, notes, and snippets.

@dvcrn
Last active June 26, 2022 19:41
Show Gist options
  • Save dvcrn/a1b0ff0a0b4b3ab02aff44bc84ac4522 to your computer and use it in GitHub Desktop.
Save dvcrn/a1b0ff0a0b4b3ab02aff44bc84ac4522 to your computer and use it in GitHub Desktop.
Get Metaplex Metadata
import * as metaplex from "@metaplex/js";
import * as web3 from "@solana/web3.js";
const connection = new web3.Connection(
web3.clusterApiUrl("mainnet-beta"),
"confirmed"
);
const tokenAddress = "CxkKDaBvtHqg8aHBVY8E4YYBsCfJkJVsTAEdTo5k4SEw";
(async () => {
const metadataPDA = await metaplex.programs.metadata.Metadata.getPDA(
tokenAddress
);
const mintAccInfo = await connection.getAccountInfo(metadataPDA); // fetch account info
const metadata = metaplex.programs.metadata.Metadata.from(
new metaplex.Account(tokenAddress, mintAccInfo)
);
console.log(metadata);
})();
@AWolf81
Copy link

AWolf81 commented Dec 31, 2021

There is a change in the latest Metaplex version (see metaplex/js issue #129).

The code above is working for version 4.1.0.

For v4.10.1 the below code is working (but could be simplified with Metadata.load method):

import { Connection } from "@metaplex/js";
import { Account } from "@metaplex-foundation/mpl-core";
import { Metadata } from "@metaplex-foundation/mpl-token-metadata";

const connection = new Connection("mainnet-beta");
const tokenAddress = "CxkKDaBvtHqg8aHBVY8E4YYBsCfJkJVsTAEdTo5k4SEw";

const getMetadata = async () => {
  const metadataPDA = await Metadata.getPDA(tokenAdr);
  const mintAccInfo = await connection.getAccountInfo(metadataPDA);

  const {
    data: { data: metadata }
  } = Metadata.from(new Account(tokenAddress, mintAccInfo));

  console.log(metadata)
};

getMetadata();

Codesandbox React example

@dvcrn
Copy link
Author

dvcrn commented Jan 2, 2022

Thanks for adding this @AWolf81!

@brankomiric-cw
Copy link

looks like Metadata doesn't have getPDA or from methods anymore after latest updates

@mwilc0x
Copy link

mwilc0x commented Apr 29, 2022

Is there still a way to get metadata without the getPDA method?

@hapetherw
Copy link

hapetherw commented Jun 26, 2022

export const METADATA_PROGRAM_ID =  'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s';

const getPDA = async (
  mint: anchor.web3.PublicKey,
): Promise<anchor.web3.PublicKey> => {
  return (
    await anchor.web3.PublicKey.findProgramAddress(
      [
        Buffer.from('metadata'),
        TOKEN_METADATA_PROGRAM_ID.toBuffer(),
        mint.toBuffer(),
      ],
      TOKEN_METADATA_PROGRAM_ID,
    )
  )[0];
};

Hopefully, this is helpful for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment