'use strict';

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

var splToken = require('@solarti/spl-token');
var Operation = require('../../../types/Operation.cjs');
var PublicKey = require('../../../types/PublicKey.cjs');
var Signer = require('../../../types/Signer.cjs');
var TransactionBuilder = require('../../../utils/TransactionBuilder.cjs');

// -----------------
// 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
 */
const sendTokensOperation = Operation.useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const sendTokensOperationHandler = {
  async handle(operation, metaplex, scope) {
    const {
      mintAddress,
      toOwner = metaplex.identity().publicKey,
      toToken
    } = operation.input;
    const destination = toToken ?? metaplex.tokens().pdas().associatedTokenAccount({
      mint: mintAddress,
      owner: toOwner,
      programs: scope.programs
    });
    const destinationAddress = PublicKey.toPublicKey(destination);
    const destinationAccountExists = await metaplex.rpc().accountExists(destinationAddress);
    scope.throwIfCanceled();
    const builder = await sendTokensBuilder(metaplex, {
      ...operation.input,
      toTokenExists: destinationAccountExists
    }, scope);
    scope.throwIfCanceled();
    return builder.sendAndConfirm(metaplex, scope.confirmOptions);
  }
};

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

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

/**
 * 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
 */
const sendTokensBuilder = async (metaplex, params, options = {}) => {
  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] = Signer.isSigner(fromOwner) ? [fromOwner.publicKey, [fromOwner]] : [fromOwner, [delegateAuthority, ...fromMultiSigners].filter(Signer.isSigner)];
  const tokenProgram = metaplex.programs().getToken(programs);
  const source = fromToken ?? metaplex.tokens().pdas().associatedTokenAccount({
    mint: mintAddress,
    owner: fromOwnerPublicKey,
    programs
  });
  const destination = toToken ?? metaplex.tokens().pdas().associatedTokenAccount({
    mint: mintAddress,
    owner: toOwner,
    programs
  });
  return TransactionBuilder.TransactionBuilder.make().setFeePayer(payer)

  // Create token account if missing.
  .add(await metaplex.tokens().builders().createTokenIfMissing({
    ...params,
    mint: mintAddress,
    owner: toOwner,
    token: toToken,
    tokenExists: toTokenExists,
    tokenVariable: 'toToken'
  }, {
    programs,
    payer
  }))

  // Transfer tokens.
  .add({
    instruction: splToken.createTransferInstruction(source, PublicKey.toPublicKey(destination), delegateAuthority ? delegateAuthority.publicKey : fromOwnerPublicKey, amount.basisPoints.toNumber(), fromMultiSigners, tokenProgram.address),
    signers,
    key: params.transferTokensInstructionKey ?? 'transferTokens'
  });
};

exports.sendTokensBuilder = sendTokensBuilder;
exports.sendTokensOperation = sendTokensOperation;
exports.sendTokensOperationHandler = sendTokensOperationHandler;
//# sourceMappingURL=sendTokens.cjs.map
