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 { createAuctioneerCancelInstruction, createCancelInstruction, createCancelListingReceiptInstruction, } from '@metaplex-foundation/mpl-auction-house';
import { SYSVAR_INSTRUCTIONS_PUBKEY } from '@solarti/web3.js';
import { AUCTIONEER_PRICE } from '../constants';
import { AuctioneerAuthorityRequiredError } from '../errors';
import { TransactionBuilder } from '../../../utils';
import { isSigner, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'CancelListingOperation';
/**
 * Cancels the user's listing in the given auction house.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .cancelListing({ auctionHouse, listing };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const cancelListingOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const cancelListingOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        return cancelListingBuilder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions);
    }),
};
/**
 * Cancels the user's listing in the given auction house.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .cancelListing({ auctionHouse, listing });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const cancelListingBuilder = (metaplex, params, options = {}) => {
    var _a;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { auctionHouse, auctioneerAuthority, listing } = params;
    // Data.
    const { asset, sellerAddress, receiptAddress, tradeStateAddress, price, tokens, } = listing;
    const { address: auctionHouseAddress, authorityAddress, feeAccountAddress, hasAuctioneer, } = auctionHouse;
    if (hasAuctioneer && !auctioneerAuthority) {
        throw new AuctioneerAuthorityRequiredError();
    }
    const buyerPrice = hasAuctioneer ? AUCTIONEER_PRICE : price.basisPoints;
    const accounts = {
        wallet: sellerAddress,
        tokenAccount: asset.token.address,
        tokenMint: asset.address,
        authority: authorityAddress,
        auctionHouse: auctionHouseAddress,
        auctionHouseFeeAccount: feeAccountAddress,
        tradeState: tradeStateAddress,
    };
    // Args.
    const args = {
        buyerPrice,
        tokenSize: tokens.basisPoints,
    };
    // Cancel Listing Instruction.
    let cancelListingInstruction = createCancelInstruction(accounts, args);
    if (auctioneerAuthority) {
        cancelListingInstruction = createAuctioneerCancelInstruction(Object.assign(Object.assign({}, accounts), { auctioneerAuthority: auctioneerAuthority.publicKey, ahAuctioneerPda: metaplex.auctionHouse().pdas().auctioneer({
                auctionHouse: auctionHouseAddress,
                auctioneerAuthority: auctioneerAuthority.publicKey,
                programs,
            }) }), args);
    }
    // Signers.
    const cancelSigners = [auctioneerAuthority].filter(isSigner);
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        // Cancel Listing.
        .add({
        instruction: cancelListingInstruction,
        signers: cancelSigners,
        key: (_a = params.instructionKey) !== null && _a !== void 0 ? _a : 'cancelListing',
    })
        // Cancel Listing Receipt.
        .when(Boolean(receiptAddress), (builder) => builder.add({
        instruction: createCancelListingReceiptInstruction({
            receipt: receiptAddress,
            instruction: SYSVAR_INSTRUCTIONS_PUBKEY,
        }),
        signers: [],
        key: 'cancelListingReceipt',
    })));
};
//# sourceMappingURL=cancelListing.js.map