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 { createRouteInstruction } from '@metaplex-foundation/mpl-candy-guard';
import * as beet from '@metaplex-foundation/beet';
import { CandyGuardRequiredOnCandyMachineError } from '../errors';
import { TransactionBuilder } from '../../../utils';
// -----------------
// Operation
// -----------------
const Key = 'CallCandyGuardRouteOperation';
/**
 * Calls the special "route" instruction on a specific guard.
 *
 * This allows guards to provide additional features such as creating
 * PDAs that verify a payer before the mint instruction is executed or
 * freezing and thawing minted NFTs.
 *
 * The "route" instruction must select a specific guard on a specific group
 * (if groups are enabled) since it is possible for the same type of guard
 * to have different settings based on its group.
 *
 * Additionally, it is possible for a guard to support multiple "paths" within
 * their "route" instruction. The route settings of the guard will usually use
 * the `path` property to distinguish them.
 *
 * ```ts
 * const { nft } = await metaplex
 *   .candyMachines()
 *   .callGuardRoute({
 *     candyMachine,
 *     guard: 'allowList',
 *     settings: {
 *       path: 'proof',
 *       merkleProof: getMerkleProof(data, leaf)
 *     },
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const callCandyGuardRouteOperation = _callCandyGuardRouteOperation;
// eslint-disable-next-line @typescript-eslint/naming-convention
function _callCandyGuardRouteOperation(input) {
    return { key: Key, input };
}
_callCandyGuardRouteOperation.key = Key;
/**
 * @group Operations
 * @category Handlers
 */
export const callCandyGuardRouteOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const builder = callCandyGuardRouteBuilder(metaplex, operation.input, scope);
            return builder.sendAndConfirm(metaplex, scope.confirmOptions);
        });
    },
};
/**
 * Calls the special "route" instruction on a specific guard.
 *
 * This allows guards to provide additional features such as creating
 * PDAs that verify a payer before the mint instruction is executed or
 * freezing and thawing minted NFTs.
 *
 * The "route" instruction must select a specific guard on a specific group
 * (if groups are enabled) since it is possible for the same type of guard
 * to have different settings based on its group.
 *
 * Additionally, it is possible for a guard to support multiple "paths" within
 * their "route" instruction. The route settings of the guard will usually use
 * the `path` property to distinguish them.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .candyMachines()
 *   .builders()
 *   .callGuardRoute({
 *     candyMachine,
 *     guard: 'allowList',
 *     settings: {
 *       path: 'proof',
 *       merkleProof: getMerkleProof(data, leaf)
 *     },
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const callCandyGuardRouteBuilder = (metaplex, params, options = {}) => {
    var _a;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { candyMachine, guard, settings, group = null } = params;
    if (!candyMachine.candyGuard) {
        throw new CandyGuardRequiredOnCandyMachineError();
    }
    // Route instruction.
    const parsedRouteSettings = metaplex
        .candyMachines()
        .guards()
        .parseRouteSettings(candyMachine.address, candyMachine.candyGuard, payer, guard, settings, group, programs);
    const routeSigners = [payer, ...parsedRouteSettings.signers];
    const routeInstruction = createRouteInstruction({
        candyGuard: candyMachine.candyGuard.address,
        candyMachine: candyMachine.address,
        payer: payer.publicKey,
    }, {
        args: {
            // "GuardType" is an enum for default guards only and will assert this
            // whereas we want to allow custom guards, so we need to pass anything
            // here to create the instruction and override this data afterwards.
            guard: 0,
            data: parsedRouteSettings.arguments,
        },
        label: group,
    }, metaplex.programs().getCandyGuard(programs).address);
    routeInstruction.keys.push(...parsedRouteSettings.accountMetas);
    // As promised, we override the guard index here.
    const availableGuards = metaplex
        .candyMachines()
        .guards()
        .forCandyGuardProgram(programs);
    const guardIndex = availableGuards.findIndex((g) => g.name === guard);
    beet.u8.write(routeInstruction.data, 8, guardIndex);
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        // Route instruction.
        .add({
        instruction: routeInstruction,
        signers: routeSigners,
        key: (_a = params.instructionKey) !== null && _a !== void 0 ? _a : 'callGuardRoute',
    }));
};
//# sourceMappingURL=callCandyGuardRoute.js.map