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 { createUtilizeInstruction } from '@metaplex-solarti/mpl-token-metadata';
import { ExpectedSignerError } from '../../../errors';
import { isSigner, toPublicKey, useOperation, } from '../../../types';
import { TransactionBuilder } from '../../../utils';
// -----------------
// Operation
// -----------------
const Key = 'UseNftOperation';
/**
 * Utilizes a usable NFT.
 *
 * ```ts
 * await metaplex.nfts().use({ mintAddress });
 * await metaplex.nfts().use({ mintAddress, numberOfUses: 3 });
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const useNftOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const useNftOperationHandler = {
    handle: (operation, metaplex, scope) => __awaiter(void 0, void 0, void 0, function* () {
        return useNftBuilder(metaplex, operation.input, scope).sendAndConfirm(metaplex, scope.confirmOptions);
    }),
};
/**
 * Utilizes a usable NFT.
 *
 * ```ts
 * const transactionBuilder = metaplex
 *   .nfts()
 *   .builders()
 *   .use({ mintAddress });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const useNftBuilder = (metaplex, params, options = {}) => {
    var _a, _b;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { mintAddress, numberOfUses = 1, owner = metaplex.identity(), useAuthority, } = params;
    // Programs.
    const tokenMetadataProgram = metaplex.programs().getTokenMetadata(programs);
    if (!isSigner(owner) && !useAuthority) {
        throw new ExpectedSignerError('owner', 'PublicKey', {
            problemSuffix: 'In order to use an NFT you must either provide the owner as a Signer ' +
                'or a delegated use authority as a Signer.',
        });
    }
    // PDAs.
    const metadata = metaplex.nfts().pdas().metadata({
        mint: mintAddress,
        programs,
    });
    const tokenAccount = (_a = params.ownerTokenAccount) !== null && _a !== void 0 ? _a : metaplex
        .tokens()
        .pdas()
        .associatedTokenAccount({
        mint: mintAddress,
        owner: toPublicKey(owner),
        programs,
    });
    const useAuthorityRecord = useAuthority
        ? metaplex.nfts().pdas().useAuthorityRecord({
            mint: mintAddress,
            useAuthority: useAuthority.publicKey,
            programs,
        })
        : undefined;
    const programAsBurner = metaplex.nfts().pdas().burner({ programs });
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        // Update the metadata account.
        .add({
        instruction: createUtilizeInstruction({
            metadata,
            tokenAccount,
            useAuthority: useAuthority
                ? useAuthority.publicKey
                : toPublicKey(owner),
            mint: mintAddress,
            owner: toPublicKey(owner),
            useAuthorityRecord,
            burner: useAuthorityRecord ? programAsBurner : undefined,
        }, { utilizeArgs: { numberOfUses } }, tokenMetadataProgram.address),
        signers: [owner, useAuthority].filter(isSigner),
        key: (_b = params.instructionKey) !== null && _b !== void 0 ? _b : 'utilizeNft',
    }));
};
//# sourceMappingURL=useNft.js.map