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 { toAuctioneerAccount, toAuctionHouseAccount } from '../accounts';
import { AuctioneerAuthorityRequiredError } from '../errors';
import { toAuctionHouse } from '../models/AuctionHouse';
import { useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'FindAuctionHouseByAddressOperation';
/**
 * Finds an Auction House by its address.
 *
 * ```ts
 * const nft = await metaplex
 *   .auctionHouse()
 *   .findByAddress({ address };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const findAuctionHouseByAddressOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const findAuctionHouseByAddressOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const { programs, commitment } = scope;
        const { address, auctioneerAuthority } = operation.input;
        const auctioneerPda = auctioneerAuthority
            ? metaplex.auctionHouse().pdas().auctioneer({
                auctionHouse: address,
                auctioneerAuthority,
                programs,
            })
            : undefined;
        const accountsToFetch = [address, auctioneerPda].filter((account) => !!account);
        const accounts = yield metaplex
            .rpc()
            .getMultipleAccounts(accountsToFetch, commitment);
        scope.throwIfCanceled();
        const auctionHouseAccount = toAuctionHouseAccount(accounts[0]);
        const mintModel = yield metaplex
            .tokens()
            .findMintByAddress({ address: auctionHouseAccount.data.treasuryMint }, scope);
        scope.throwIfCanceled();
        if (!auctionHouseAccount.data.hasAuctioneer) {
            return toAuctionHouse(auctionHouseAccount, mintModel);
        }
        if (!accounts[1] || !accounts[1].exists) {
            throw new AuctioneerAuthorityRequiredError();
        }
        const auctioneerAccount = toAuctioneerAccount(accounts[1]);
        return toAuctionHouse(auctionHouseAccount, mintModel, auctioneerAccount);
    }),
};
//# sourceMappingURL=findAuctionHouseByAddress.js.map