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 { createMintToInstruction } from '@solarti/spl-token';
import { isSigner, toPublicKey, useOperation, } from '../../../types';
import { TransactionBuilder } from '../../../utils';
// -----------------
// Operation
// -----------------
const Key = 'MintTokensOperation';
/**
 * Mint tokens to an account.
 *
 * ```ts
 * await metaplex
 *   .tokens()
 *   .mint({
 *     mintAddress,
 *     toOwner,
 *     amount: token(100),
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const mintTokensOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const mintTokensOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const { programs, confirmOptions } = scope;
            const { mintAddress, toOwner = metaplex.identity().publicKey, toToken, } = operation.input;
            const destination = toToken !== null && toToken !== void 0 ? toToken : metaplex.tokens().pdas().associatedTokenAccount({
                mint: mintAddress,
                owner: toOwner,
                programs,
            });
            const destinationAddress = toPublicKey(destination);
            const destinationAccountExists = yield metaplex
                .rpc()
                .accountExists(destinationAddress);
            scope.throwIfCanceled();
            const builder = yield mintTokensBuilder(metaplex, Object.assign(Object.assign({}, operation.input), { toTokenExists: destinationAccountExists }), scope);
            scope.throwIfCanceled();
            return builder.sendAndConfirm(metaplex, confirmOptions);
        });
    },
};
/**
 * Mint tokens to an account.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .tokens()
 *   .builders()
 *   .mint({
 *     mintAddress,
 *     toOwner,
 *     amount: token(100),
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const mintTokensBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { mintAddress, amount, toOwner = metaplex.identity().publicKey, toToken, toTokenExists = true, mintAuthority = metaplex.identity(), multiSigners = [], } = params;
    const [mintAuthorityPublicKey, signers] = isSigner(mintAuthority)
        ? [mintAuthority.publicKey, [mintAuthority]]
        : [mintAuthority, multiSigners];
    const tokenProgram = metaplex.programs().getToken(programs);
    const destination = toToken !== null && toToken !== void 0 ? toToken : metaplex.tokens().pdas().associatedTokenAccount({
        mint: mintAddress,
        owner: toOwner,
        programs,
    });
    return (TransactionBuilder.make()
        // Create token account if missing.
        .add(yield metaplex
        .tokens()
        .builders()
        .createTokenIfMissing(Object.assign(Object.assign({}, params), { mint: mintAddress, owner: toOwner, token: toToken, tokenExists: toTokenExists, tokenVariable: 'toToken' }), { payer, programs }))
        // Mint tokens.
        .add({
        instruction: createMintToInstruction(mintAddress, toPublicKey(destination), mintAuthorityPublicKey, amount.basisPoints.toNumber(), multiSigners, tokenProgram.address),
        signers,
        key: (_a = params.mintTokensInstructionKey) !== null && _a !== void 0 ? _a : 'mintTokens',
    }));
});
//# sourceMappingURL=mintTokens.js.map