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 { toMintAccount, toTokenAccount } from '../accounts';
import { TokenAndMintDoNotMatchError } from '../errors';
import { toMint } from '../models/Mint';
import { toTokenWithMint } from '../models/Token';
import { useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'FindTokenWithMintByMintOperation';
/**
 * Finds a token account and its associated mint account
 * by providing the mint address and either:
 * - the token address or
 * - the address of the token's owner.
 *
 * ```ts
 * const tokenWithMint = await metaplex
 *   .tokens()
 *   .findTokenWithMintByMint({ mint, address: tokenAddress, type: "token" };
 *
 * const tokenWithMint = await metaplex
 *   .tokens()
 *   .findTokenWithMintByMint({ mint, address: ownerAddress, type: "owner" };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const findTokenWithMintByMintOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const findTokenWithMintByMintOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const { commitment, programs } = scope;
        const { mint, address, addressType } = operation.input;
        const tokenAddress = addressType === 'owner'
            ? metaplex.tokens().pdas().associatedTokenAccount({
                mint,
                owner: address,
                programs,
            })
            : address;
        const accounts = yield metaplex
            .rpc()
            .getMultipleAccounts([mint, tokenAddress], commitment);
        const mintAccount = toMintAccount(accounts[0]);
        const tokenAccount = toTokenAccount(accounts[1]);
        if (!tokenAccount.data.mint.equals(mint)) {
            throw new TokenAndMintDoNotMatchError(tokenAddress, tokenAccount.data.mint, mint);
        }
        return toTokenWithMint(tokenAccount, toMint(mintAccount));
    }),
};
//# sourceMappingURL=findTokenWithMintByMint.js.map