> ## Documentation Index
> Fetch the complete documentation index at: https://luminouslabs-cc5545c6-swen-add-code-runner.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Close Compressed Accounts

> Guide to close compressed accounts in Solana programs with full code examples.

Compressed accounts are closed via CPI to the Light System Program.

Closing a compressed account

* consumes the existing account hash, and
* produces a new account hash with zero values to mark it as closed.
* A closed compressed account [can be reinitialized](/compressed-pdas/guides/how-to-reinitialize-compressed-accounts).

<Note>
  Find [full code examples at the end](/compressed-pdas/guides/how-to-close-compressed-accounts#full-code-example) for Anchor and native Rust.
</Note>

# Implementation Guide

This guide will cover the components of a Solana program that closes compressed accounts.
Here is the complete flow to close compressed accounts:

<div className="hidden dark:block">
  <Frame>
    <img src="https://mintcdn.com/luminouslabs-cc5545c6-swen-add-code-runner/kjqHHw14Q8G9AGL6/images/program-closes.png?fit=max&auto=format&n=kjqHHw14Q8G9AGL6&q=85&s=775d523fb90b9fa75fe15f46cb734b30" alt="" width="1146" height="639" data-path="images/program-closes.png" />
  </Frame>
</div>

<div className="block dark:hidden">
  <Frame>
    <img src="https://mintcdn.com/luminouslabs-cc5545c6-swen-add-code-runner/kjqHHw14Q8G9AGL6/images/program-close.png?fit=max&auto=format&n=kjqHHw14Q8G9AGL6&q=85&s=6ff5b8162beb2fae40551bcde9b53a55" alt="" width="1146" height="639" data-path="images/program-close.png" />
  </Frame>
</div>

<Steps>
  <Step>
    ### Program Setup

    <Accordion title="Dependencies, Constants, Compressed Account">
      **Dependencies**

      Add dependencies to your program.

      <CodeGroup>
        ```toml Anchor theme={null}
        [dependencies]
        light-sdk = "0.16.0"
        anchor_lang = "0.31.1"
        ```

        ```toml Native Rust theme={null}
        [dependencies]
        light-sdk = "0.16.0"
        borsh = "0.10.0"
        solana-program = "2.2"
        ```
      </CodeGroup>

      * The `light-sdk` provides macros, wrappers and CPI interface to create and interact with compressed accounts.
      * Add the serialization library (`borsh` for native Rust, or use `AnchorSerialize`).

      **Constants**

      Set program address and derive the CPI authority PDA to call the Light System program.

      ```rust theme={null}
      declare_id!("rent4o4eAiMbxpkAM1HeXzks9YeGuz18SEgXEizVvPq");

      pub const LIGHT_CPI_SIGNER: CpiSigner =
          derive_light_cpi_signer!("rent4o4eAiMbxpkAM1HeXzks9YeGuz18SEgXEizVvPq");
      ```

      **`CPISigner`** is the configuration struct for CPI's to the Light System Program.

      * CPIs to the Light System program must be signed with a PDA derived by your program with the seed `b"authority"`
      * `derive_light_cpi_signer!` derives the CPI signer PDA for you at compile time.

      **Compressed Account**

      Define your compressed account struct.

      <CodeGroup>
        ```rust Anchor theme={null}
        #[event] // declared as event so that it is part of the idl.
        #[derive(
            Clone,
            Debug,
            Default,
            LightDiscriminator
        )]
        pub struct MyCompressedAccount {
            pub owner: Pubkey,
            pub message: String,
        }
        ```

        ```rust Native Rust theme={null}
        #[derive(
            Debug,
            Default,
            Clone,
            BorshSerialize,
            BorshDeserialize,
            LightDiscriminator,
        )]
        pub struct MyCompressedAccount {
            pub owner: Pubkey,
            pub message: String,
        }
        ```
      </CodeGroup>

      You derive

      * the standard traits (`Clone`, `Debug`, `Default`),
      * `borsh` or `AnchorSerialize` to serialize account data, and
      * `LightDiscriminator` to implements a unique type ID (8 bytes) to distinguish account types. The default compressed account layout enforces a discriminator in its *own field*, <Tooltip tip="The Anchor framework reserves the first 8 bytes of a *regular account's data field* for the discriminator." cta="Anchor" href="https://www.anchor-lang.com/">not the first 8 bytes of the data field</Tooltip>.

      <Info>
        The traits listed above are required for `LightAccount`. `LightAccount` wraps `MyCompressedAccount` in Step 3 to set the discriminator and create the compressed account's data.
      </Info>
    </Accordion>
  </Step>

  <Step>
    ### Instruction Data

    Define the instruction data with the following parameters:

    <Tabs>
      <Tab title="Anchor">
        ```rust theme={null}
        pub fn close_account<'info>(
            ctx: Context<'_, '_, '_, 'info, GenericAnchorAccounts<'info>>,
            proof: ValidityProof,
            account_meta: CompressedAccountMeta,
            current_message: String,
        ) -> Result<()>
        ```
      </Tab>

      <Tab title="Native Rust">
        ```rust theme={null}
        pub struct CloseInstructionData {
            pub proof: ValidityProof,
            pub account_meta: CompressedAccountMeta,
            pub current_message: String,
        }
        ```
      </Tab>
    </Tabs>

    1. **Validity Proof**

    * Define `proof` to include the proof that the account exists in the state tree.
    * Clients fetch a validity proof with `getValidityProof()` from an RPC provider that supports ZK Compression (Helius, Triton, ...).

    2. **Specify input state and output state tree (stores closed account hash)**

    * Define `account_meta: CompressedAccountMeta` to reference the existing account and specify the state tree to store the new hash with zero values:
      * `tree_info: PackedStateTreeInfo`: References the existing account hash in the state tree.
      * `address`: The account's derived address.
      * `output_state_tree_index` points to the state tree that will store the updated hash with a zero-byte hash to mark the account as closed.

    <Info>
      Clients fetch the current account with `getCompressedAccount()` and populate `CompressedAccountMeta` with the account's metadata.
    </Info>

    3. **Current data**

    * Define fields to include the current account data passed by the client.
    * This depends on your program logic. This example includes the `current_message` field.
  </Step>

  <Step>
    ### Close Compressed Account

    Load the compressed account and mark it as closed with `LightAccount::new_close()`.

    <Note>
      `new_close()`

      1. hashes the current account data as input state and
      2. marks the account for closure for the Light System Program.
    </Note>

    <Tabs>
      <Tab title="Anchor">
        ```rust theme={null}
        let my_compressed_account = LightAccount::<MyCompressedAccount>::new_close(
            &crate::ID,
            &account_meta,
            MyCompressedAccount {
                owner: ctx.accounts.signer.key(),
                message: current_message,
            },
        )?;
        ```
      </Tab>

      <Tab title="Native Rust">
        ```rust theme={null}
        let my_compressed_account = LightAccount::<MyCompressedAccount>::new_close(
            &ID,
            &instruction_data.account_meta,
            MyCompressedAccount {
                owner: *signer.key,
                message: instruction_data.current_message,
            },
        )?;
        ```
      </Tab>
    </Tabs>

    **Pass these parameters to `new_close()`:**

    * `&program_id`: The program's ID that owns the compressed account.
    * `&account_meta`: The `CompressedAccountMeta` from instruction data (*Step 2*) that identifies the existing account and specifies the output state tree.
    * Current account data: The existing account data. The SDK hashes this input state for verification by the Light System Program.
      * Anchor: Construct `MyCompressedAccount` with `ctx.accounts.signer.key()` and `current_message`
      * Native: Construct `MyCompressedAccount` with data from `instruction_data`

    **The SDK creates:**

    * A `LightAccount` wrapper similar to Anchor's `Account` that marks the account for closure.

    <Info>
      `new_close()` hashes the input state and marks the account for closure. The Light System Program creates output state with zero values:

      * a zero discriminator (`0u8; 8`) removes type identification of the account,
      * the output contains zeroes as data hash that indicates no data content, and
      * the data field contains an empty vector, instead of serialized account fields.
    </Info>
  </Step>

  <Step>
    ### Light System Program CPI

    Invoke the Light System Program to close the compressed account. This empty account can be reinitialized with `LightAccount::new_empty()`.

    <Note>
      The Light System Program

      * validates the account exists in state tree,
      * nullifies the existing account hash, and
      * appends the new account hash with zero values to the state tree to mark it as closed.
    </Note>

    <Tabs>
      <Tab title="Anchor">
        ```rust theme={null}
        let light_cpi_accounts = CpiAccounts::new(
            ctx.accounts.signer.as_ref(),
            ctx.remaining_accounts,
            crate::LIGHT_CPI_SIGNER,
        );

        LightSystemProgramCpi::new_cpi(LIGHT_CPI_SIGNER, proof)
            .with_light_account(my_compressed_account)?
            .invoke(light_cpi_accounts)?;
        ```

        **Set up `CpiAccounts::new()`:**

        `CpiAccounts::new()` parses accounts for the CPI call to Light System Program.

        **Pass these parameters:**

        * `ctx.accounts.signer.as_ref()`: the transaction signer
        * `ctx.remaining_accounts`: Slice with `[system_accounts, ...packed_tree_accounts]`. The client builds this with `PackedAccounts` and passes it to the instruction.
        * `&LIGHT_CPI_SIGNER`: Your program's CPI signer PDA defined in Constants.
      </Tab>

      <Tab title="Native Rust">
        ```rust theme={null}
        let (signer, remaining_accounts) = accounts
            .split_first();

        let cpi_accounts = CpiAccounts::new(
            signer,
            remaining_accounts,
            LIGHT_CPI_SIGNER
        );

        LightSystemProgramCpi::new_cpi(LIGHT_CPI_SIGNER, instruction_data.proof)
            .with_light_account(my_compressed_account)?
            .invoke(cpi_accounts)?;
        ```

        **Set up `CpiAccounts::new()`:**

        `CpiAccounts::new()` parses accounts for the CPI call to Light System Program.

        **Pass these parameters:**

        * `signer`: account that signs and pays for the transaction
        * `remaining_accounts`: Slice with `[system_accounts, ...packed_tree_accounts]`. The client builds this with `PackedAccounts`.
          * `split_first()` extracts the fee payer from the accounts array to separate it from the Light System Program accounts needed for the CPI.
        * `&LIGHT_CPI_SIGNER`: Your program's CPI signer PDA defined in Constants.
      </Tab>
    </Tabs>

    <Accordion title="System Accounts List">
      <table>
        <colgroup>
          <col style={{width: '5%'}} />

          <col style={{width: '30%', textAlign: 'left'}} />

          <col style={{width: '65%'}} />
        </colgroup>

        <thead>
          <tr>
            <th style={{textAlign: 'left'}} />

            <th style={{textAlign: 'left'}} />

            <th style={{textAlign: 'left'}} />
          </tr>
        </thead>

        <tbody>
          <tr>
            <td>1</td>
            <td style={{textAlign: 'left'}}><strong><Tooltip tip="SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7" cta="Program ID" href="https://solscan.io/account/SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7">Light System Program</Tooltip></strong></td>
            <td>Verifies validity proofs, compressed account ownership checks, and CPIs the Account Compression Program to update tree accounts.</td>
          </tr>

          <tr>
            <td>2</td>
            <td style={{textAlign: 'left'}}><strong>CPI Signer</strong></td>

            <td>
              * PDA to sign CPI calls from your program to the Light System Program.<br />
              * Verified by the Light System Program during CPI.<br />
              * Derived from your program ID.
            </td>
          </tr>

          <tr>
            <td>3</td>
            <td style={{textAlign: 'left'}}><strong>Registered Program PDA</strong></td>
            <td>Provides access control to the Account Compression Program.</td>
          </tr>

          <tr>
            <td>4</td>
            <td style={{textAlign: 'left'}}><strong><Tooltip tip="PDA derived from Light System Program ID with seed b 'cpi_authority'.HZH7qSLcpAeDqCopVU4e5XkhT9j3JFsQiq8CmruY3aru" cta="Program ID" href="https://solscan.io/account/HZH7qSLcpAeDqCopVU4e5XkhT9j3JFsQiq8CmruY3aru">Account Compression Authority</Tooltip></strong></td>
            <td>Signs CPI calls from the Light System Program to the Account Compression Program.</td>
          </tr>

          <tr>
            <td>5</td>
            <td style={{textAlign: 'left'}}><strong><Tooltip tip="compr6CUsB5m2jS4Y3831ztGSTnDpnKJTKS95d64XVq" cta="Program ID" href="https://solscan.io/account/compr6CUsB5m2jS4Y3831ztGSTnDpnKJTKS95d64XVq">Account Compression Program</Tooltip></strong></td>

            <td>
              * Writes to state and address tree accounts.<br />
              * Clients and the Account Compression Program do not interact directly — handled internally.
            </td>
          </tr>

          <tr>
            <td>6</td>
            <td style={{textAlign: 'left'}}><strong><Tooltip tip="11111111111111111111111111111111" cta="Program ID" href="https://solscan.io/account/11111111111111111111111111111111">System Program</Tooltip></strong></td>
            <td>Solana System Program used to transfer lamports.</td>
          </tr>
        </tbody>
      </table>
    </Accordion>

    **Build the CPI instruction**:

    * `new_cpi()` initializes the CPI instruction with the `proof` to prove the compressed account exists in the state tree *- defined in the Instruction Data (Step 2).*
    * `with_light_account` adds the `LightAccount` wrapper configured to close the account with the zero values *- defined in Step 3*.
    * `invoke()` calls the Light System Program with `CpiAccounts`.
  </Step>
</Steps>

# Full Code Example

The example programs below implement all steps from this guide.
Make sure you have your developer environment set up first.

<Accordion title="Setup">
  **Install Solana CLI:**

  ```bash theme={null}
  sh -c "$(curl -sSfL https://release.solana.com/v2.2.15/install)"
  ```

  **Install Anchor CLI:**

  ```bash theme={null}
  cargo install --git https://github.com/coral-xyz/anchor avm --force
  avm install latest
  avm use latest
  ```

  **Install the Light CLI:**

  <Tabs>
    <Tab title="npm">
      ```bash theme={null}
      npm install -g @lightprotocol/zk-compression-cli@alpha
      ```
    </Tab>

    <Tab title="yarn">
      ```bash theme={null}
      yarn global add @lightprotocol/zk-compression-cli@alpha
      ```
    </Tab>

    <Tab title="pnpm">
      ```bash theme={null}
      pnpm add -g @lightprotocol/zk-compression-cli@alpha
      ```
    </Tab>
  </Tabs>

  **Verify installation:**

  ```bash theme={null}
  light --version
  ```
</Accordion>

<Tabs>
  <Tab title="Anchor">
    <Info>
      Find the source code for this example [here](https://github.com/Lightprotocol/program-examples/blob/3a9ff76d0b8b9778be0e14aaee35e041cabfb8b2/counter/anchor/programs/counter/src/lib.rs#L167).
    </Info>

    ```rust expandable theme={null}
    #![allow(unexpected_cfgs)]
    #![allow(deprecated)]

    use anchor_lang::{prelude::*, AnchorDeserialize, AnchorSerialize};
    use light_sdk::{
        account::LightAccount,
        address::v1::derive_address,
        cpi::{v1::CpiAccounts, CpiSigner},
        derive_light_cpi_signer,
        instruction::{account_meta::CompressedAccountMeta, PackedAddressTreeInfo, ValidityProof},
        LightDiscriminator,
    };

    declare_id!("DzQ3za3DVCpXkXhmZVSrNchwbbSsJXmi9MBc8v5tvZuQ");

    pub const LIGHT_CPI_SIGNER: CpiSigner =
        derive_light_cpi_signer!("DzQ3za3DVCpXkXhmZVSrNchwbbSsJXmi9MBc8v5tvZuQ");

    #[program]
    pub mod close {

        use super::*;
        use light_sdk::cpi::{
            v1::LightSystemProgramCpi, InvokeLightSystemProgram, LightCpiInstruction,
        };

        /// Setup: Create a compressed account
        pub fn create_account<'info>(
            ctx: Context<'_, '_, '_, 'info, GenericAnchorAccounts<'info>>,
            proof: ValidityProof,
            address_tree_info: PackedAddressTreeInfo,
            output_state_tree_index: u8,
            message: String,
        ) -> Result<()> {
            let light_cpi_accounts = CpiAccounts::new(
                ctx.accounts.signer.as_ref(),
                ctx.remaining_accounts,
                crate::LIGHT_CPI_SIGNER,
            );

            let (address, address_seed) = derive_address(
                &[b"message", ctx.accounts.signer.key().as_ref()],
                &address_tree_info
                    .get_tree_pubkey(&light_cpi_accounts)
                    .map_err(|_| ErrorCode::AccountNotEnoughKeys)?,
                &crate::ID,
            );

            let mut my_compressed_account = LightAccount::<MyCompressedAccount>::new_init(
                &crate::ID,
                Some(address),
                output_state_tree_index,
            );

            my_compressed_account.owner = ctx.accounts.signer.key();
            my_compressed_account.message = message.clone();

            msg!(
                "Created compressed account with message: {}",
                my_compressed_account.message
            );

            LightSystemProgramCpi::new_cpi(LIGHT_CPI_SIGNER, proof)
                .with_light_account(my_compressed_account)?
                .with_new_addresses(&[address_tree_info.into_new_address_params_packed(address_seed)])
                .invoke(light_cpi_accounts)?;

            Ok(())
        }

        /// Close compressed account
        pub fn close_account<'info>(
            ctx: Context<'_, '_, '_, 'info, GenericAnchorAccounts<'info>>,
            proof: ValidityProof,
            account_meta: CompressedAccountMeta,
            current_message: String,
        ) -> Result<()> {
            let light_cpi_accounts = CpiAccounts::new(
                ctx.accounts.signer.as_ref(),
                ctx.remaining_accounts,
                crate::LIGHT_CPI_SIGNER,
            );

            let my_compressed_account = LightAccount::<MyCompressedAccount>::new_close(
                &crate::ID,
                &account_meta,
                MyCompressedAccount {
                    owner: ctx.accounts.signer.key(),
                    message: current_message,
                },
            )?;

            msg!("Close compressed account.");

            LightSystemProgramCpi::new_cpi(LIGHT_CPI_SIGNER, proof)
                .with_light_account(my_compressed_account)?
                .invoke(light_cpi_accounts)?;

            Ok(())
        }
    }

    #[derive(Accounts)]
    pub struct GenericAnchorAccounts<'info> {
        #[account(mut)]
        pub signer: Signer<'info>,
    }

    #[event]
    #[derive(Clone, Debug, Default, LightDiscriminator)]
    pub struct MyCompressedAccount {
        pub owner: Pubkey,
        pub message: String,
    }
    ```
  </Tab>

  <Tab title="Native Rust">
    <Info>
      Find the source code for this example [here](https://github.com/Lightprotocol/program-examples/blob/3a9ff76d0b8b9778be0e14aaee35e041cabfb8b2/counter/native/src/lib.rs#L277).
    </Info>

    ```rust expandable theme={null}
    #![allow(unexpected_cfgs)]

    #[cfg(any(test, feature = "test-helpers"))]
    pub mod test_helpers;

    use borsh::{BorshDeserialize, BorshSerialize};
    use light_macros::pubkey;
    use light_sdk::{
        account::sha::LightAccount,
        address::v1::derive_address,
        cpi::{
            v1::{CpiAccounts, LightSystemProgramCpi},
            CpiSigner, InvokeLightSystemProgram, LightCpiInstruction,
        },
        derive_light_cpi_signer,
        error::LightSdkError,
        instruction::{account_meta::CompressedAccountMeta, PackedAddressTreeInfo, ValidityProof},
        LightDiscriminator,
    };
    use solana_program::{
        account_info::AccountInfo, entrypoint, program_error::ProgramError, pubkey::Pubkey,
    };

    pub const ID: Pubkey = pubkey!("NLusgr6vsEjYDvF6nDxpdrhMUxUC19s4XoyshSrGFVN");
    pub const LIGHT_CPI_SIGNER: CpiSigner = derive_light_cpi_signer!("NLusgr6vsEjYDvF6nDxpdrhMUxUC19s4XoyshSrGFVN");

    #[cfg(not(feature = "no-entrypoint"))]
    entrypoint!(process_instruction);

    #[derive(Debug, BorshSerialize, BorshDeserialize)]
    pub enum InstructionType {
        Create,
        Close,
    }

    #[derive(Debug, BorshSerialize, BorshDeserialize)]
    pub struct CreateInstructionData {
        pub proof: ValidityProof,
        pub address_tree_info: PackedAddressTreeInfo,
        pub output_state_tree_index: u8,
        pub message: String,
    }

    #[derive(Debug, BorshSerialize, BorshDeserialize)]
    pub struct CloseInstructionData {
        pub proof: ValidityProof,
        pub account_meta: CompressedAccountMeta,
        pub current_message: String,
    }

    #[derive(Debug, Default, Clone, BorshSerialize, BorshDeserialize, LightDiscriminator)]
    pub struct MyCompressedAccount {
        pub owner: Pubkey,
        pub message: String,
    }

    pub fn process_instruction(
        _program_id: &Pubkey,
        accounts: &[AccountInfo],
        instruction_data: &[u8],
    ) -> Result<(), ProgramError> {
        let (instruction_type, rest) = instruction_data
            .split_first()
            .ok_or(ProgramError::InvalidInstructionData)?;

        match InstructionType::try_from_slice(&[*instruction_type])
            .map_err(|_| ProgramError::InvalidInstructionData)?
        {
            InstructionType::Create => create(accounts, rest)?,
            InstructionType::Close => close(accounts, rest)?,
        }

        Ok(())
    }

    fn create(accounts: &[AccountInfo], instruction_data: &[u8]) -> Result<(), LightSdkError> {
        let instruction_data =
            CreateInstructionData::try_from_slice(instruction_data).map_err(|_| LightSdkError::Borsh)?;

        let signer = accounts.first().ok_or(ProgramError::NotEnoughAccountKeys)?;

        let light_cpi_accounts = CpiAccounts::new(
            signer,
            &accounts[1..],
            LIGHT_CPI_SIGNER
        );

        let (address, address_seed) = derive_address(
            &[b"message", signer.key.as_ref()],
            &instruction_data
                .address_tree_info
                .get_tree_pubkey(&light_cpi_accounts)
                .map_err(|_| ProgramError::NotEnoughAccountKeys)?,
            &ID,
        );

        let new_address_params = instruction_data
            .address_tree_info
            .into_new_address_params_packed(address_seed);

        let mut my_compressed_account = LightAccount::<MyCompressedAccount>::new_init(
            &ID,
            Some(address),
            instruction_data.output_state_tree_index,
        );
        my_compressed_account.owner = *signer.key;
        my_compressed_account.message = instruction_data.message;

        LightSystemProgramCpi::new_cpi(LIGHT_CPI_SIGNER, instruction_data.proof)
            .with_light_account(my_compressed_account)?
            .with_new_addresses(&[new_address_params])
            .invoke(light_cpi_accounts)?;

        Ok(())
    }

    fn close(accounts: &[AccountInfo], instruction_data: &[u8]) -> Result<(), LightSdkError> {
        let instruction_data =
            CloseInstructionData::try_from_slice(instruction_data).map_err(|_| LightSdkError::Borsh)?;

        let (signer, remaining_accounts) = accounts
            .split_first()
            .ok_or(ProgramError::InvalidAccountData)?;

        let cpi_accounts = CpiAccounts::new(
            signer,
            remaining_accounts,
            LIGHT_CPI_SIGNER
        );

        let my_compressed_account = LightAccount::<MyCompressedAccount>::new_close(
            &ID,
            &instruction_data.account_meta,
            MyCompressedAccount {
                owner: *signer.key,
                message: instruction_data.current_message,
            },
        )?;

        LightSystemProgramCpi::new_cpi(LIGHT_CPI_SIGNER, instruction_data.proof)
            .with_light_account(my_compressed_account)?
            .invoke(cpi_accounts)?;

        Ok(())
    }
    ```
  </Tab>
</Tabs>

# Next Steps

<CardGroup>
  <Card title="Build a client for your program" icon="chevron-right" color="#0066ff" href="/client-library/client-guide" horizontal />

  <Card title="Learn how to reinitialize compressed accounts" icon="chevron-right" color="#0066ff" href="/compressed-pdas/guides/how-to-reinitialize-compressed-accounts" horizontal />
</CardGroup>
