'use strict';

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

var web3_js = require('@solarti/web3.js');
var Operation = require('../../../types/Operation.cjs');
var Amount = require('../../../types/Amount.cjs');
var TransactionBuilder = require('../../../utils/TransactionBuilder.cjs');

// -----------------
// Operation
// -----------------

const Key = 'CreateAccountOperation';

/**
 * Creates a new uninitialized Solana account.
 *
 * ```ts
 * const { newAccount } = await metaplex
 *   .system()
 *   .createAccount({ space: 100 }); // 100 bytes
 * ```
 *
 * @group Operations
 * @category Constructors
 */
const createAccountOperation = Operation.useOperation(Key);

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

/**
 * @group Operations
 * @category Handlers
 */
const createAccountOperationHandler = {
  async handle(operation, metaplex, scope) {
    const builder = await createAccountBuilder(metaplex, operation.input, scope);
    scope.throwIfCanceled();
    return builder.sendAndConfirm(metaplex, scope.confirmOptions);
  }
};

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

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

/**
 * Creates a new uninitialized Solana account.
 *
 * ```ts
 * const transactionBuilder = await metaplex
 *   .system()
 *   .builders()
 *   .createAccount({ space: 100 }); // 100 bytes
 * ```
 *
 * Note that accessing this transaction builder is asynchronous
 * because we may need to contact the cluster to get the
 * rent-exemption for the provided space.
 *
 * @group Transaction Builders
 * @category Constructors
 */
const createAccountBuilder = async (metaplex, params, options = {}) => {
  const {
    payer = metaplex.rpc().getDefaultFeePayer()
  } = options;
  const {
    space,
    newAccount = web3_js.Keypair.generate(),
    program = web3_js.SystemProgram.programId
  } = params;
  const lamports = params.lamports ?? (await metaplex.rpc().getRent(space));
  Amount.assertSol(lamports);
  return TransactionBuilder.TransactionBuilder.make().setFeePayer(payer).setContext({
    newAccount,
    lamports
  }).add({
    instruction: web3_js.SystemProgram.createAccount({
      fromPubkey: payer.publicKey,
      newAccountPubkey: newAccount.publicKey,
      space,
      lamports: lamports.basisPoints.toNumber(),
      programId: program
    }),
    signers: [payer, newAccount],
    key: params.instructionKey ?? 'createAccount'
  });
};

exports.createAccountBuilder = createAccountBuilder;
exports.createAccountOperation = createAccountOperation;
exports.createAccountOperationHandler = createAccountOperationHandler;
//# sourceMappingURL=createAccount.cjs.map
