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 { createTransferInstruction } from '@solarti/spl-token';
import { isSigner, toPublicKey, useOperation, } from '../../../types';
import { TransactionBuilder } from '../../../utils';
// -----------------
// Operation
// -----------------
const Key = 'SendTokensOperation';
/**
 * Send tokens from one account to another.
 *
 * ```ts
 * await metaplex
 *   .tokens()
 *   .send({
 *     mintAddress,
 *     toOwner,
 *     amount: token(100),
 *   };
 * ```
 *
 * @group Operations
 * @category Constructors
 */
export const sendTokensOperation = useOperation(Key);
/**
 * @group Operations
 * @category Handlers
 */
export const sendTokensOperationHandler = {
    handle(operation, metaplex, scope) {
        return __awaiter(this, void 0, void 0, function* () {
            const { mintAddress, toOwner = metaplex.identity().publicKey, toToken, } = operation.input;
            const destination = toToken !== null && toToken !== void 0 ? toToken : metaplex.tokens().pdas().associatedTokenAccount({
                mint: mintAddress,
                owner: toOwner,
                programs: scope.programs,
            });
            const destinationAddress = toPublicKey(destination);
            const destinationAccountExists = yield metaplex
                .rpc()
                .accountExists(destinationAddress);
            scope.throwIfCanceled();
            const builder = yield sendTokensBuilder(metaplex, Object.assign(Object.assign({}, operation.input), { toTokenExists: destinationAccountExists }), scope);
            scope.throwIfCanceled();
            return builder.sendAndConfirm(metaplex, scope.confirmOptions);
        });
    },
};
/**
 * Send tokens from one account to another.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .tokens()
 *   .builders()
 *   .send({
 *     mintAddress,
 *     toOwner,
 *     amount: token(100),
 *   });
 * ```
 *
 * @group Transaction Builders
 * @category Constructors
 */
export const sendTokensBuilder = (metaplex, params, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const { programs, payer = metaplex.rpc().getDefaultFeePayer() } = options;
    const { mintAddress, amount, toOwner = metaplex.identity().publicKey, toToken, toTokenExists = true, fromOwner = metaplex.identity(), fromToken, fromMultiSigners = [], delegateAuthority, } = params;
    const [fromOwnerPublicKey, signers] = isSigner(fromOwner)
        ? [fromOwner.publicKey, [fromOwner]]
        : [fromOwner, [delegateAuthority, ...fromMultiSigners].filter(isSigner)];
    const tokenProgram = metaplex.programs().getToken(programs);
    const source = fromToken !== null && fromToken !== void 0 ? fromToken : metaplex.tokens().pdas().associatedTokenAccount({
        mint: mintAddress,
        owner: fromOwnerPublicKey,
        programs,
    });
    const destination = toToken !== null && toToken !== void 0 ? toToken : metaplex.tokens().pdas().associatedTokenAccount({
        mint: mintAddress,
        owner: toOwner,
        programs,
    });
    return (TransactionBuilder.make()
        .setFeePayer(payer)
        // Create token account if missing.
        .add(yield metaplex
        .tokens()
        .builders()
        .createTokenIfMissing(Object.assign(Object.assign({}, params), { mint: mintAddress, owner: toOwner, token: toToken, tokenExists: toTokenExists, tokenVariable: 'toToken' }), { programs, payer }))
        // Transfer tokens.
        .add({
        instruction: createTransferInstruction(source, toPublicKey(destination), delegateAuthority ? delegateAuthority.publicKey : fromOwnerPublicKey, amount.basisPoints.toNumber(), fromMultiSigners, tokenProgram.address),
        signers,
        key: (_a = params.transferTokensInstructionKey) !== null && _a !== void 0 ? _a : 'transferTokens',
    }));
});
//# sourceMappingURL=sendTokens.js.map