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 { createMintNewEditionFromMasterEditionViaTokenInstruction } from '@metaplex-solarti/mpl-token-metadata';
import { Keypair } from '@solarti/web3.js';
import { toOriginalEditionAccount } from '../accounts';
import { assertNftWithToken, toNftOriginalEdition, } from '../models';
import { TransactionBuilder } from '../../../utils';
import { makeConfirmOptionsFinalizedOnMainnet, toBigNumber, token, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'PrintNewEditionOperation';
/**
 * Prints a new edition from an original NFT.
 *
 * ```ts
 * const { nft } = await metaplex
 *   .nfts()
 *   .printNewEdition({ originalMint };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const printNewEditionOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const printNewEditionOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const originalEditionAccount = yield metaplex.rpc().getAccount(metaplex.nfts().pdas().masterEdition({
            mint: operation.input.originalMint,
            programs: scope.programs,
        }));
        scope.throwIfCanceled();
        const originalEdition = toNftOriginalEdition(toOriginalEditionAccount(originalEditionAccount));
        const builder = yield printNewEditionBuilder(metaplex, Object.assign(Object.assign({}, operation.input), { originalSupply: originalEdition.supply }), scope);
        scope.throwIfCanceled();
        const confirmOptions = makeConfirmOptionsFinalizedOnMainnet(metaplex, scope.confirmOptions);
        const output = yield builder.sendAndConfirm(metaplex, confirmOptions);
        scope.throwIfCanceled();
        const nft = yield metaplex.nfts().findByMint({
            mintAddress: output.mintSigner.publicKey,
            tokenAddress: output.tokenAddress,
        }, scope);
        scope.throwIfCanceled();
        assertNftWithToken(nft);
        return Object.assign(Object.assign({}, output), { nft });
    }),
};
/**
 * Prints a new edition from an original NFT.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .nfts()
 *   .builders()
 *   .printNewEdition({ originalMint });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const printNewEditionBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { originalMint, newMint = 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 = toBigNumber(params.originalSupply.addn(1));
    const originalEditionMarkPda = metaplex.nfts().pdas().editionMarker({
        mint: originalMint,
        edition,
        programs,
    });
    // New NFT.
    const newMintAuthority = 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 = yield metaplex
        .tokens()
        .builders()
        .createTokenWithMint({
        decimals: 0,
        initialSupply: 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 = (_a = params.originalTokenAccountOwner) !== null && _a !== void 0 ? _a : metaplex.identity();
    const originalTokenAccount = (_b = params.originalTokenAccount) !== null && _b !== void 0 ? _b : metaplex.tokens().pdas().associatedTokenAccount({
        mint: originalMint,
        owner: originalTokenAccountOwner.publicKey,
        programs,
    });
    return (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: createMintNewEditionFromMasterEditionViaTokenInstruction(Object.assign(Object.assign({}, sharedAccounts), { tokenAccountOwner: originalTokenAccountOwner.publicKey, tokenAccount: originalTokenAccount }), { mintNewEditionFromMasterEditionViaTokenArgs: { edition } }, tokenMetadataProgram.address),
        signers: [newMint, newMintAuthority, payer, originalTokenAccountOwner],
        key: printNewEditionInstructionKey,
    }));
});
//# sourceMappingURL=printNewEdition.js.map