Skip to content

Commit

Permalink
Metaplex: Add cache for repeat token lookups
Browse files Browse the repository at this point in the history
  • Loading branch information
skynetcap committed Nov 28, 2023
1 parent d6e9f47 commit 0dba666
Showing 1 changed file with 8 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MetaplexManager {

private final RpcClient client;
private final Map<PublicKey, Metadata> metadataCache = new HashMap<>();
private static final PublicKey METAPLEX = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");

// Offsets (from https://docs.metaplex.com/programs/token-metadata/accounts)
Expand All @@ -33,6 +36,10 @@ public MetaplexManager(final RpcClient client) {
}

public Optional<Metadata> getTokenMetadata(final PublicKey tokenMint) {
if (metadataCache.containsKey(tokenMint)) {
return Optional.of(metadataCache.get(tokenMint));
}

try {
final PublicKey.ProgramDerivedAddress metadataPda = PublicKey.findProgramAddress(
List.of(
Expand All @@ -54,6 +61,7 @@ public Optional<Metadata> getTokenMetadata(final PublicKey tokenMint) {
.uri(new String(ByteUtils.readBytes(data, URI_OFFSET, URI_SIZE)).trim())
.build();

metadataCache.put(tokenMint, metadata);
return Optional.ofNullable(metadata);
} catch (Exception e) {
return Optional.empty();
Expand Down

0 comments on commit 0dba666

Please sign in to comment.