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 { createCreateAuctionHouseInstruction, createDelegateAuctioneerInstruction, } from '@metaplex-foundation/mpl-auction-house';
import { WRAPPED_SOL_MINT } from '../../tokenModule';
import { AUCTIONEER_ALL_SCOPES } from '../constants';
import { TransactionBuilder } from '../../../utils';
import { isSigner, makeConfirmOptionsFinalizedOnMainnet, toPublicKey, useOperation, } from '../../../types';
import { ExpectedSignerError } from '../../../errors';
// -----------------
// Operation
// -----------------
const Key = 'CreateAuctionHouseOperation';
/**
 * Creates an Auction House.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .create({ sellerFeeBasisPoints: 500 }); // 5% fee
 * ```
 *
 * Provide `auctioneerAuthority` in case you want to enable Auctioneer.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .create({ sellerFeeBasisPoints: 500, auctioneerAuthority: mx.identity().publicKey };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const createAuctionHouseOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const createAuctionHouseOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const builder = createAuctionHouseBuilder(metaplex, operation.input, scope);
            const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
            const output = yield builder.sendAndConfirm(metaplex, confirmOptions);
            scope.throwIfCanceled();
            const auctionHouse = yield metaplex.auctionHouse().findByAddress({
                address: output.auctionHouseAddress,
                auctioneerAuthority: operation.input.auctioneerAuthority,
            }, scope);
            return Object.assign(Object.assign({}, output), { auctionHouse });
        });
    },
};
/**
 * Creates an Auction House.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .createAuctionHouse({ sellerFeeBasisPoints: 500 }) // 5% fee
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const createAuctionHouseBuilder = (metaplex, params, options = {}) => {
    var _a, _b, _c, _d, _e, _f, _g;
    // Data.
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const canChangeSalePrice = (_a = params.canChangeSalePrice) !== null && _a !== void 0 ? _a : false;
    const requiresSignOff = (_b = params.requiresSignOff) !== null && _b !== void 0 ? _b : canChangeSalePrice;
    // Accounts.
    const authority = (_c = params.authority) !== null && _c !== void 0 ? _c : metaplex.identity();
    const treasuryMint = (_d = params.treasuryMint) !== null && _d !== void 0 ? _d : WRAPPED_SOL_MINT;
    const treasuryWithdrawalDestinationOwner = (_e = params.treasuryWithdrawalDestinationOwner) !== null && _e !== void 0 ? _e : metaplex.identity().publicKey;
    const feeWithdrawalDestination = (_f = params.feeWithdrawalDestination) !== null && _f !== void 0 ? _f : metaplex.identity().publicKey;
    // Auctioneer delegate instruction needs to be signed by authority
    if (params.auctioneerAuthority && !isSigner(authority)) {
        throw new ExpectedSignerError('authority', 'PublicKey', {
            problemSuffix: 'You are trying to delegate to an Auctioneer authority which ' +
                'requires the Auction House authority to sign a transaction. ' +
                'But you provided the Auction House authority as a Public Key.',
        });
    }
    // PDAs.
    const auctionHouse = metaplex
        .auctionHouse()
        .pdas()
        .auctionHouse({
        creator: toPublicKey(authority),
        treasuryMint,
        programs,
    });
    const auctionHouseFeeAccount = metaplex.auctionHouse().pdas().fee({
        auctionHouse,
        programs,
    });
    const auctionHouseTreasury = metaplex.auctionHouse().pdas().treasury({
        auctionHouse,
        programs,
    });
    const treasuryWithdrawalDestination = treasuryMint.equals(WRAPPED_SOL_MINT)
        ? treasuryWithdrawalDestinationOwner
        : metaplex.tokens().pdas().associatedTokenAccount({
            mint: treasuryMint,
            owner: treasuryWithdrawalDestinationOwner,
            programs,
        });
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        .setContext({
        auctionHouseAddress: auctionHouse,
        auctionHouseFeeAccountAddress: auctionHouseFeeAccount,
        auctionHouseTreasuryAddress: auctionHouseTreasury,
        treasuryWithdrawalDestinationAddress: treasuryWithdrawalDestination,
    })
        // Create and initialize the Auction House account.
        .add({
        instruction: createCreateAuctionHouseInstruction({
            treasuryMint,
            payer: payer.publicKey,
            authority: toPublicKey(authority),
            feeWithdrawalDestination,
            treasuryWithdrawalDestination,
            treasuryWithdrawalDestinationOwner,
            auctionHouse,
            auctionHouseFeeAccount,
            auctionHouseTreasury,
        }, {
            bump: auctionHouse.bump,
            feePayerBump: auctionHouseFeeAccount.bump,
            treasuryBump: auctionHouseTreasury.bump,
            sellerFeeBasisPoints: params.sellerFeeBasisPoints,
            requiresSignOff,
            canChangeSalePrice,
        }),
        signers: [payer],
        key: (_g = params.instructionKey) !== null && _g !== void 0 ? _g : 'createAuctionHouse',
    })
        // Delegate to the Auctioneer authority when provided.
        .when(Boolean(params.auctioneerAuthority), (builder) => {
        var _a, _b;
        const auctioneerAuthority = params.auctioneerAuthority;
        return builder.add({
            instruction: createDelegateAuctioneerInstruction({
                auctionHouse,
                authority: toPublicKey(authority),
                auctioneerAuthority,
                ahAuctioneerPda: metaplex.auctionHouse().pdas().auctioneer({
                    auctionHouse,
                    auctioneerAuthority,
                    programs,
                }),
            }, { scopes: (_a = params.auctioneerScopes) !== null && _a !== void 0 ? _a : AUCTIONEER_ALL_SCOPES }),
            signers: [authority],
            key: (_b = params.delegateAuctioneerInstructionKey) !== null && _b !== void 0 ? _b : 'delegateAuctioneer',
        });
    }));
};
//# sourceMappingURL=createAuctionHouse.js.map