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 { AuctioneerAuthorityRequiredError } from '../errors';
import { TransactionBuilder } from '../../../utils';
import { now, toPublicKey, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'DirectBuyOperation';
/**
 * Creates a bid on a given asset and then executes a sale on the created bid and listing.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .buy({ auctionHouse, listing, buyer };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const directBuyOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const directBuyOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const builder = yield directBuyBuilder(metaplex, operation.input, scope);
        scope.throwIfCanceled();
        return builder.sendAndConfirm(metaplex, scope.confirmOptions);
    }),
};
/**
 * Creates a bid on a given asset and executes a sale on the created bid and given listing.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .buy({ auctionHouse, listing, buyer })
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const directBuyBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    // Data.
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { auctionHouse, auctioneerAuthority, listing, price = listing.price, buyer = metaplex.identity(), authority = auctionHouse.authorityAddress, bookkeeper = metaplex.identity(), createBidInstructionKey, executeSaleInstructionKey, } = params;
    const { tokens, asset, sellerAddress, receiptAddress } = listing;
    const printReceipt = ((_a = params.printReceipt) !== null && _a !== void 0 ? _a : true) && Boolean(receiptAddress);
    if (auctionHouse.hasAuctioneer && !auctioneerAuthority) {
        throw new AuctioneerAuthorityRequiredError();
    }
    const bidBuilder = yield metaplex.auctionHouse().builders().bid({
        auctionHouse,
        auctioneerAuthority,
        authority,
        tokens,
        price,
        mintAccount: asset.mint.address,
        seller: sellerAddress,
        buyer,
        printReceipt,
        bookkeeper,
        instructionKey: createBidInstructionKey,
    }, { programs, payer });
    const { receipt, buyerTradeState } = bidBuilder.getContext();
    const bid = {
        model: 'bid',
        lazy: false,
        auctionHouse,
        asset,
        tradeStateAddress: buyerTradeState,
        bookkeeperAddress: bookkeeper.publicKey,
        buyerAddress: buyer.publicKey,
        receiptAddress: receipt,
        purchaseReceiptAddress: null,
        price,
        tokens,
        canceledAt: null,
        createdAt: now(),
        isPublic: false,
    };
    const saleBuilder = metaplex
        .auctionHouse()
        .builders()
        .executeSale({
        auctionHouse,
        auctioneerAuthority,
        bid,
        listing,
        printReceipt,
        bookkeeper,
        instructionKey: executeSaleInstructionKey,
    }, { programs, payer });
    const { receipt: purchaseReceiptAddress } = saleBuilder.getContext();
    const buyerTokenAccount = metaplex
        .tokens()
        .pdas()
        .associatedTokenAccount({
        mint: asset.address,
        owner: toPublicKey(buyer),
        programs,
    });
    const purchasedAsset = Object.assign(Object.assign({}, asset), { token: Object.assign(Object.assign({}, asset.token), { address: buyerTokenAccount, ownerAddress: toPublicKey(buyer) }) });
    const purchase = {
        auctionHouse,
        model: 'purchase',
        lazy: false,
        buyerAddress: toPublicKey(buyer),
        sellerAddress,
        asset: purchasedAsset,
        bookkeeperAddress: toPublicKey(bookkeeper),
        receiptAddress: purchaseReceiptAddress,
        price: listing.price,
        tokens,
        createdAt: now(),
    };
    return TransactionBuilder.make()
        .setContext({
        bid,
        purchase,
    })
        .add(bidBuilder)
        .add(saleBuilder);
});
//# sourceMappingURL=directBuy.js.map