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, createCancelBidReceiptInstruction, createCancelInstruction, } from '@metaplex-foundation/mpl-auction-house';
import { SYSVAR_INSTRUCTIONS_PUBKEY } from '@solarti/web3.js';
import { AuctioneerAuthorityRequiredError } from '../errors';
import { TransactionBuilder } from '../../../utils';
import { isSigner, toPublicKey, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'CancelBidOperation';
/**
 * Cancels the user's bid in the given auction house.
 *
 * ```ts
 * await metaplex
 *   .auctionHouse()
 *   .cancelBid({ auctionHouse, bid };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const cancelBidOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const cancelBidOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        return cancelBidBuilder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions);
    }),
};
/**
 * Cancels the user's bid in the given auction house.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .auctionHouse()
 *   .builders()
 *   .cancelBid({ auctionHouse, bid });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const cancelBidBuilder = (metaplex, params, options = {}) => {
    var _a;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { auctionHouse, auctioneerAuthority, bid } = params;
    // Data.
    const { asset, buyerAddress, tradeStateAddress, price, receiptAddress, tokens, isPublic, } = bid;
    const { authorityAddress, address: auctionHouseAddress, feeAccountAddress, hasAuctioneer, } = auctionHouse;
    if (hasAuctioneer && !auctioneerAuthority) {
        throw new AuctioneerAuthorityRequiredError();
    }
    // Accounts.
    const tokenAccount = isPublic
        ? metaplex
            .tokens()
            .pdas()
            .associatedTokenAccount({
            mint: asset.mint.address,
            owner: toPublicKey(buyerAddress),
            programs,
        })
        : asset.token.address;
    const accounts = {
        wallet: buyerAddress,
        tokenAccount,
        tokenMint: asset.address,
        authority: authorityAddress,
        auctionHouse: auctionHouseAddress,
        auctionHouseFeeAccount: feeAccountAddress,
        tradeState: tradeStateAddress,
    };
    // Args.
    const args = {
        buyerPrice: price.basisPoints,
        tokenSize: tokens.basisPoints,
    };
    // Cancel Bid Instruction.
    let cancelBidInstruction = createCancelInstruction(accounts, args);
    if (auctioneerAuthority) {
        cancelBidInstruction = 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 Bid.
        .add({
        instruction: cancelBidInstruction,
        signers: cancelSigners,
        key: (_a = params.instructionKey) !== null && _a !== void 0 ? _a : 'cancelBid',
    })
        // Cancel Bid Receipt.
        .when(Boolean(receiptAddress), (builder) => builder.add({
        instruction: createCancelBidReceiptInstruction({
            receipt: receiptAddress,
            instruction: SYSVAR_INSTRUCTIONS_PUBKEY,
        }),
        signers: [],
        key: 'cancelBidReceipt',
    })));
};
//# sourceMappingURL=cancelBid.js.map