var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { toMint, toMintAccount, toToken, toTokenAccount, } from '../../tokenModule';
import { parseOriginalOrPrintEditionAccount, toMetadataAccount, } from '../accounts';
import { toMetadata, toNft, toNftEdition, toNftWithToken, toSft, toSftWithToken, } from '../models';
import { useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'FindNftByMintOperation';
/**
 * Finds an NFT or an SFT by its mint address.
 *
 * ```ts
 * const nft = await metaplex
 *   .nfts()
 *   .findByMint({ mintAddress };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const findNftByMintOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const findNftByMintOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const { programs, commitment } = scope;
        const { mintAddress, tokenAddress, tokenOwner, loadJsonMetadata = true, } = operation.input;
        const associatedTokenAddress = tokenOwner
            ? metaplex.tokens().pdas().associatedTokenAccount({
                mint: mintAddress,
                owner: tokenOwner,
                programs,
            })
            : undefined;
        const nftPdas = metaplex.nfts().pdas();
        const accountAddresses = [
            mintAddress,
            nftPdas.metadata({ mint: mintAddress, programs }),
            nftPdas.masterEdition({ mint: mintAddress, programs }),
            tokenAddress !== null && tokenAddress !== void 0 ? tokenAddress : associatedTokenAddress,
        ].filter((address) => !!address);
        const accounts = yield metaplex
            .rpc()
            .getMultipleAccounts(accountAddresses, commitment);
        scope.throwIfCanceled();
        const mint = toMint(toMintAccount(accounts[0]));
        let metadata = toMetadata(toMetadataAccount(accounts[1]));
        const editionAccount = parseOriginalOrPrintEditionAccount(accounts[2]);
        const token = accounts[3] ? toToken(toTokenAccount(accounts[3])) : null;
        if (loadJsonMetadata) {
            try {
                const json = yield metaplex
                    .storage()
                    .downloadJson(metadata.uri, scope);
                metadata = Object.assign(Object.assign({}, metadata), { jsonLoaded: true, json });
            }
            catch (error) {
                metadata = Object.assign(Object.assign({}, metadata), { jsonLoaded: true, json: null });
            }
        }
        const isNft = editionAccount.exists &&
            mint.mintAuthorityAddress &&
            mint.mintAuthorityAddress.equals(editionAccount.publicKey);
        if (isNft) {
            const edition = toNftEdition(editionAccount);
            return token
                ? toNftWithToken(metadata, mint, edition, token)
                : toNft(metadata, mint, edition);
        }
        return token
            ? toSftWithToken(metadata, mint, token)
            : toSft(metadata, mint);
    }),
};
//# sourceMappingURL=findNftByMint.js.map