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 { ACCOUNT_SIZE, createAssociatedTokenAccountInstruction, createInitializeAccountInstruction, } from '@solarti/spl-token';
import { ExpectedSignerError } from '../../../errors';
import { isSigner, makeConfirmOptionsFinalizedOnMainnet, toPublicKey, useOperation, } from '../../../types';
import { TransactionBuilder } from '../../../utils';
// -----------------
// Operation
// -----------------
const Key = 'CreateTokenOperation';
/**
 * Creates a new token account.
 *
 * ```ts
 * const { token } = await metaplex.tokens().createToken({ mint });
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const createTokenOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const createTokenOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const builder = yield createTokenBuilder(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()
                .findTokenByAddress({ address: output.tokenAddress }, scope);
            return Object.assign(Object.assign({}, output), { token });
        });
    },
};
/**
 * Creates a new token account.
 *
 * ```ts
 * const transactionBuilder = await metaplex.tokens().builders().createToken({ mint });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const createTokenBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { mint, owner = metaplex.identity().publicKey, token } = params;
    const tokenProgram = metaplex.programs().getToken(programs);
    const associatedTokenProgram = metaplex
        .programs()
        .getAssociatedToken(programs);
    const isAssociatedToken = token === undefined;
    const builder = TransactionBuilder.make().setFeePayer(payer);
    if (isAssociatedToken) {
        const associatedTokenAddress = metaplex
            .tokens()
            .pdas()
            .associatedTokenAccount({ mint, owner, programs });
        return (builder
            .setContext({ tokenAddress: associatedTokenAddress })
            // Create an associated token account.
            .add({
            instruction: createAssociatedTokenAccountInstruction(payer.publicKey, associatedTokenAddress, owner, mint, tokenProgram.address, associatedTokenProgram.address),
            signers: [payer],
            key: (_a = params.createAssociatedTokenAccountInstructionKey) !== null && _a !== void 0 ? _a : 'createAssociatedTokenAccount',
        }));
    }
    return (builder
        .setFeePayer(payer)
        .setContext({ tokenAddress: token.publicKey })
        // Create an empty account for the Token.
        .add(yield metaplex
        .system()
        .builders()
        .createAccount({
        newAccount: token,
        space: ACCOUNT_SIZE,
        program: tokenProgram.address,
        instructionKey: (_b = params.createAccountInstructionKey) !== null && _b !== void 0 ? _b : 'createAccount',
    }, { payer, programs }))
        // Initialize the Token.
        .add({
        instruction: createInitializeAccountInstruction(token.publicKey, mint, owner, tokenProgram.address),
        signers: [token],
        key: (_c = params.initializeTokenInstructionKey) !== null && _c !== void 0 ? _c : 'initializeToken',
    }));
});
/**
 * @group Transaction Builders
 * @category Constructors
 * @internal
 */
export const createTokenIfMissingBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { mint, owner = metaplex.identity().publicKey, token, tokenExists = true, tokenVariable = 'token', } = params;
    const destination = token !== null && token !== void 0 ? token : metaplex.tokens().pdas().associatedTokenAccount({ mint, owner, programs });
    const destinationAddress = toPublicKey(destination);
    const builder = TransactionBuilder.make()
        .setFeePayer(payer)
        .setContext({ tokenAddress: destinationAddress });
    if (tokenExists) {
        return builder;
    }
    // When creating a token account, ensure it is passed as a Signer.
    if (token && !isSigner(token)) {
        throw new ExpectedSignerError(tokenVariable, 'PublicKey', {
            problemSuffix: `The provided "${tokenVariable}" account ` +
                `at address [${destinationAddress}] does not exist. ` +
                `Therefore, it needs to be created and passed as a Signer.`,
            solution: `If you want to create the "${tokenVariable}" account, then please pass it as a Signer. ` +
                `Alternatively, you can pass the owner account as a PublicKey instead to ` +
                `use (or create) an associated token account.`,
        });
    }
    return builder.add(yield metaplex
        .tokens()
        .builders()
        .createToken(Object.assign(Object.assign({}, params), { mint,
        owner,
        token }), { programs, payer }));
});
//# sourceMappingURL=createToken.js.map