'use strict';

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

var mplCandyMachine = require('@metaplex-solarti/mpl-candy-machine');
var web3_js = require('@solarti/web3.js');
var accounts = require('../accounts.cjs');
var asserts = require('../asserts.cjs');
var errors = require('../errors.cjs');
var pdas = require('../pdas.cjs');
var Operation = require('../../../types/Operation.cjs');
var Amount = require('../../../types/Amount.cjs');
var TransactionBuilder = require('../../../utils/TransactionBuilder.cjs');
var Account = require('../../../types/Account.cjs');

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

const Key = 'MintCandyMachineV2Operation';

/**
 * Mint an NFT from an existing Candy Machine.
 *
 * ```ts
 * const { nft } = await metaplex
 *   .candyMachinesV2()
 *   .mint({ candyMachine };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const mintCandyMachineV2Operation = Operation.useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const mintCandyMachineV2OperationHandler = {
  async handle(operation, metaplex, scope) {
    asserts.assertCanMintCandyMachineV2(operation.input.candyMachine, scope.payer);
    const builder = await mintCandyMachineV2Builder(metaplex, operation.input, scope);
    scope.throwIfCanceled();
    const confirmOptions = Operation.makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
    const output = await builder.sendAndConfirm(metaplex, confirmOptions);
    scope.throwIfCanceled();
    let nft;
    try {
      nft = await metaplex.nfts().findByMint({
        mintAddress: output.mintSigner.publicKey,
        tokenAddress: output.tokenAddress
      }, scope);
    } catch (error) {
      throw new errors.CandyMachineV2BotTaxError(metaplex.rpc().getSolanaExporerUrl(output.response.signature), error);
    }
    return {
      nft,
      ...output
    };
  }
};

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

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

/**
 * Mint an NFT from an existing Candy Machine.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .candyMachinesV2()
 *   .builders()
 *   .mint({ candyMachine });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const mintCandyMachineV2Builder = async (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    candyMachine,
    newMint = web3_js.Keypair.generate(),
    newOwner = metaplex.identity().publicKey,
    newToken
  } = params;
  const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs).address;
  const newMetadata = metaplex.nfts().pdas().metadata({
    mint: newMint.publicKey,
    programs
  });
  const newEdition = metaplex.nfts().pdas().masterEdition({
    mint: newMint.publicKey,
    programs
  });
  const candyMachineCreator = pdas.findCandyMachineV2CreatorPda(candyMachine.address);
  const candyMachineCollectionAddress = pdas.findCandyMachineV2CollectionPda(candyMachine.address);
  const candyMachineCollectionAccount = accounts.parseCandyMachineV2CollectionAccount(await metaplex.rpc().getAccount(candyMachineCollectionAddress));
  const tokenWithMintBuilder = await metaplex.tokens().builders().createTokenWithMint({
    decimals: 0,
    initialSupply: Amount.token(1),
    mint: newMint,
    mintAuthority: payer,
    freezeAuthority: payer.publicKey,
    owner: newOwner,
    token: newToken,
    createMintAccountInstructionKey: params.createMintAccountInstructionKey,
    initializeMintInstructionKey: params.initializeMintInstructionKey,
    createAssociatedTokenAccountInstructionKey: params.createAssociatedTokenAccountInstructionKey,
    createTokenAccountInstructionKey: params.createTokenAccountInstructionKey,
    initializeTokenInstructionKey: params.initializeTokenInstructionKey,
    mintTokensInstructionKey: params.mintTokensInstructionKey
  }, {
    payer,
    programs
  });
  const {
    tokenAddress
  } = tokenWithMintBuilder.getContext();
  const mintNftInstruction = mplCandyMachine.createMintNftInstruction({
    candyMachine: candyMachine.address,
    candyMachineCreator,
    payer: payer.publicKey,
    wallet: candyMachine.walletAddress,
    metadata: newMetadata,
    mint: newMint.publicKey,
    mintAuthority: payer.publicKey,
    updateAuthority: payer.publicKey,
    masterEdition: newEdition,
    tokenMetadataProgram,
    clock: web3_js.SYSVAR_CLOCK_PUBKEY,
    recentBlockhashes: web3_js.SYSVAR_SLOT_HASHES_PUBKEY,
    instructionSysvarAccount: web3_js.SYSVAR_INSTRUCTIONS_PUBKEY
  }, {
    creatorBump: candyMachineCreator.bump
  });
  if (candyMachine.whitelistMintSettings) {
    const whitelistToken = params.whitelistToken ?? metaplex.tokens().pdas().associatedTokenAccount({
      mint: candyMachine.whitelistMintSettings.mint,
      owner: payer.publicKey
    });
    mintNftInstruction.keys.push({
      pubkey: whitelistToken,
      isWritable: true,
      isSigner: false
    }, {
      pubkey: candyMachine.whitelistMintSettings.mint,
      isWritable: true,
      isSigner: false
    }, {
      pubkey: payer.publicKey,
      isWritable: false,
      isSigner: true
    });
  }
  if (candyMachine.tokenMintAddress) {
    const payerToken = params.payerToken ?? metaplex.tokens().pdas().associatedTokenAccount({
      mint: candyMachine.tokenMintAddress,
      owner: payer.publicKey
    });
    mintNftInstruction.keys.push({
      pubkey: payerToken,
      isWritable: true,
      isSigner: false
    }, {
      pubkey: payer.publicKey,
      isWritable: false,
      isSigner: true
    });
  }
  return TransactionBuilder.TransactionBuilder.make().setFeePayer(payer).setContext({
    mintSigner: newMint,
    tokenAddress
  })

  // Create token and mint accounts.
  .add(tokenWithMintBuilder)

  // Create the new NFT.
  .add({
    instruction: mintNftInstruction,
    signers: [payer, newMint],
    key: params.mintNftInstructionKey ?? 'mintNft'
  })

  // Set the collection on the NFT.
  .when(candyMachineCollectionAccount.exists, builder => {
    Account.assertAccountExists(candyMachineCollectionAccount);
    const collectionMint = candyMachineCollectionAccount.data.mint;
    const collectionMetadata = metaplex.nfts().pdas().metadata({
      mint: collectionMint,
      programs
    });
    const collectionMasterEdition = metaplex.nfts().pdas().masterEdition({
      mint: collectionMint,
      programs
    });
    const collectionAuthorityRecord = metaplex.nfts().pdas().collectionAuthorityRecord({
      mint: collectionMint,
      collectionAuthority: candyMachineCollectionAccount.publicKey,
      programs
    });
    return builder.add({
      instruction: mplCandyMachine.createSetCollectionDuringMintInstruction({
        candyMachine: candyMachine.address,
        metadata: newMetadata,
        payer: payer.publicKey,
        collectionPda: candyMachineCollectionAccount.publicKey,
        tokenMetadataProgram,
        instructions: web3_js.SYSVAR_INSTRUCTIONS_PUBKEY,
        collectionMint: candyMachineCollectionAccount.data.mint,
        collectionMetadata,
        collectionMasterEdition,
        authority: candyMachine.authorityAddress,
        collectionAuthorityRecord
      }),
      signers: [payer],
      key: params.setCollectionInstructionKey ?? 'setCollection'
    });
  });
};

exports.mintCandyMachineV2Builder = mintCandyMachineV2Builder;
exports.mintCandyMachineV2Operation = mintCandyMachineV2Operation;
exports.mintCandyMachineV2OperationHandler = mintCandyMachineV2OperationHandler;
//# sourceMappingURL=mintCandyMachineV2.cjs.map
