'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var web3_js = require('@solarti/web3.js');
var errors = require('../errors.cjs');
var Operation = require('../../../types/Operation.cjs');
var PublicKey = require('../../../types/PublicKey.cjs');
var TransactionBuilder = require('../../../utils/TransactionBuilder.cjs');
var Signer = require('../../../types/Signer.cjs');

// -----------------
// 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
 */
const createTokenWithMintOperation = Operation.useOperation(Key);

/**
 * @group Operations
 * @category Types
 */

/**
 * @group Operations
 * @category Handlers
 */
const createTokenWithMintOperationHandler = {
  async handle(operation, metaplex, scope) {
    const builder = await createTokenWithMintBuilder(metaplex, operation.input, scope);
    scope.throwIfCanceled();
    const confirmOptions = Operation.makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
    const output = await builder.sendAndConfirm(metaplex, confirmOptions);
    scope.throwIfCanceled();
    const token = await metaplex.tokens().findTokenWithMintByMint({
      mint: output.mintSigner.publicKey,
      address: output.tokenAddress,
      addressType: 'token'
    }, scope);
    return {
      ...output,
      token
    };
  }
};

// -----------------
// Builder
// -----------------

/**
 * @group Transaction Builders
 * @category Inputs
 */

/**
 * Creates both mint and token accounts in the same transaction.
 *
 * ```ts
 * const transactionBuilder = await metaplex.tokens().builders().createTokenWithMint();
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const createTokenWithMintBuilder = async (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    decimals = 0,
    initialSupply,
    mint = web3_js.Keypair.generate(),
    mintAuthority = metaplex.identity(),
    freezeAuthority = metaplex.identity().publicKey,
    owner = metaplex.identity().publicKey,
    token
  } = params;
  const createMintBuilder = await metaplex.tokens().builders().createMint({
    decimals,
    mint,
    mintAuthority: PublicKey.toPublicKey(mintAuthority),
    freezeAuthority,
    createAccountInstructionKey: params.createMintAccountInstructionKey ?? 'createMintAccount',
    initializeMintInstructionKey: params.initializeMintInstructionKey ?? 'initializeMint'
  }, {
    programs,
    payer
  });
  const createTokenBuilder = await metaplex.tokens().builders().createToken({
    mint: mint.publicKey,
    owner,
    token,
    createAssociatedTokenAccountInstructionKey: params.createAssociatedTokenAccountInstructionKey ?? 'createAssociatedTokenAccount',
    createAccountInstructionKey: params.createTokenAccountInstructionKey ?? 'createTokenAccount',
    initializeTokenInstructionKey: params.initializeTokenInstructionKey ?? 'initializeToken'
  }, {
    payer,
    programs
  });
  const {
    tokenAddress
  } = createTokenBuilder.getContext();
  const builder = TransactionBuilder.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 (!Signer.isSigner(mintAuthority)) {
      throw new errors.MintAuthorityMustBeSignerToMintInitialSupplyError();
    }
    builder.add(await metaplex.tokens().builders().mint({
      mintAddress: mint.publicKey,
      toToken: tokenAddress,
      amount: initialSupply,
      mintAuthority,
      mintTokensInstructionKey: params.mintTokensInstructionKey ?? 'mintTokens'
    }, {
      payer,
      programs
    }));
  }
  return builder;
};

exports.createTokenWithMintBuilder = createTokenWithMintBuilder;
exports.createTokenWithMintOperation = createTokenWithMintOperation;
exports.createTokenWithMintOperationHandler = createTokenWithMintOperationHandler;
//# sourceMappingURL=createTokenWithMint.cjs.map
