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