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 { createCreateMasterEditionV3Instruction, } from '@metaplex-solarti/mpl-token-metadata';
import { Keypair } from '@solarti/web3.js';
import { assertNftWithToken } from '../models';
import { TransactionBuilder } from '../../../utils';
import { makeConfirmOptionsFinalizedOnMainnet, token, toPublicKey, useOperation, } from '../../../types';
// -----------------
// Operation
// -----------------
const Key = 'CreateNftOperation';
/**
 * Creates a new NFT.
 *
 * ```ts
 * const { nft } = await metaplex
 *   .nfts()
 *   .create({
 *     name: 'My NFT',
 *     uri: 'https://example.com/my-nft',
 *     sellerFeeBasisPoints: 250, // 2.5%
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const createNftOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const createNftOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        const { useNewMint = Keypair.generate(), useExistingMint, tokenOwner = metaplex.identity().publicKey, tokenAddress: tokenSigner, } = operation.input;
        const mintAddress = useExistingMint !== null && useExistingMint !== void 0 ? useExistingMint : useNewMint.publicKey;
        const tokenAddress = tokenSigner
            ? toPublicKey(tokenSigner)
            : metaplex.tokens().pdas().associatedTokenAccount({
                mint: mintAddress,
                owner: tokenOwner,
                programs: scope.programs,
            });
        const tokenAccount = yield metaplex.rpc().getAccount(tokenAddress);
        const tokenExists = tokenAccount.exists;
        const builder = yield createNftBuilder(metaplex, Object.assign(Object.assign({}, operation.input), { useNewMint,
            tokenOwner,
            tokenExists }), 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.mintAddress,
            tokenAddress: output.tokenAddress,
        }, scope);
        scope.throwIfCanceled();
        assertNftWithToken(nft);
        return Object.assign(Object.assign({}, output), { nft });
    }),
};
/**
 * Creates a new NFT.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .nfts()
 *   .builders()
 *   .create({
 *     name: 'My NFT',
 *     uri: 'https://example.com/my-nft',
 *     sellerFeeBasisPoints: 250, // 2.5%
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const createNftBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { useNewMint = Keypair.generate(), updateAuthority = metaplex.identity(), mintAuthority = metaplex.identity(), tokenOwner = metaplex.identity().publicKey, } = params;
    const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs);
    const sftBuilder = yield metaplex
        .nfts()
        .builders()
        .createSft(Object.assign(Object.assign({}, params), { updateAuthority,
        mintAuthority, freezeAuthority: mintAuthority.publicKey, useNewMint,
        tokenOwner, tokenAmount: token(1), decimals: 0 }), { programs, payer });
    const { mintAddress, metadataAddress, tokenAddress } = sftBuilder.getContext();
    const masterEditionAddress = metaplex.nfts().pdas().masterEdition({
        mint: mintAddress,
        programs,
    });
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        .setContext({
        mintAddress,
        metadataAddress,
        masterEditionAddress,
        tokenAddress: tokenAddress,
    })
        // Create the mint, the token and the metadata.
        .add(sftBuilder)
        // Create master edition account (prevents further minting).
        .add({
        instruction: createCreateMasterEditionV3Instruction({
            edition: masterEditionAddress,
            mint: mintAddress,
            updateAuthority: updateAuthority.publicKey,
            mintAuthority: mintAuthority.publicKey,
            payer: payer.publicKey,
            metadata: metadataAddress,
        }, {
            createMasterEditionArgs: {
                maxSupply: params.maxSupply === undefined ? 0 : params.maxSupply,
            },
        }, tokenMetadataProgram.address),
        signers: [payer, mintAuthority, updateAuthority],
        key: (_a = params.createMasterEditionInstructionKey) !== null && _a !== void 0 ? _a : 'createMasterEdition',
    }));
});
//# sourceMappingURL=createNft.js.map