'use strict';

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

var mplTokenMetadata = require('@metaplex-solarti/mpl-token-metadata');
var web3_js = require('@solarti/web3.js');
var accounts = require('../accounts.cjs');
var NftEdition = require('../models/NftEdition.cjs');
var Operation = require('../../../types/Operation.cjs');
var Nft = require('../models/Nft.cjs');
var BigNumber = require('../../../types/BigNumber.cjs');
var Amount = require('../../../types/Amount.cjs');
var TransactionBuilder = require('../../../utils/TransactionBuilder.cjs');

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

const Key = 'PrintNewEditionOperation';

/**
 * Prints a new edition from an original NFT.
 *
 * ```ts
 * const { nft } = await metaplex
 *   .nfts()
 *   .printNewEdition({ originalMint };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const printNewEditionOperation = Operation.useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const printNewEditionOperationHandler = {
  handle: async (operation, metaplex, scope) => {
    const originalEditionAccount = await metaplex.rpc().getAccount(metaplex.nfts().pdas().masterEdition({
      mint: operation.input.originalMint,
      programs: scope.programs
    }));
    scope.throwIfCanceled();
    const originalEdition = NftEdition.toNftOriginalEdition(accounts.toOriginalEditionAccount(originalEditionAccount));
    const builder = await printNewEditionBuilder(metaplex, {
      ...operation.input,
      originalSupply: originalEdition.supply
    }, scope);
    scope.throwIfCanceled();
    const confirmOptions = Operation.makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
    const output = await builder.sendAndConfirm(metaplex, confirmOptions);
    scope.throwIfCanceled();
    const nft = await metaplex.nfts().findByMint({
      mintAddress: output.mintSigner.publicKey,
      tokenAddress: output.tokenAddress
    }, scope);
    scope.throwIfCanceled();
    Nft.assertNftWithToken(nft);
    return {
      ...output,
      nft
    };
  }
};

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

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

/**
 * Prints a new edition from an original NFT.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .nfts()
 *   .builders()
 *   .printNewEdition({ originalMint });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
const printNewEditionBuilder = async (metaplex, params, options = {}) => {
  const {
    programs,
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    originalMint,
    newMint = web3_js.Keypair.generate(),
    newUpdateAuthority = metaplex.identity().publicKey,
    newOwner = metaplex.identity().publicKey,
    newTokenAccount,
    printNewEditionInstructionKey = 'printNewEdition'
  } = params;

  // Programs.
  const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs);

  // Original NFT.
  const originalMetadataAddress = metaplex.nfts().pdas().metadata({
    mint: originalMint,
    programs
  });
  const originalEditionAddress = metaplex.nfts().pdas().masterEdition({
    mint: originalMint,
    programs
  });
  const edition = BigNumber.toBigNumber(params.originalSupply.addn(1));
  const originalEditionMarkPda = metaplex.nfts().pdas().editionMarker({
    mint: originalMint,
    edition,
    programs
  });

  // New NFT.
  const newMintAuthority = web3_js.Keypair.generate(); // Will be overwritten by edition PDA.
  const newMetadataAddress = metaplex.nfts().pdas().metadata({
    mint: newMint.publicKey,
    programs
  });
  const newEditionAddress = metaplex.nfts().pdas().edition({
    mint: newMint.publicKey,
    programs
  });
  const sharedAccounts = {
    newMetadata: newMetadataAddress,
    newEdition: newEditionAddress,
    masterEdition: originalEditionAddress,
    newMint: newMint.publicKey,
    editionMarkPda: originalEditionMarkPda,
    newMintAuthority: newMintAuthority.publicKey,
    payer: payer.publicKey,
    newMetadataUpdateAuthority: newUpdateAuthority,
    metadata: originalMetadataAddress
  };
  const tokenWithMintBuilder = await metaplex.tokens().builders().createTokenWithMint({
    decimals: 0,
    initialSupply: Amount.token(1),
    mint: newMint,
    mintAuthority: newMintAuthority,
    freezeAuthority: newMintAuthority.publicKey,
    owner: newOwner,
    token: newTokenAccount,
    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 originalTokenAccountOwner = params.originalTokenAccountOwner ?? metaplex.identity();
  const originalTokenAccount = params.originalTokenAccount ?? metaplex.tokens().pdas().associatedTokenAccount({
    mint: originalMint,
    owner: originalTokenAccountOwner.publicKey,
    programs
  });
  return TransactionBuilder.TransactionBuilder.make().setFeePayer(payer).setContext({
    mintSigner: newMint,
    metadataAddress: newMetadataAddress,
    editionAddress: newEditionAddress,
    tokenAddress,
    updatedSupply: edition
  })

  // Create the mint and token accounts before minting 1 token to the owner.
  .add(tokenWithMintBuilder)

  // Mint new edition.
  .add({
    instruction: mplTokenMetadata.createMintNewEditionFromMasterEditionViaTokenInstruction({
      ...sharedAccounts,
      tokenAccountOwner: originalTokenAccountOwner.publicKey,
      tokenAccount: originalTokenAccount
    }, {
      mintNewEditionFromMasterEditionViaTokenArgs: {
        edition
      }
    }, tokenMetadataProgram.address),
    signers: [newMint, newMintAuthority, payer, originalTokenAccountOwner],
    key: printNewEditionInstructionKey
  });
};

exports.printNewEditionBuilder = printNewEditionBuilder;
exports.printNewEditionOperation = printNewEditionOperation;
exports.printNewEditionOperationHandler = printNewEditionOperationHandler;
//# sourceMappingURL=printNewEdition.cjs.map
