Created
February 28, 2025 14:46
-
-
Save danmt/daa56583f501abf74af5887d2e8075e6 to your computer and use it in GitHub Desktop.
This method allows you to fetch a token with its mint and metadata (covers Token Extensions and Metaplex)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Metaplex } from "@metaplex-foundation/js"; | |
import { | |
getMint, | |
getTokenMetadata as getToken2022Metadata, | |
Mint, | |
} from "@solana/spl-token"; | |
import { PublicKey } from "@solana/web3.js"; | |
import { config } from "./config"; | |
// Generalized Token metadata interface | |
interface TokenMetadataResult { | |
symbol: string; | |
name?: string; | |
uri?: string; | |
} | |
// Token object combining Mint and metadata | |
interface Token { | |
mint: Mint; | |
metadata: TokenMetadataResult; | |
} | |
export async function fetchToken(mint: PublicKey): Promise<Token> { | |
const { connection } = config; | |
// Fetch Mint info | |
const mintInfo = await getMint(connection, mint); | |
// Special case for Wrapped SOL | |
if (mint.toBase58() === "So11111111111111111111111111111111111111112") { | |
return { | |
mint: mintInfo, | |
metadata: { symbol: "SOL" }, | |
}; | |
} | |
// Try Token-2022 metadata (on-chain extensions) | |
const token2022Metadata = await getToken2022Metadata(connection, mint).catch( | |
() => null | |
); | |
if (token2022Metadata?.symbol) { | |
return { | |
mint: mintInfo, | |
metadata: { | |
symbol: token2022Metadata.symbol, | |
name: token2022Metadata.name, | |
uri: token2022Metadata.uri, | |
}, | |
}; | |
} | |
// Try Metaplex metadata (off-chain PDA) | |
const metaplex = new Metaplex(connection); | |
const metaplexMetadata = await metaplex | |
.nfts() | |
.findByMint({ mintAddress: mint }) | |
.catch(() => null); | |
if (metaplexMetadata?.json?.symbol) { | |
return { | |
mint: mintInfo, | |
metadata: { | |
symbol: metaplexMetadata.json.symbol, | |
name: metaplexMetadata.json.name, | |
uri: metaplexMetadata.uri, | |
}, | |
}; | |
} | |
// Fallback to truncated mint | |
return { | |
mint: mintInfo, | |
metadata: { symbol: mint.toBase58().slice(0, 6) }, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment