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 { createAuctioneerWithdrawInstruction, createWithdrawInstruction, } from '@metaplex-foundation/mpl-auction-house';
import { AuctioneerAuthorityRequiredError, WithdrawFromBuyerAccountRequiresSignerError, } from '../errors';
import { TransactionBuilder } from '../../../utils';
import { isSigner, toPublicKey, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'WithdrawFromBuyerAccountOperation';
/**
 * Withdraws funds from the user's buyer escrow account for the given auction house.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .withdraw({ auctionHouse, buyer, amount };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const withdrawFromBuyerAccountOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const withdrawFromBuyerAccountOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        return withdrawFromBuyerAccountBuilder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions);
    }),
};
/**
 * Withdraws funds from the user's buyer escrow account to the given auction house.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .withdrawFromBuyerAccountBuilder({ auctionHouse, buyer, amount });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const withdrawFromBuyerAccountBuilder = (metaplex, params, options = {}) => {
    var _a, _b, _c;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { auctionHouse, auctioneerAuthority, amount } = params;
    if (auctionHouse.hasAuctioneer && !params.auctioneerAuthority) {
        throw new AuctioneerAuthorityRequiredError();
    }
    const amountBasisPoint = amount.basisPoints;
    const buyer = (_a = params.buyer) !== null && _a !== void 0 ? _a : metaplex.identity();
    const authority = (_b = params.authority) !== null && _b !== void 0 ? _b : auctionHouse.authorityAddress;
    if (!isSigner(buyer) && !isSigner(authority)) {
        throw new WithdrawFromBuyerAccountRequiresSignerError();
    }
    const escrowPayment = metaplex
        .auctionHouse()
        .pdas()
        .buyerEscrow({
        auctionHouse: auctionHouse.address,
        buyer: toPublicKey(buyer),
        programs,
    });
    // Accounts,
    const accounts = {
        wallet: toPublicKey(buyer),
        receiptAccount: toPublicKey(buyer),
        escrowPaymentAccount: escrowPayment,
        treasuryMint: auctionHouse.treasuryMint.address,
        authority: toPublicKey(authority),
        auctionHouse: auctionHouse.address,
        auctionHouseFeeAccount: auctionHouse.feeAccountAddress,
    };
    // Args.
    const args = {
        escrowPaymentBump: escrowPayment.bump,
        amount: amountBasisPoint,
    };
    // Withdraw Instruction.
    let withdrawInstruction = createWithdrawInstruction(accounts, args);
    if (auctioneerAuthority) {
        const ahAuctioneerPda = metaplex.auctionHouse().pdas().auctioneer({
            auctionHouse: auctionHouse.address,
            auctioneerAuthority: auctioneerAuthority.publicKey,
            programs,
        });
        const accountsWithAuctioneer = Object.assign(Object.assign({}, accounts), { auctioneerAuthority: auctioneerAuthority.publicKey, ahAuctioneerPda });
        withdrawInstruction = createAuctioneerWithdrawInstruction(accountsWithAuctioneer, args);
    }
    // Signers.
    const signer = isSigner(buyer) ? buyer : authority;
    const withdrawSigners = [signer, params.auctioneerAuthority].filter(isSigner);
    // Update the account to be a signer since it's not covered properly by MPL due to its dynamic nature.
    const signerKeyIndex = withdrawInstruction.keys.findIndex((key) => key.pubkey.equals(signer.publicKey));
    withdrawInstruction.keys[signerKeyIndex].isSigner = true;
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        // Withdraw.
        .add({
        instruction: withdrawInstruction,
        signers: withdrawSigners,
        key: (_c = params.instructionKey) !== null && _c !== void 0 ? _c : 'withdrawFromBuyerAccount',
    }));
};
//# sourceMappingURL=withdrawFromBuyerAccount.js.map