import { Keypair, SystemProgram } from '@solarti/web3.js';
import { useOperation } from '../../../types/Operation.mjs';
import { assertSol } from '../../../types/Amount.mjs';
import { TransactionBuilder } from '../../../utils/TransactionBuilder.mjs';

// -----------------
// 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 = 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 = Keypair.generate(),
    program = SystemProgram.programId
  } = params;
  const lamports = params.lamports ?? (await metaplex.rpc().getRent(space));
  assertSol(lamports);
  return TransactionBuilder.make().setFeePayer(payer).setContext({
    newAccount,
    lamports
  }).add({
    instruction: SystemProgram.createAccount({
      fromPubkey: payer.publicKey,
      newAccountPubkey: newAccount.publicKey,
      space,
      lamports: lamports.basisPoints.toNumber(),
      programId: program
    }),
    signers: [payer, newAccount],
    key: params.instructionKey ?? 'createAccount'
  });
};

export { createAccountBuilder, createAccountOperation, createAccountOperationHandler };
//# sourceMappingURL=createAccount.mjs.map
