import { MINT_SIZE, createInitializeMintInstruction } from '@solarti/spl-token';
import { Keypair } from '@solarti/web3.js';
import { useOperation, makeConfirmOptionsFinalizedOnMainnet } from '../../../types/Operation.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';

// -----------------
// Operation
// -----------------

const Key = 'CreateMintOperation';

/**
 * Creates a new mint account.
 *
 * ```ts
 * const { mint } = await metaplex.tokens().createMint();
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const createMintOperation = useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const createMintOperationHandler = {
  async handle(operation, metaplex, scope) {
    const builder = await createMintBuilder(metaplex, operation.input, scope);
    scope.throwIfCanceled();
    const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
    const output = await builder.sendAndConfirm(metaplex, confirmOptions);
    scope.throwIfCanceled();
    const mint = await metaplex.tokens().findMintByAddress({
      address: output.mintSigner.publicKey
    }, scope);
    return {
      ...output,
      mint
    };
  }
};

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

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

/**
 * Creates a new mint account.
 *
 * ```ts
 * const transactionBuilder = await metaplex.tokens().builders().createMint();
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const createMintBuilder = async (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    decimals = 0,
    mint = Keypair.generate(),
    mintAuthority = metaplex.identity().publicKey,
    freezeAuthority = mintAuthority
  } = params;
  const tokenProgram = metaplex.programs().getToken(programs);
  return TransactionBuilder.make().setFeePayer(payer).setContext({
    mintSigner: mint
  })

  // Create an empty account for the mint.
  .add(await metaplex.system().builders().createAccount({
    newAccount: mint,
    space: MINT_SIZE,
    program: tokenProgram.address,
    instructionKey: params.createAccountInstructionKey ?? 'createAccount'
  }, {
    payer,
    programs
  }))

  // Initialize the mint.
  .add({
    instruction: createInitializeMintInstruction(mint.publicKey, decimals, mintAuthority, freezeAuthority, tokenProgram.address),
    signers: [mint],
    key: params.initializeMintInstructionKey ?? 'initializeMint'
  });
};

export { createMintBuilder, createMintOperation, createMintOperationHandler };
//# sourceMappingURL=createMint.mjs.map
