Skip to content

Commit

Permalink
feat: add Metadata.findDataByOwner (#68)
Browse files Browse the repository at this point in the history
A `findByOwner` implementation that uses batched calls to
`getMultipleAccountsInfo` (via `Account.getInfos`) instead of
individual calls to `getProgramAccounts` per address.
  • Loading branch information
solberenson authored Nov 23, 2021
1 parent 3bd2381 commit 248b61b
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/programs/metadata/accounts/Metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ERROR_INVALID_ACCOUNT_DATA, ERROR_INVALID_OWNER } from '@metaplex/error
import { AnyPublicKey, StringPublicKey } from '@metaplex/types';
import { Borsh } from '@metaplex/utils';
import { AccountInfo, Connection, PublicKey } from '@solana/web3.js';
import BN from 'bn.js';
import bs58 from 'bs58';
import { Buffer } from 'buffer';
import { config } from '../../../config';
Expand Down Expand Up @@ -216,6 +217,24 @@ export class Metadata extends Account<MetadataData> {
).flat();
}

static async findDataByOwner(
connection: Connection,
owner: AnyPublicKey,
): Promise<MetadataData[]> {
const accounts = await TokenAccount.getTokenAccountsByOwner(connection, owner);

const metadataPdaLookups = accounts.reduce((memo, { data }) => {
// Only include tokens where amount equal to 1.
// Note: This is not the same as mint supply.
// NFTs by definition have supply of 1, but an account balance > 1 implies a mint supply > 1.
return data.amount?.eq(new BN(1)) ? [...memo, Metadata.getPDA(data.mint)] : memo;
}, []);

const metadataAddresses = await Promise.all(metadataPdaLookups);
const tokenInfo = await Account.getInfos(connection, metadataAddresses);
return Array.from(tokenInfo.values()).map((m) => MetadataData.deserialize(m.data));
}

static async getEdition(connection: Connection, mint: AnyPublicKey) {
const pda = await Edition.getPDA(mint);
const info = await Account.getInfo(connection, pda);
Expand Down

0 comments on commit 248b61b

Please sign in to comment.