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 { Keypair } from '@solarti/web3.js';
import { MintAuthorityMustBeSignerToMintInitialSupplyError } from '../errors';
import { TransactionBuilder } from '../../../utils';
import { isSigner, makeConfirmOptionsFinalizedOnMainnet, toPublicKey, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'CreateTokenWithMintOperation';
/**
 * Creates both mint and token accounts in the same transaction.
 *
 * ```ts
 * const { token } = await metaplex.tokens().createTokenWithMint();
 * const mint = token.mint;
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const createTokenWithMintOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const createTokenWithMintOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const builder = yield createTokenWithMintBuilder(metaplex, operation.input, scope);
            scope.throwIfCanceled();
            const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
            const output = yield builder.sendAndConfirm(metaplex, confirmOptions);
            scope.throwIfCanceled();
            const token = yield metaplex.tokens().findTokenWithMintByMint({
                mint: output.mintSigner.publicKey,
                address: output.tokenAddress,
                addressType: 'token',
            }, scope);
            return Object.assign(Object.assign({}, output), { token });
        });
    },
};
/**
 * Creates both mint and token accounts in the same transaction.
 *
 * ```ts
 * const transactionBuilder = await metaplex.tokens().builders().createTokenWithMint();
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const createTokenWithMintBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e, _f;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { decimals = 0, initialSupply, mint = Keypair.generate(), mintAuthority = metaplex.identity(), freezeAuthority = metaplex.identity().publicKey, owner = metaplex.identity().publicKey, token, } = params;
    const createMintBuilder = yield metaplex
        .tokens()
        .builders()
        .createMint({
        decimals,
        mint,
        mintAuthority: toPublicKey(mintAuthority),
        freezeAuthority,
        createAccountInstructionKey: (_a = params.createMintAccountInstructionKey) !== null && _a !== void 0 ? _a : 'createMintAccount',
        initializeMintInstructionKey: (_b = params.initializeMintInstructionKey) !== null && _b !== void 0 ? _b : 'initializeMint',
    }, { programs, payer });
    const createTokenBuilder = yield metaplex
        .tokens()
        .builders()
        .createToken({
        mint: mint.publicKey,
        owner,
        token,
        createAssociatedTokenAccountInstructionKey: (_c = params.createAssociatedTokenAccountInstructionKey) !== null && _c !== void 0 ? _c : 'createAssociatedTokenAccount',
        createAccountInstructionKey: (_d = params.createTokenAccountInstructionKey) !== null && _d !== void 0 ? _d : 'createTokenAccount',
        initializeTokenInstructionKey: (_e = params.initializeTokenInstructionKey) !== null && _e !== void 0 ? _e : 'initializeToken',
    }, { payer, programs });
    const { tokenAddress } = createTokenBuilder.getContext();
    const builder = TransactionBuilder.make()
        .setFeePayer(payer)
        .setContext({ mintSigner: mint, tokenAddress })
        // Create the Mint account.
        .add(createMintBuilder)
        // Create the Token account.
        .add(createTokenBuilder);
    // Potentially mint the initial supply to the token account.
    if (!!initialSupply) {
        if (!isSigner(mintAuthority)) {
            throw new MintAuthorityMustBeSignerToMintInitialSupplyError();
        }
        builder.add(yield metaplex
            .tokens()
            .builders()
            .mint({
            mintAddress: mint.publicKey,
            toToken: tokenAddress,
            amount: initialSupply,
            mintAuthority,
            mintTokensInstructionKey: (_f = params.mintTokensInstructionKey) !== null && _f !== void 0 ? _f : 'mintTokens',
        }, { payer, programs }));
    }
    return builder;
});
//# sourceMappingURL=createTokenWithMint.js.map