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 { createAuctioneerExecuteSaleInstruction, createExecutePartialSaleInstruction, createExecuteSaleInstruction, createPrintPurchaseReceiptInstruction, } from '@metaplex-foundation/mpl-auction-house';
import { SYSVAR_INSTRUCTIONS_PUBKEY } from '@solarti/web3.js';
import { AuctioneerAuthorityRequiredError, AuctioneerPartialSaleNotSupportedError, BidAndListingHaveDifferentAuctionHousesError, BidAndListingHaveDifferentMintsError, CanceledBidIsNotAllowedError, CanceledListingIsNotAllowedError, PartialPriceMismatchError, } from '../errors';
import { TransactionBuilder } from '../../../utils';
import { amount, isSigner, lamports, now, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'ExecuteSaleOperation';
/**
 * Executes a sale on a given bid and listing.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .executeSale({ auctionHouse, bid, listing };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const executeSaleOperation = useOperation(Key);
/**
 * Executes a sale on a given bid and listing.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .executeSale({ auctionHouse, listing, bid });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const executeSaleOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const { auctionHouse } = operation.input;
            const output = yield executeSaleBuilder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions);
            scope.throwIfCanceled();
            if (output.receipt) {
                const purchase = yield metaplex
                    .auctionHouse()
                    .findPurchaseByReceipt({ auctionHouse, receiptAddress: output.receipt }, scope);
                return Object.assign({ purchase }, output);
            }
            const lazyPurchase = {
                model: 'purchase',
                lazy: true,
                auctionHouse: operation.input.auctionHouse,
                buyerAddress: output.buyer,
                sellerAddress: output.seller,
                metadataAddress: output.metadata,
                bookkeeperAddress: output.bookkeeper,
                receiptAddress: output.receipt,
                price: output.price,
                tokens: output.tokens.basisPoints,
                createdAt: now(),
            };
            return Object.assign({ purchase: yield metaplex
                    .auctionHouse()
                    .loadPurchase({ lazyPurchase }, scope) }, output);
        });
    },
};
/**
 * @group Transaction Builders
 * @category Constructors
 */
export const executeSaleBuilder = (metaplex, params, options = {}) => {
    var _a, _b, _c;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { auctionHouse, listing, bid, auctioneerAuthority } = params;
    const { sellerAddress, asset } = listing;
    const { buyerAddress } = bid;
    const { hasAuctioneer, isNative, treasuryMint, address: auctionHouseAddress, authorityAddress, feeAccountAddress, treasuryAccountAddress, } = auctionHouse;
    const isPartialSale = bid.tokens.basisPoints < listing.tokens.basisPoints;
    // Use full size of listing & price when finding trade state PDA for the partial sale.
    const { tokens, price } = isPartialSale ? listing : bid;
    const { price: buyerPrice, tokens: buyerTokensSize } = bid;
    if (!listing.auctionHouse.address.equals(bid.auctionHouse.address)) {
        throw new BidAndListingHaveDifferentAuctionHousesError();
    }
    if (!listing.asset.address.equals(bid.asset.address)) {
        throw new BidAndListingHaveDifferentMintsError();
    }
    if (bid.canceledAt) {
        throw new CanceledBidIsNotAllowedError();
    }
    if (listing.canceledAt) {
        throw new CanceledListingIsNotAllowedError();
    }
    if (hasAuctioneer && !auctioneerAuthority) {
        throw new AuctioneerAuthorityRequiredError();
    }
    if (isPartialSale && hasAuctioneer) {
        throw new AuctioneerPartialSaleNotSupportedError();
    }
    if (isPartialSale) {
        const listingPricePerToken = price.basisPoints.div(tokens.basisPoints);
        const buyerPricePerToken = buyerPrice.basisPoints.div(buyerTokensSize.basisPoints);
        if (!listingPricePerToken.eq(buyerPricePerToken)) {
            throw new PartialPriceMismatchError(auctionHouse.isNative
                ? lamports(listingPricePerToken)
                : amount(listingPricePerToken, auctionHouse.treasuryMint.currency), auctionHouse.isNative
                ? lamports(buyerPricePerToken)
                : amount(buyerPricePerToken, auctionHouse.treasuryMint.currency));
        }
    }
    // Accounts.
    const sellerPaymentReceiptAccount = isNative
        ? sellerAddress
        : metaplex.tokens().pdas().associatedTokenAccount({
            mint: treasuryMint.address,
            owner: sellerAddress,
            programs,
        });
    const buyerReceiptTokenAccount = metaplex
        .tokens()
        .pdas()
        .associatedTokenAccount({
        mint: asset.address,
        owner: buyerAddress,
        programs,
    });
    const escrowPayment = metaplex.auctionHouse().pdas().buyerEscrow({
        auctionHouse: auctionHouseAddress,
        buyer: buyerAddress,
        programs,
    });
    const freeTradeState = metaplex
        .auctionHouse()
        .pdas()
        .tradeState({
        auctionHouse: auctionHouseAddress,
        wallet: sellerAddress,
        treasuryMint: treasuryMint.address,
        tokenMint: asset.address,
        price: lamports(0).basisPoints,
        tokenSize: tokens.basisPoints,
        tokenAccount: asset.token.address,
        programs,
    });
    const programAsSigner = metaplex.auctionHouse().pdas().programAsSigner();
    const accounts = {
        buyer: buyerAddress,
        seller: sellerAddress,
        tokenAccount: asset.token.address,
        tokenMint: asset.address,
        metadata: asset.metadataAddress,
        treasuryMint: treasuryMint.address,
        escrowPaymentAccount: escrowPayment,
        sellerPaymentReceiptAccount,
        buyerReceiptTokenAccount,
        authority: authorityAddress,
        auctionHouse: auctionHouseAddress,
        auctionHouseFeeAccount: feeAccountAddress,
        auctionHouseTreasury: treasuryAccountAddress,
        buyerTradeState: bid.tradeStateAddress,
        sellerTradeState: listing.tradeStateAddress,
        freeTradeState,
        programAsSigner,
    };
    // Args.
    const args = {
        freeTradeStateBump: freeTradeState.bump,
        escrowPaymentBump: escrowPayment.bump,
        programAsSignerBump: programAsSigner.bump,
        buyerPrice: price.basisPoints,
        tokenSize: tokens.basisPoints,
    };
    // Execute Sale Instruction
    const partialSaleArgs = Object.assign(Object.assign({}, args), { partialOrderSize: bid.tokens.basisPoints, partialOrderPrice: bid.price.basisPoints });
    let executeSaleInstruction = isPartialSale
        ? createExecutePartialSaleInstruction(accounts, partialSaleArgs)
        : createExecuteSaleInstruction(accounts, args);
    if (auctioneerAuthority) {
        const auctioneerAccounts = Object.assign(Object.assign({}, accounts), { auctioneerAuthority: auctioneerAuthority.publicKey, ahAuctioneerPda: metaplex.auctionHouse().pdas().auctioneer({
                auctionHouse: auctionHouse.address,
                auctioneerAuthority: auctioneerAuthority.publicKey,
                programs,
            }) });
        executeSaleInstruction = createAuctioneerExecuteSaleInstruction(auctioneerAccounts, args);
    }
    // Provide additional keys to pay royalties.
    asset.creators.forEach(({ address }) => {
        executeSaleInstruction.keys.push({
            pubkey: address,
            isWritable: true,
            isSigner: false,
        });
        // Provide ATA to receive SPL token royalty if is not native SOL sale.
        if (!isNative) {
            executeSaleInstruction.keys.push({
                pubkey: metaplex.tokens().pdas().associatedTokenAccount({
                    mint: treasuryMint.address,
                    owner: address,
                    programs,
                }),
                isWritable: true,
                isSigner: false,
            });
        }
    });
    // Signers.
    const executeSaleSigners = [auctioneerAuthority].filter(isSigner);
    // Receipt.
    const shouldPrintReceipt = ((_a = params.printReceipt) !== null && _a !== void 0 ? _a : true) &&
        Boolean(listing.receiptAddress && bid.receiptAddress && !isPartialSale);
    const bookkeeper = (_b = params.bookkeeper) !== null && _b !== void 0 ? _b : metaplex.identity();
    const purchaseReceipt = metaplex.auctionHouse().pdas().purchaseReceipt({
        listingTradeState: listing.tradeStateAddress,
        bidTradeState: bid.tradeStateAddress,
        programs,
    });
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        .setContext({
        sellerTradeState: listing.tradeStateAddress,
        buyerTradeState: bid.tradeStateAddress,
        buyer: buyerAddress,
        seller: sellerAddress,
        metadata: asset.metadataAddress,
        bookkeeper: shouldPrintReceipt ? bookkeeper.publicKey : null,
        receipt: shouldPrintReceipt ? purchaseReceipt : null,
        price,
        tokens,
    })
        // Execute Sale.
        .add({
        instruction: executeSaleInstruction,
        signers: executeSaleSigners,
        key: (_c = params.instructionKey) !== null && _c !== void 0 ? _c : 'executeSale',
    })
        // Print the Purchase Receipt.
        .when(shouldPrintReceipt, (builder) => builder.add({
        instruction: createPrintPurchaseReceiptInstruction({
            purchaseReceipt,
            listingReceipt: listing.receiptAddress,
            bidReceipt: bid.receiptAddress,
            bookkeeper: bookkeeper.publicKey,
            instruction: SYSVAR_INSTRUCTIONS_PUBKEY,
        }, { purchaseReceiptBump: purchaseReceipt.bump }),
        signers: [bookkeeper],
        key: 'printPurchaseReceipt',
    })));
};
//# sourceMappingURL=executeSale.js.map