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 { createInitializeInstruction, initializeInstructionDiscriminator, } from '@metaplex-foundation/mpl-candy-guard';
import { Keypair } from '@solarti/web3.js';
import { emptyDefaultCandyGuardSettings, } from '../guards';
import { TransactionBuilder } from '../../../utils';
import { makeConfirmOptionsFinalizedOnMainnet, serializeDiscriminator, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'CreateCandyGuardOperation';
/**
 * Creates a new Candy Guard account with the provided settings.
 *
 * ```ts
 * const { candyGuard } = await metaplex
 *   .candyMachines()
 *   .createCandyGuard({
 *     guards: {
 *       startDate: { date: toDateTime('2022-09-05T20:00:00.000Z') },
 *       solPayment: { amount: sol(1.5), },
 *       botTax: { lamports: sol(0.01), lastInstruction: true },
 *     },
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const createCandyGuardOperation = _createCandyGuardOperation;
// eslint-disable-next-line @typescript-eslint/naming-convention
function _createCandyGuardOperation(input) {
    return { key: Key, input };
}
_createCandyGuardOperation.key = Key;
/**
 * @group Operations
 * @category Handlers
 */
export const createCandyGuardOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const builder = createCandyGuardBuilder(metaplex, operation.input, scope);
            const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
            const output = yield builder.sendAndConfirm(metaplex, confirmOptions);
            scope.throwIfCanceled();
            const candyGuard = yield metaplex
                .candyMachines()
                .findCandyGuardByBaseAddress({ address: output.base.publicKey }, scope);
            return Object.assign(Object.assign({}, output), { candyGuard });
        });
    },
};
/**
 * Creates a new Candy Guard account with the provided settings.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .candyMachines()
 *   .builders()
 *   .createCandyGuard({
 *     guards: {
 *       startDate: { date: toDateTime('2022-09-05T20:00:00.000Z') },
 *       solPayment: { amount: sol(1.5), },
 *       botTax: { lamports: sol(0.01), lastInstruction: true },
 *     },
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const createCandyGuardBuilder = (metaplex, params, options = {}) => {
    var _a, _b, _c, _d;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const base = (_a = params.base) !== null && _a !== void 0 ? _a : Keypair.generate();
    const authority = (_b = params.authority) !== null && _b !== void 0 ? _b : metaplex.identity().publicKey;
    const candyGuardProgram = metaplex.programs().getCandyGuard(programs);
    const candyGuard = metaplex
        .candyMachines()
        .pdas()
        .candyGuard({ base: base.publicKey, programs });
    const initializeInstruction = createInitializeInstruction({
        candyGuard,
        base: base.publicKey,
        authority,
        payer: payer.publicKey,
    }, {
        data: {
            default: emptyDefaultCandyGuardSettings,
            groups: null,
        },
    }, candyGuardProgram.address);
    const serializedSettings = metaplex
        .candyMachines()
        .guards()
        .serializeSettings(params.guards, (_c = params.groups) !== null && _c !== void 0 ? _c : [], programs);
    const discriminator = serializeDiscriminator(initializeInstructionDiscriminator);
    initializeInstruction.data = Buffer.concat([
        discriminator,
        serializedSettings,
    ]);
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        .setContext({ base, candyGuardAddress: candyGuard })
        // Create and initialize the candy guard account.
        .add({
        instruction: initializeInstruction,
        signers: [base, payer],
        key: (_d = params.createCandyGuardInstructionKey) !== null && _d !== void 0 ? _d : 'createCandyGuard',
    }));
};
//# sourceMappingURL=createCandyGuard.js.map