> ## Documentation Index
> Fetch the complete documentation index at: https://www.zkcompression.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Associated Light Token Accounts

> Client and program guide to create associated Light Token accounts. Includes step-by-step implementation and full code examples.

export const lightCreateAtaCpiCode = ["use light_token::instruction::CreateAssociatedAccountCpi;", "", "CreateAssociatedAccountCpi {", "    payer: payer.clone(),", "    owner: owner.clone(),", "    mint: mint.clone(),", "    ata: associated_token_account.clone(),", "    bump,", "}", ".rent_free(", "    compressible_config.clone(),", "    rent_sponsor.clone(),", "    system_program.clone(),", ")", ".invoke()?"].join("\n");

export const splCreateAtaCpiCode = ["use spl_associated_token_account::instruction::create_associated_token_account;", "", "let ix = create_associated_token_account(", "    &payer.pubkey(),", "    &owner.pubkey(),", "    &mint,", "    &spl_token::id(),", ");", "", "invoke(&ix, &[payer, owner, mint])?;"].join("\n");

export const lightCreateAtaMacroCode = ["#[light_account(", "    init,", "    associated_token::authority = ata_owner,", "    associated_token::mint = ata_mint,", "    associated_token::bump = params.ata_bump", ")]", "pub ata: UncheckedAccount<'info>,"].join("\n");

export const splCreateAtaMacroCode = ["#[account(", "    init,", "    payer = fee_payer,", "    associated_token::mint = mint,", "    associated_token::authority = owner,", ")]", "pub ata: Account<'info, TokenAccount>,"].join("\n");

export const lightCreateAtaRustCode = ["use light_token::instruction::CreateAssociatedTokenAccount;", "", "let ix = CreateAssociatedTokenAccount::new(", "    payer.pubkey(),", "    owner.pubkey(),", "    mint,", ")", ".instruction()?;"].join("\n");

export const splCreateAtaRustCode = ["use spl_associated_token_account::instruction::create_associated_token_account;", "", "let ix = create_associated_token_account(", "    &payer.pubkey(),", "    &owner.pubkey(),", "    &mint,", "    &spl_token::id(),", ");"].join("\n");

export const lightCreateAtaCode = ['import { getOrCreateAtaInterface } from "@lightprotocol/compressed-token/unified";', "", "const ata = await getOrCreateAtaInterface(", "  rpc,", "  payer,", "  mint,", "  owner", ");"].join("\n");

export const splCreateAtaCode = ['import { getOrCreateAssociatedTokenAccount } from "@solana/spl-token";', "", "const ata = await getOrCreateAssociatedTokenAccount(", "  connection,", "  payer,", "  mint,", "  owner", ");"].join("\n");

export const CodeCompare = ({firstCode = "", secondCode = "", firstLabel = "Light Token", secondLabel = "SPL", language = "javascript"}) => {
  const [sliderPercent, setSliderPercent] = useState(100);
  const [isDragging, setIsDragging] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [copied, setCopied] = useState(false);
  const containerRef = useRef(null);
  const animationRef = useRef(null);
  const firstPreRef = useRef(null);
  const secondPreRef = useRef(null);
  const [containerHeight, setContainerHeight] = useState(null);
  const showingFirst = sliderPercent > 50;
  const handleCopy = async () => {
    const codeToCopy = showingFirst ? firstCode : secondCode;
    await navigator.clipboard.writeText(codeToCopy);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  const highlightCode = code => {
    let escaped = code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    if (language === "rust") {
      const rustPattern = /(\/\/.*$)|(["'])(?:(?!\2)[^\\]|\\.)*?\2|\b(use|let|mut|pub|fn|struct|impl|enum|mod|const|static|trait|type|where|for|in|if|else|match|loop|while|return|self|Self|true|false|Some|None|Ok|Err|Result|Option|vec!)\b|::([a-zA-Z_][a-zA-Z0-9_]*)|&amp;([a-zA-Z_][a-zA-Z0-9_]*)|\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?=\()|(\?)/gm;
      return escaped.replace(rustPattern, (match, comment, stringQuote, keyword, pathSegment, reference, func, questionMark) => {
        if (comment) return `<span style="color:#6b7280;font-style:italic">${match}</span>`;
        if (stringQuote) return `<span style="color:#059669">${match}</span>`;
        if (keyword) return `<span style="color:#db2777">${match}</span>`;
        if (pathSegment) return `::<span style="color:#0891b2">${pathSegment}</span>`;
        if (reference) return `&amp;<span style="color:#6366f1">${reference}</span>`;
        if (func) return `<span style="color:#2563eb">${match}</span>`;
        if (questionMark) return `<span style="color:#db2777">?</span>`;
        return match;
      });
    }
    const pattern = /(\/\/.*$)|(["'`])(?:(?!\2)[^\\]|\\.)*?\2|\b(const|let|var|await|async|import|from|export|return|if|else|function|class|new|throw|try|catch)\b|\.([a-zA-Z_][a-zA-Z0-9_]*)\b|\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?=\()/gm;
    return escaped.replace(pattern, (match, comment, stringQuote, keyword, property, func) => {
      if (comment) return `<span style="color:#6b7280;font-style:italic">${match}</span>`;
      if (stringQuote) return `<span style="color:#059669">${match}</span>`;
      if (keyword) return `<span style="color:#db2777">${match}</span>`;
      if (property) return `.<span style="color:#0891b2">${property}</span>`;
      if (func) return `<span style="color:#2563eb">${match}</span>`;
      return match;
    });
  };
  const animateTo = target => {
    if (animationRef.current) cancelAnimationFrame(animationRef.current);
    setIsAnimating(true);
    const start = sliderPercent;
    const startTime = performance.now();
    const duration = 400;
    const animate = currentTime => {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      const current = start + (target - start) * eased;
      setSliderPercent(current);
      if (progress < 1) {
        animationRef.current = requestAnimationFrame(animate);
      } else {
        setSliderPercent(target);
        setIsAnimating(false);
        animationRef.current = null;
      }
    };
    animationRef.current = requestAnimationFrame(animate);
  };
  const handleToggle = () => {
    animateTo(showingFirst ? 0 : 100);
  };
  const handleMouseDown = e => {
    if (isAnimating) {
      cancelAnimationFrame(animationRef.current);
      setIsAnimating(false);
    }
    e.preventDefault();
    setIsDragging(true);
  };
  const handleMouseUp = () => {
    setIsDragging(false);
  };
  const handleMouseMove = e => {
    if (!isDragging || !containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const percent = Math.max(0, Math.min(100, x / rect.width * 100));
    setSliderPercent(percent);
  };
  const handleTouchMove = e => {
    if (!containerRef.current) return;
    if (isAnimating) {
      cancelAnimationFrame(animationRef.current);
      setIsAnimating(false);
    }
    const rect = containerRef.current.getBoundingClientRect();
    const x = e.touches[0].clientX - rect.left;
    const percent = Math.max(0, Math.min(100, x / rect.width * 100));
    setSliderPercent(percent);
  };
  const handleKeyDown = e => {
    if (e.key === "ArrowLeft") {
      setSliderPercent(p => Math.max(0, p - 5));
    } else if (e.key === "ArrowRight") {
      setSliderPercent(p => Math.min(100, p + 5));
    }
  };
  useEffect(() => {
    if (isDragging) {
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
      return () => {
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };
    }
  }, [isDragging]);
  useEffect(() => {
    return () => {
      if (animationRef.current) cancelAnimationFrame(animationRef.current);
    };
  }, []);
  useEffect(() => {
    const activeRef = showingFirst ? firstPreRef : secondPreRef;
    if (activeRef.current) {
      setContainerHeight(activeRef.current.scrollHeight);
    }
  }, [showingFirst]);
  return <>
      <div className="rounded-3xl not-prose mt-4 backdrop-blur-xl border overflow-hidden border-zinc-300 dark:border-zinc-700" style={{
    fontFamily: "Inter, sans-serif"
  }}>
        {}
        <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-200 dark:border-zinc-700 bg-gray-50 dark:bg-zinc-900">
          <span className="text-sm font-medium text-zinc-600 dark:text-zinc-300">
            {showingFirst ? firstLabel : secondLabel}
          </span>

          <div className="flex items-center gap-3">
            {}
            <button onClick={handleCopy} className="p-1.5 rounded hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors text-zinc-500 dark:text-zinc-400" title="Copy code" style={{
    background: "transparent",
    border: "none",
    cursor: "pointer"
  }}>
              {copied ? <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#22c55e" strokeWidth="2">
                  <path d="M20 6L9 17l-5-5" />
                </svg> : <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                  <path d="M14.25 5.25H7.25C6.14543 5.25 5.25 6.14543 5.25 7.25V14.25C5.25 15.3546 6.14543 16.25 7.25 16.25H14.25C15.3546 16.25 16.25 15.3546 16.25 14.25V7.25C16.25 6.14543 15.3546 5.25 14.25 5.25Z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M2.80103 11.998L1.77203 5.07397C1.61003 3.98097 2.36403 2.96397 3.45603 2.80197L10.38 1.77297C11.313 1.63397 12.19 2.16297 12.528 3.00097" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>}
            </button>

            {}
            <div onClick={handleToggle} className="bg-zinc-200 dark:bg-zinc-600" style={{
    position: "relative",
    width: "56px",
    height: "28px",
    borderRadius: "14px",
    boxShadow: "inset -2px -2px 4px rgba(255,255,255,0.3), inset 2px 2px 4px rgba(0,0,0,0.1)",
    cursor: "pointer",
    transition: "all 0.3s ease"
  }}>
              {}
              <div className="bg-white dark:bg-zinc-300" style={{
    position: "absolute",
    width: "24px",
    height: "24px",
    borderRadius: "12px",
    top: "2px",
    left: showingFirst ? "30px" : "2px",
    boxShadow: "0 2px 4px rgba(0,0,0,0.2)",
    transition: "all 0.3s ease-in-out",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
  }}>
                {}
                <div style={{
    width: "6px",
    height: "6px",
    background: showingFirst ? "#0066ff" : "#999",
    borderRadius: "50%",
    boxShadow: showingFirst ? "0 0 5px 1px rgba(0, 102, 255, 0.6)" : "0 0 4px 1px rgba(0, 0, 0, 0.1)",
    transition: "all 0.3s ease-in-out"
  }} />
              </div>
            </div>
          </div>
        </div>

        {}
        <div ref={containerRef} className="p-0" style={{
    cursor: isDragging ? "grabbing" : "default"
  }} onTouchMove={handleTouchMove} tabIndex={0} onKeyDown={handleKeyDown} role="slider" aria-valuenow={sliderPercent} aria-valuemin={0} aria-valuemax={100} aria-label="Code comparison slider">
          <div className="relative" style={{
    minHeight: "140px",
    overflow: "hidden",
    height: containerHeight ? `${containerHeight}px` : "auto",
    transition: "height 0.3s ease"
  }}>
            <div style={{
    position: "relative"
  }}>
              {}
              <pre ref={secondPreRef} className="m-0 p-4 text-zinc-700 dark:text-white/80 bg-transparent" style={{
    position: showingFirst ? "absolute" : "relative",
    top: 0,
    left: 0,
    right: 0,
    fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
    fontSize: "13px",
    lineHeight: "1.6",
    whiteSpace: "pre",
    zIndex: 1
  }} dangerouslySetInnerHTML={{
    __html: highlightCode(secondCode)
  }} />

              {}
              <pre ref={firstPreRef} className="m-0 p-4 text-zinc-700 dark:text-white/80 bg-white dark:bg-zinc-900" style={{
    position: showingFirst ? "relative" : "absolute",
    top: 0,
    left: 0,
    right: 0,
    fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
    fontSize: "13px",
    lineHeight: "1.6",
    whiteSpace: "pre",
    zIndex: 2,
    clipPath: `inset(0 ${100 - sliderPercent}% 0 0)`
  }} dangerouslySetInnerHTML={{
    __html: highlightCode(firstCode)
  }} />
            </div>

            {}
            <div className="absolute top-0 bottom-0 flex items-center justify-center pointer-events-none" style={{
    left: `${sliderPercent}%`,
    transform: "translateX(-50%)",
    zIndex: 30
  }}>
              <div className="absolute top-0 bottom-0 w-px bg-zinc-400 dark:bg-white/30" />

              <div className="absolute top-0 bottom-0" style={{
    right: "50%",
    width: "60px",
    background: "linear-gradient(to left, rgba(0, 102, 255, 0.15) 0%, transparent 100%)"
  }} />

              {}
              <div onMouseDown={handleMouseDown} className="pointer-events-auto cursor-grab flex items-center justify-center gap-px transition-transform" style={{
    width: "20px",
    height: "32px",
    borderRadius: "4px",
    background: "#f8fafc",
    border: "1px solid #d1d5db",
    boxShadow: "0 1px 2px rgba(0,0,0,0.05)",
    transform: isDragging ? "scale(1.08)" : "scale(1)"
  }}>
                <div className="flex flex-col gap-0.5">
                  {[0, 1, 2].map(i => <div key={i} style={{
    width: "3px",
    height: "3px",
    borderRadius: "50%",
    background: "#0066ff"
  }} />)}
                </div>
                <div className="flex flex-col gap-0.5">
                  {[0, 1, 2].map(i => <div key={i} style={{
    width: "3px",
    height: "3px",
    borderRadius: "50%",
    background: "#0066ff"
  }} />)}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>;
};

1. Associated Light Token accounts can hold token balances of light, SPL, or Token 2022 mints.
2. Light-ATAs are on-chain accounts like SPL ATA's, but the light token program sponsors the rent-exemption cost for you.

<Accordion title="Light Rent Config Explained">
  1) A rent sponsor PDA by Light Protocol pays the rent-exemption cost for the account.
  2) Transaction fee payers bump a virtual rent balance when writing to the account, which keeps the account "hot".
  3) "Cold" accounts virtual rent balance below threshold (eg 24h without write bump) get auto-compressed.
  4) The cold account's state is cryptographically preserved on the Solana ledger.
     Users can load a cold account into hot state in-flight when using the account
     again.
</Accordion>

<Accordion title="Agent skill">
  Install or view [dedicated agent skills](/ai-tools/overview#agent-skills).

  ```
  npx skills add Lightprotocol/skills
  ```

  Install orchestrator agent skill or view [skill.md](https://www.zkcompression.com/skill.md):

  ```bash theme={null}
  npx skills add https://zkcompression.com
  ```
</Accordion>

<Tabs>
  <Tab title="TypeScript Client">
    The `createAtaInterface` function creates an associated Light Token account in a single call.

    Compare to SPL:

    <CodeCompare firstCode={lightCreateAtaCode} secondCode={splCreateAtaCode} firstLabel="light-token" secondLabel="SPL" />

    <Info>
      Find the source code
      [here](https://github.com/Lightprotocol/light-protocol/blob/main/js/compressed-token/src/v3/actions/create-ata-interface.ts).
    </Info>

    <Tabs>
      <Tab title="Guide">
        <Steps>
          <Step>
            ### Create Associated Token Account

            <Accordion title="Installation">
              <Tabs>
                <Tab title="npm">
                  Install packages in your working directory:

                  ```bash theme={null}
                  npm install @lightprotocol/stateless.js@^0.23.0 \
                              @lightprotocol/compressed-token@^0.23.0
                  ```

                  Install the CLI globally:

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

                <Tab title="yarn">
                  Install packages in your working directory:

                  ```bash theme={null}
                  yarn add @lightprotocol/stateless.js@^0.23.0 \
                           @lightprotocol/compressed-token@^0.23.0
                  ```

                  Install the CLI globally:

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

                <Tab title="pnpm">
                  Install packages in your working directory:

                  ```bash theme={null}
                  pnpm add @lightprotocol/stateless.js@^0.23.0 \
                           @lightprotocol/compressed-token@^0.23.0
                  ```

                  Install the CLI globally:

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

                <Tab title="SDK 2.0 (token-interface)">
                  Install packages in your working directory:

                  ```bash theme={null}
                  # npm
                  npm install @lightprotocol/stateless.js@^0.23.0 \
                              @lightprotocol/token-interface@^0.1.2

                  # yarn
                  yarn add @lightprotocol/stateless.js@^0.23.0 \
                           @lightprotocol/token-interface@^0.1.2

                  # pnpm
                  pnpm add @lightprotocol/stateless.js@^0.23.0 \
                           @lightprotocol/token-interface@^0.1.2
                  ```

                  Install the CLI globally:

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

            <Tabs>
              <Tab title="Localnet">
                ```bash theme={null}
                # start local test-validator in a separate terminal
                light test-validator
                ```

                <Note>
                  In the code examples, use `createRpc()` without arguments for localnet.
                </Note>
              </Tab>

              <Tab title="Devnet">
                Get an API key from [Helius](https://helius.dev) and add to `.env`:

                ```bash title=".env" theme={null}
                API_KEY=<your-helius-api-key>
                ```

                <Note>
                  In the code examples, use `createRpc(RPC_URL)` with the devnet URL.
                </Note>
              </Tab>
            </Tabs>

            <Tabs>
              <Tab title="Action">
                ```typescript theme={null}
                import "dotenv/config";
                import { Keypair } from "@solana/web3.js";
                import { createRpc } from "@lightprotocol/stateless.js";
                import {
                    createMintInterface,
                    createAtaInterface,
                } from "@lightprotocol/compressed-token";
                import { homedir } from "os";
                import { readFileSync } from "fs";

                // devnet:
                // const RPC_URL = `https://devnet.helius-rpc.com?api-key=${process.env.API_KEY!}`;
                // const rpc = createRpc(RPC_URL);
                // localnet:
                const rpc = createRpc();

                const payer = Keypair.fromSecretKey(
                    new Uint8Array(
                        JSON.parse(readFileSync(`${homedir()}/.config/solana/id.json`, "utf8"))
                    )
                );

                (async function () {
                    const { mint } = await createMintInterface(rpc, payer, payer, null, 9);

                    const owner = Keypair.generate();
                    const ata = await createAtaInterface(rpc, payer, mint, owner.publicKey);

                    console.log("ATA:", ata.toBase58());
                })();
                ```
              </Tab>

              <Tab title="Instruction">
                ```typescript theme={null}
                import "dotenv/config";
                import {
                    Keypair,
                    Transaction,
                    sendAndConfirmTransaction,
                } from "@solana/web3.js";
                import { createRpc, LIGHT_TOKEN_PROGRAM_ID } from "@lightprotocol/stateless.js";
                import {
                    createMintInterface,
                    createAssociatedTokenAccountInterfaceInstruction,
                    getAssociatedTokenAddressInterface,
                } from "@lightprotocol/compressed-token";
                import { homedir } from "os";
                import { readFileSync } from "fs";

                // devnet:
                // const RPC_URL = `https://devnet.helius-rpc.com?api-key=${process.env.API_KEY!}`;
                // const rpc = createRpc(RPC_URL);
                // localnet:
                const rpc = createRpc();

                const payer = Keypair.fromSecretKey(
                    new Uint8Array(
                        JSON.parse(readFileSync(`${homedir()}/.config/solana/id.json`, "utf8"))
                    )
                );

                (async function () {
                    const { mint } = await createMintInterface(rpc, payer, payer, null, 9);

                    const owner = Keypair.generate();
                    const associatedToken = getAssociatedTokenAddressInterface(
                        mint,
                        owner.publicKey
                    );

                    const ix = createAssociatedTokenAccountInterfaceInstruction(
                        payer.publicKey,
                        associatedToken,
                        owner.publicKey,
                        mint,
                        LIGHT_TOKEN_PROGRAM_ID
                    );

                    const tx = new Transaction().add(ix);
                    const signature = await sendAndConfirmTransaction(rpc, tx, [payer]);

                    console.log("ATA:", associatedToken.toBase58());
                    console.log("Tx:", signature);
                })();
                ```
              </Tab>

              <Tab title="SDK 2.0 (token-interface)">
                ```typescript theme={null}
                import { Keypair, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
                import { createRpc, LIGHT_TOKEN_PROGRAM_ID } from "@lightprotocol/stateless.js";
                import { createAtaInstruction, getAtaAddress } from "@lightprotocol/token-interface";

                const rpc = createRpc();
                const payer = Keypair.fromSecretKey(/* ... */);

                const mint = /* existing mint public key */;
                const owner = Keypair.generate();
                const associatedToken = getAtaAddress({ mint, owner: owner.publicKey });

                const ix = createAtaInstruction({
                  payer: payer.publicKey,
                  owner: owner.publicKey,
                  mint,
                  programId: LIGHT_TOKEN_PROGRAM_ID,
                });

                const tx = new Transaction().add(ix);
                const signature = await sendAndConfirmTransaction(rpc, tx, [payer]);
                console.log("ATA:", associatedToken.toBase58());
                console.log("Tx:", signature);
                ```
              </Tab>
            </Tabs>
          </Step>
        </Steps>
      </Tab>

      <Tab title="AI Prompt">
        <Prompt description="Create rent-free associated token account" actions={["copy", "cursor"]}>
          {`---
                    description: Create rent-free associated token account
                    allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
                    ---

                    ## Create rent-free associated token account

                    Context:
                    - Guide: https://zkcompression.com/light-token/cookbook/create-ata
                    - Skills and resources index: https://zkcompression.com/skill.md
                    - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
                    - Packages: @lightprotocol/compressed-token, @lightprotocol/stateless.js

                    SPL equivalent: createAssociatedTokenAccount() → Light Token: createAtaInterface()

                    ### 1. Index project
                    - Grep \`@solana/spl-token|Connection|Keypair|createAssociatedTokenAccount|createAtaInterface\` across src/
                    - Glob \`**/*.ts\` for project structure
                    - Identify: RPC setup, existing ATA logic, entry point for ATA creation
                    - Task subagent (Grep/Read/WebFetch) if project has multiple packages to scan in parallel

                    ### 2. Read references
                    - WebFetch the guide above — follow the TypeScript Client tab
                    - WebFetch skill.md — check for a dedicated skill and resources matching this task
                    - TaskCreate one todo per phase below to track progress

                    ### 3. Clarify intention
                    - AskUserQuestion: what is the goal? (new feature, migrate existing SPL code, add alongside existing)
                    - AskUserQuestion: does the project already have ATA operations to extend, or is this greenfield?
                    - Summarize findings and wait for user confirmation before implementing

                    ### 4. Create plan
                    - Based on steps 1–3, draft an implementation plan: which files to modify, what code to add, dependency changes
                    - Verify existing connection/signer setup is compatible with the cookbook prerequisites
                    - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
                    - Present the plan to the user for approval before proceeding

                    ### 5. Implement
                    - Add deps if missing: Bash \`npm install @lightprotocol/compressed-token @lightprotocol/stateless.js\`
                    - Follow the cookbook guide and the approved plan
                    - Write/Edit to create or modify files
                    - TaskUpdate to mark each step done

                    ### 6. Verify
                    - Bash \`tsc --noEmit\`
                    - Bash run existing test suite if present
                    - TaskUpdate to mark complete

                    ### Tools
                    - mcp__zkcompression__SearchLightProtocol("<query>") for API details
                    - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
                    - Task subagent with Grep/Read/WebFetch for parallel lookups
                    - TaskList to check remaining work`}
        </Prompt>

        ```text theme={null}
        ---
        description: Create rent-free associated token account
        allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
        ---

        ## Create rent-free associated token account

        Context:
        - Guide: https://zkcompression.com/light-token/cookbook/create-ata
        - Skills and resources index: https://zkcompression.com/skill.md
        - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
        - Packages: @lightprotocol/compressed-token, @lightprotocol/stateless.js

        SPL equivalent: createAssociatedTokenAccount() → Light Token: createAtaInterface()

        ### 1. Index project
        - Grep `@solana/spl-token|Connection|Keypair|createAssociatedTokenAccount|createAtaInterface` across src/
        - Glob `**/*.ts` for project structure
        - Identify: RPC setup, existing ATA logic, entry point for ATA creation
        - Task subagent (Grep/Read/WebFetch) if project has multiple packages to scan in parallel

        ### 2. Read references
        - WebFetch the guide above — follow the TypeScript Client tab
        - WebFetch skill.md — check for a dedicated skill and resources matching this task
        - TaskCreate one todo per phase below to track progress

        ### 3. Clarify intention
        - AskUserQuestion: what is the goal? (new feature, migrate existing SPL code, add alongside existing)
        - AskUserQuestion: does the project already have ATA operations to extend, or is this greenfield?
        - Summarize findings and wait for user confirmation before implementing

        ### 4. Create plan
        - Based on steps 1–3, draft an implementation plan: which files to modify, what code to add, dependency changes
        - Verify existing connection/signer setup is compatible with the cookbook prerequisites
        - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
        - Present the plan to the user for approval before proceeding

        ### 5. Implement
        - Add deps if missing: Bash `npm install @lightprotocol/compressed-token @lightprotocol/stateless.js`
        - Follow the cookbook guide and the approved plan
        - Write/Edit to create or modify files
        - TaskUpdate to mark each step done

        ### 6. Verify
        - Bash `tsc --noEmit`
        - Bash run existing test suite if present
        - TaskUpdate to mark complete

        ### Tools
        - mcp__zkcompression__SearchLightProtocol("<query>") for API details
        - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
        - Task subagent with Grep/Read/WebFetch for parallel lookups
        - TaskList to check remaining work
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="Rust Client">
    `CreateAssociatedTokenAccount` creates an on-chain ATA to store token balances of light, SPL, or Token 2022 mints.

    Compare to SPL:

    <CodeCompare firstCode={lightCreateAtaRustCode} secondCode={splCreateAtaRustCode} firstLabel="light-token" secondLabel="SPL" language="rust" />

    <Tabs>
      <Tab title="Guide">
        <Steps>
          <Step>
            ### Prerequisites

            <Accordion title="Dependencies">
              ```toml Cargo.toml theme={null}
              [dependencies]
              light-token = "0.23.0"
              light-client = { version = "0.23.0", features = ["v2"] }
              solana-sdk = "2"
              borsh = "0.10.4"
              tokio = { version = "1", features = ["full"] }
              ```
            </Accordion>

            <Accordion title="Developer Environment">
              <Tabs>
                <Tab title="In-Memory (LightProgramTest)">
                  Test with Lite-SVM (...)

                  ```bash theme={null}
                  # Initialize project
                  cargo init my-light-project
                  cd my-light-project

                  # Run tests
                  cargo test
                  ```

                  ```rust theme={null}
                  use light_program_test::{LightProgramTest, ProgramTestConfig};
                  use solana_sdk::signer::Signer;

                  #[tokio::test]
                  async fn test_example() {
                      // In-memory test environment 
                      let mut rpc = LightProgramTest::new(ProgramTestConfig::default())
                          .await
                          .unwrap();

                      let payer = rpc.get_payer().insecure_clone();
                      println!("Payer: {}", payer.pubkey());
                  }
                  ```
                </Tab>

                <Tab title="Localnet (LightClient)">
                  Connects to a local test validator.

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

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

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

                  ```bash theme={null}
                  # Initialize project
                  cargo init my-light-project
                  cd my-light-project

                  # Start local test validator (in separate terminal)
                  light test-validator
                  ```

                  ```rust theme={null}
                  use light_client::rpc::{LightClient, LightClientConfig, Rpc};

                  #[tokio::main]
                  async fn main() -> Result<(), Box<dyn std::error::Error>> {
                      // Connects to http://localhost:8899
                      let rpc = LightClient::new(LightClientConfig::local()).await?;

                      let slot = rpc.get_slot().await?;
                      println!("Current slot: {}", slot);

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

                <Tab title="Devnet (LightClient)">
                  Replace `<your-api-key>` with your actual API key. [Get your API key here](https://www.helius.dev/zk-compression).

                  ```rust theme={null}
                  use light_client::rpc::{LightClient, LightClientConfig, Rpc};

                  #[tokio::main]
                  async fn main() -> Result<(), Box<dyn std::error::Error>> {
                      let rpc_url = "https://devnet.helius-rpc.com?api-key=<your_api_key>";
                      let rpc = LightClient::new(
                          LightClientConfig::new(rpc_url.to_string(), None, None)
                      ).await?;

                      println!("Connected to Devnet");
                      Ok(())
                  }
                  ```
                </Tab>
              </Tabs>
            </Accordion>
          </Step>

          <Step>
            ### Create ATA

            <Info>
              Find the source code [here](https://github.com/Lightprotocol/light-protocol/blob/main/sdk-libs/token-sdk/src/instruction/create_ata.rs).
            </Info>

            <Tabs>
              <Tab title="Action">
                ```rust theme={null}
                use light_token_client::actions::{CreateAta, CreateMint};
                use rust_client::setup_rpc_and_payer;
                use solana_sdk::signer::Signer;

                #[tokio::main]
                async fn main() -> Result<(), Box<dyn std::error::Error>> {
                    let (mut rpc, payer) = setup_rpc_and_payer().await;

                    // Create mint
                    let (_signature, mint) = CreateMint {
                        decimals: 9,
                        freeze_authority: None,
                        token_metadata: None,
                        seed: None,
                    }
                    .execute(&mut rpc, &payer, &payer)
                    .await?;

                    // Create associated token account
                    let (_signature, associated_token_account) = CreateAta {
                        mint,
                        owner: payer.pubkey(),
                        idempotent: true,
                    }
                    .execute(&mut rpc, &payer)
                    .await?;

                    println!("Associated token account: {associated_token_account}");

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

              <Tab title="Instruction">
                ```rust theme={null}
                use light_client::rpc::Rpc;
                use light_token::instruction::{get_associated_token_address, CreateAssociatedTokenAccount};
                use rust_client::{setup_spl_mint_context, SplMintContext};
                use solana_sdk::{signature::Keypair, signer::Signer};

                #[tokio::main]
                async fn main() -> Result<(), Box<dyn std::error::Error>> {
                    // You can use Light, SPL, or Token-2022 mints to create a Light associated token account.
                    let SplMintContext {
                        mut rpc,
                        payer,
                        mint,
                    } = setup_spl_mint_context().await;

                    let owner = Keypair::new();

                    let create_associated_token_account_instruction =
                        CreateAssociatedTokenAccount::new(payer.pubkey(), owner.pubkey(), mint).instruction()?;

                    let sig = rpc
                        .create_and_send_transaction(&[create_associated_token_account_instruction], &payer.pubkey(), &[&payer])
                        .await?;

                    let associated_token_account = get_associated_token_address(&owner.pubkey(), &mint);
                    let data = rpc.get_account(associated_token_account).await?;
                    println!("Associated token account: {associated_token_account} exists: {} Tx: {sig}", data.is_some());

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

      <Tab title="AI Prompt">
        <Prompt description="Create rent-free associated token account" actions={["copy", "cursor"]}>
          {`---
                    description: Create rent-free associated token account
                    allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
                    ---

                    ## Create rent-free associated token account

                    Context:
                    - Guide: https://zkcompression.com/light-token/cookbook/create-ata
                    - Skills and resources index: https://zkcompression.com/skill.md
                    - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
                    - Crates: light-token-client (actions), light-token (instructions), light-client (RPC)

                    SPL equivalent: spl_associated_token_account::create → Light Token: CreateAta

                    ### 1. Index project
                    - Grep \`light_token::|light_token_client::|solana_sdk|Keypair|async|CreateAta|create_associated_token_account\` across src/
                    - Glob \`**/*.rs\` for project structure
                    - Identify: RPC setup, existing token ops, entry point for ATA creation
                    - Check Cargo.toml for existing light-* dependencies and solana-sdk version
                    - Task subagent (Grep/Read/WebFetch) if project has multiple crates to scan in parallel

                    ### 2. Read references
                    - WebFetch the guide above — follow the Rust Client tab
                    - WebFetch skill.md — check for a dedicated skill and resources matching this task
                    - TaskCreate one todo per phase below to track progress

                    ### 3. Clarify intention
                    - AskUserQuestion: what is the goal? (new feature, migrate existing SPL code, add alongside existing)
                    - AskUserQuestion: does the project already have ATA operations to extend, or is this greenfield?
                    - AskUserQuestion: action-level API (high-level, fewer lines) or instruction-level API (low-level, full control)?
                    - Summarize findings and wait for user confirmation before implementing

                    ### 4. Create plan
                    - Based on steps 1–3, draft an implementation plan: which files to modify, what code to add, dependency changes
                    - Verify existing Rpc/signer setup is compatible with the cookbook prerequisites (light_client::rpc::Rpc, solana_sdk::signature::Keypair)
                    - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
                    - Present the plan to the user for approval before proceeding

                    ### 5. Implement
                    - Add deps if missing: Bash \`cargo add light-token-client light-token light-client --features light-client/v2\`
                    - Follow the cookbook guide and the approved plan
                    - Write/Edit to create or modify files
                    - TaskUpdate to mark each step done

                    ### 6. Verify
                    - Bash \`cargo check\`
                    - Bash \`cargo test\` if tests exist
                    - TaskUpdate to mark complete

                    ### Tools
                    - mcp__zkcompression__SearchLightProtocol("<query>") for API details
                    - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
                    - Task subagent with Grep/Read/WebFetch for parallel lookups
                    - TaskList to check remaining work`}
        </Prompt>

        ```text theme={null}
        ---
        description: Create rent-free associated token account
        allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
        ---

        ## Create rent-free associated token account

        Context:
        - Guide: https://zkcompression.com/light-token/cookbook/create-ata
        - Skills and resources index: https://zkcompression.com/skill.md
        - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
        - Crates: light-token-client (actions), light-token (instructions), light-client (RPC)

        SPL equivalent: spl_associated_token_account::create → Light Token: CreateAta

        ### 1. Index project
        - Grep `light_token::|light_token_client::|solana_sdk|Keypair|async|CreateAta|create_associated_token_account` across src/
        - Glob `**/*.rs` for project structure
        - Identify: RPC setup, existing token ops, entry point for ATA creation
        - Check Cargo.toml for existing light-* dependencies and solana-sdk version
        - Task subagent (Grep/Read/WebFetch) if project has multiple crates to scan in parallel

        ### 2. Read references
        - WebFetch the guide above — follow the Rust Client tab
        - WebFetch skill.md — check for a dedicated skill and resources matching this task
        - TaskCreate one todo per phase below to track progress

        ### 3. Clarify intention
        - AskUserQuestion: what is the goal? (new feature, migrate existing SPL code, add alongside existing)
        - AskUserQuestion: does the project already have ATA operations to extend, or is this greenfield?
        - AskUserQuestion: action-level API (high-level, fewer lines) or instruction-level API (low-level, full control)?
        - Summarize findings and wait for user confirmation before implementing

        ### 4. Create plan
        - Based on steps 1–3, draft an implementation plan: which files to modify, what code to add, dependency changes
        - Verify existing Rpc/signer setup is compatible with the cookbook prerequisites (light_client::rpc::Rpc, solana_sdk::signature::Keypair)
        - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
        - Present the plan to the user for approval before proceeding

        ### 5. Implement
        - Add deps if missing: Bash `cargo add light-token-client light-token light-client --features light-client/v2`
        - Follow the cookbook guide and the approved plan
        - Write/Edit to create or modify files
        - TaskUpdate to mark each step done

        ### 6. Verify
        - Bash `cargo check`
        - Bash `cargo test` if tests exist
        - TaskUpdate to mark complete

        ### Tools
        - mcp__zkcompression__SearchLightProtocol("<query>") for API details
        - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
        - Task subagent with Grep/Read/WebFetch for parallel lookups
        - TaskList to check remaining work
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="Program">
    <Tabs>
      <Tab title="CPI">
        <Tabs>
          <Tab title="Guide">
            Compare to SPL:

            <CodeCompare firstCode={lightCreateAtaCpiCode} secondCode={splCreateAtaCpiCode} firstLabel="light-token" secondLabel="SPL" language="rust" />

            <Note>
              Find [a full code example at the end](#full-code-example).
            </Note>

            <Steps>
              <Step>
                ### Build Account Infos and CPI the Light Token Program

                1. Pass ATA accounts and call `.rent_free()` with rent config accounts.
                2. Use `invoke` or `invoke_signed`:
                   * When the `payer` is an external wallet, use `invoke`.
                   * When the `payer` is a PDA, use `invoke_signed` with its seeds.

                <Note>
                  The light-ATA address is derived from `[owner, light_token_program_id, mint]`.
                  Unlike Light Token accounts, owner and mint are passed as accounts, not in
                  instruction data.
                </Note>

                <Tabs>
                  <Tab title="invoke (External signer)">
                    ```rust theme={null}
                    use light_token::instruction::CreateAssociatedAccountCpi;

                    CreateAssociatedAccountCpi {
                        payer: payer.clone(),
                        owner: owner.clone(),
                        mint: mint.clone(),
                        ata: associated_token_account.clone(),
                        bump,
                    }
                    .rent_free(
                        compressible_config.clone(),
                        rent_sponsor.clone(),
                        system_program.clone(),
                    )
                    .invoke()
                    ```
                  </Tab>

                  <Tab title="invoke_signed (PDA signer)">
                    ```rust theme={null}
                    use light_token::instruction::CreateAssociatedAccountCpi;

                    let signer_seeds: &[&[u8]] = &[ATA_SEED, &[authority_bump]];

                    CreateAssociatedAccountCpi {
                        payer: payer.clone(),
                        owner: owner.clone(),
                        mint: mint.clone(),
                        ata: associated_token_account.clone(),
                        bump,
                    }
                    .rent_free(
                        compressible_config.clone(),
                        rent_sponsor.clone(),
                        system_program.clone(),
                    )
                    .invoke_signed(&[signer_seeds])
                    ```
                  </Tab>
                </Tabs>

                <table>
                  <colgroup>
                    <col style={{width: '25%', textAlign: 'left'}} />

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

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

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

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

                  <tbody>
                    <tr>
                      <td style={{textAlign: 'left'}}><strong>Owner</strong></td>
                      <td>-</td>

                      <td>
                        * The wallet that will own this light-ATA.<br />
                        * Used to derive the light-ATA address deterministically.
                      </td>
                    </tr>

                    <tr>
                      <td style={{textAlign: 'left'}}><strong>Mint</strong></td>
                      <td>-</td>

                      <td>
                        * The SPL or light-mint token mint.<br />
                        * Used to derive the light-ATA address deterministically.
                      </td>
                    </tr>

                    <tr>
                      <td style={{textAlign: 'left'}}><strong>Payer</strong></td>
                      <td>signer, mutable</td>

                      <td>
                        * Pays initial rent per epoch, transaction fee and compression incentive.<br />
                        * Does NOT pay rent exemption (paid by the light token program, `rent_sponsor`).
                      </td>
                    </tr>

                    <tr>
                      <td style={{textAlign: 'left'}}><strong>light-ATA Account</strong></td>
                      <td>mutable</td>

                      <td>
                        * The light-ATA being created.<br />
                        * Address is derived from `[owner, light_token_program_id, mint]`.
                      </td>
                    </tr>

                    <tr>
                      <td style={{textAlign: 'left'}}><strong><Tooltip tip="11111111111111111111111111111111" cta="Program ID" href="https://solscan.io/account/11111111111111111111111111111111">System Program</Tooltip></strong></td>
                      <td>-</td>
                      <td>Solana System Program. Required for CPI to create the on-chain account.</td>
                    </tr>

                    <tr>
                      <td style={{textAlign: 'left'}}><strong>Bump</strong></td>
                      <td>u8</td>
                      <td>The PDA bump seed for the light-ATA address derivation.</td>
                    </tr>

                    <tr>
                      <td style={{textAlign: 'left'}}><strong>Idempotent</strong></td>
                      <td>bool</td>

                      <td>
                        * When `true`, silently succeeds if account already exists.<br />
                        * When `false`, fails if account already exists.
                      </td>
                    </tr>
                  </tbody>
                </table>
              </Step>
            </Steps>

            # Full Code Example

            <Info>
              View the [source code](https://github.com/Lightprotocol/light-protocol/blob/main/sdk-libs/token-sdk/src/instruction/create_ata.rs) and [full example](https://github.com/Lightprotocol/examples-light-token/tree/main/programs/anchor/basic-instructions/create-associated-token-account) with shared test utilities.
            </Info>

            <CodeGroup>
              ```rust lib.rs theme={null}
              #![allow(unexpected_cfgs, deprecated)]

              use anchor_lang::prelude::*;
              use light_token::instruction::CreateAssociatedAccountCpi;

              declare_id!("35MukgdfpNUbPMhTmEk63ECV8vjgpNVFRH9nP8ovMN58");

              #[program]
              pub mod light_token_anchor_create_associated_token_account {
                  use super::*;

                  pub fn create_associated_token_account(ctx: Context<CreateAssociatedTokenAccountAccounts>, idempotent: bool) -> Result<()> {
                      let cpi = CreateAssociatedAccountCpi {
                          payer: ctx.accounts.payer.to_account_info(),
                          owner: ctx.accounts.owner.to_account_info(),
                          mint: ctx.accounts.mint.to_account_info(),
                          ata: ctx.accounts.associated_token_account.to_account_info(),
                      };

                      if idempotent {
                          cpi.idempotent().rent_free(
                              ctx.accounts.compressible_config.to_account_info(),
                              ctx.accounts.rent_sponsor.to_account_info(),
                              ctx.accounts.system_program.to_account_info(),
                          )
                      } else {
                          cpi.rent_free(
                              ctx.accounts.compressible_config.to_account_info(),
                              ctx.accounts.rent_sponsor.to_account_info(),
                              ctx.accounts.system_program.to_account_info(),
                          )
                      }
                      .invoke()?;
                      Ok(())
                  }
              }

              #[derive(Accounts)]
              pub struct CreateAssociatedTokenAccountAccounts<'info> {
                  /// CHECK: Light token program for CPI
                  pub light_token_program: AccountInfo<'info>,
                  /// CHECK: Validated by light-token CPI
                  pub owner: AccountInfo<'info>,
                  /// CHECK: Validated by light-token CPI
                  pub mint: AccountInfo<'info>,
                  #[account(mut)]
                  pub payer: Signer<'info>,
                  /// CHECK: Validated by light-token CPI
                  #[account(mut)]
                  pub associated_token_account: AccountInfo<'info>,
                  pub system_program: Program<'info, System>,
                  /// CHECK: Validated by light-token CPI
                  pub compressible_config: AccountInfo<'info>,
                  /// CHECK: Validated by light-token CPI
                  #[account(mut)]
                  pub rent_sponsor: AccountInfo<'info>,
              }
              ```

              ```rust test.rs theme={null}
              use anchor_lang::{InstructionData, ToAccountMetas};
              use light_client::indexer::AddressWithTree;
              use light_program_test::{Indexer, LightProgramTest, ProgramTestConfig, Rpc};
              use light_token_anchor_create_associated_token_account::{accounts, instruction::CreateAssociatedTokenAccount, ID};
              use light_token::instruction::{
                  CreateMint, CreateMintParams, config_pda, derive_mint_compressed_address, derive_token_ata,
                  find_mint_address, rent_sponsor_pda, LIGHT_TOKEN_PROGRAM_ID,
                  DEFAULT_RENT_PAYMENT, DEFAULT_WRITE_TOP_UP,
              };
              use anchor_lang::system_program;
              use solana_sdk::{
                  instruction::Instruction,
                  signature::Keypair,
                  signer::Signer,
              };

              #[tokio::test]
              async fn test_create_associated_token_account() {
                  let config =
                      ProgramTestConfig::new_v2(true, Some(vec![("light_token_anchor_create_associated_token_account", ID)]));
                  let mut rpc = LightProgramTest::new(config).await.unwrap();
                  let payer = rpc.get_payer().insecure_clone();

                  let mint_seed = Keypair::new();
                  let mint_authority = payer.pubkey();
                  let decimals = 9u8;

                  let address_tree = rpc.get_address_tree_v2();
                  let output_queue = rpc.get_random_state_tree_info().unwrap().queue;

                  let compression_address =
                      derive_mint_compressed_address(&mint_seed.pubkey(), &address_tree.tree);
                  let (mint_pda, bump) = find_mint_address(&mint_seed.pubkey());

                  let rpc_result = rpc
                      .get_validity_proof(
                          vec![],
                          vec![AddressWithTree {
                              address: compression_address,
                              tree: address_tree.tree,
                          }],
                          None,
                      )
                      .await
                      .unwrap()
                      .value;

                  let params = CreateMintParams {
                      decimals,
                      address_merkle_tree_root_index: rpc_result.addresses[0].root_index,
                      mint_authority,
                      proof: rpc_result.proof.0.unwrap(),
                      compression_address,
                      mint: mint_pda,
                      bump,
                      freeze_authority: None,
                      extensions: None,
                      rent_payment: DEFAULT_RENT_PAYMENT,
                      write_top_up: DEFAULT_WRITE_TOP_UP,
                  };

                  let create_mint_ix = CreateMint::new(
                      params,
                      mint_seed.pubkey(),
                      payer.pubkey(),
                      address_tree.tree,
                      output_queue,
                  )
                  .instruction()
                  .unwrap();

                  rpc.create_and_send_transaction(&[create_mint_ix], &payer.pubkey(), &[&payer, &mint_seed])
                      .await
                      .unwrap();

                  // You can use light, spl, t22 mints to create a light token associated token account.
                  // Derive associated token account address and bump
                  let associated_token_account = derive_token_ata(&payer.pubkey(), &mint_pda);

                  // Call the anchor program to create associated token account
                  let compressible_config = config_pda();
                  let rent_sponsor = rent_sponsor_pda();

                  let ix = Instruction {
                      program_id: ID,
                      accounts: accounts::CreateAssociatedTokenAccountAccounts {
                          light_token_program: LIGHT_TOKEN_PROGRAM_ID,
                          owner: payer.pubkey(),
                          mint: mint_pda,
                          payer: payer.pubkey(),
                          associated_token_account: associated_token_account,
                          system_program: system_program::ID,
                          compressible_config,
                          rent_sponsor,
                      }
                      .to_account_metas(Some(true)),
                      data: CreateAssociatedTokenAccount {
                          idempotent: false,
                      }
                      .data(),
                  };

                  let sig = rpc.create_and_send_transaction(&[ix], &payer.pubkey(), &[&payer])
                      .await
                      .unwrap();

                  println!("Tx: {}", sig);
              }
              ```
            </CodeGroup>
          </Tab>

          <Tab title="AI Prompt">
            <Prompt description="Add create-ATA CPI to an Anchor program" actions={["copy", "cursor"]}>
              {`---
                            description: Add create-ATA CPI to an Anchor program
                            allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
                            ---

                            ## Add create-ATA CPI to an Anchor program

                            Context:
                            - Guide: https://zkcompression.com/light-token/cookbook/create-ata
                            - Skills and resources index: https://zkcompression.com/skill.md
                            - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
                            - Crate: light-token (CreateAssociatedAccountCpi)
                            - Example: https://github.com/Lightprotocol/examples-light-token/tree/main/programs/anchor/basic-instructions/create-associated-token-account

                            Key CPI struct: \`light_token::instruction::CreateAssociatedAccountCpi\`

                            ### 1. Index project
                            - Grep \`declare_id|#\[program\]|anchor_lang|Account<|Pubkey|invoke|ata|associated|owner|mint\` across src/
                            - Glob \`**/*.rs\` and \`**/Cargo.toml\` for project structure
                            - Identify: program ID, existing instructions, account structs, ATA derivation
                            - Read Cargo.toml — note existing dependencies and framework version
                            - Task subagent (Grep/Read/WebFetch) if project has multiple crates to scan in parallel

                            ### 2. Read references
                            - WebFetch the guide above — review the CPI tab under Program: ATA creation with .rent_free() chain
                            - WebFetch skill.md — check for a dedicated skill and resources matching this task
                            - TaskCreate one todo per phase below to track progress

                            ### 3. Clarify intention
                            - AskUserQuestion: what is the goal? (add create-ATA to existing program, new program from scratch, migrate from SPL create_associated_token_account)
                            - AskUserQuestion: should the payer be an external signer or a PDA? (determines invoke vs invoke_signed)
                            - Summarize findings and wait for user confirmation before implementing

                            ### 4. Create plan
                            - Based on steps 1–3, draft an implementation plan: which files to modify, what code to add, dependency changes
                            - Follow the guide's step order: Build CreateAssociatedAccountCpi → .rent_free() → .invoke() or .invoke_signed()
                            - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
                            - Present the plan to the user for approval before proceeding

                            ### 5. Implement
                            - Add deps if missing: Bash \`cargo add light-token anchor-lang@0.31\`
                            - Follow the guide and the approved plan
                            - Write/Edit to create or modify files
                            - TaskUpdate to mark each step done

                            ### 6. Verify
                            - Bash \`anchor build\`
                            - Bash \`anchor test\` if tests exist
                            - TaskUpdate to mark complete

                            ### Tools
                            - mcp__zkcompression__SearchLightProtocol("<query>") for API details
                            - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
                            - Task subagent with Grep/Read/WebFetch for parallel lookups
                            - TaskList to check remaining work`}
            </Prompt>

            ```text theme={null}
            ---
            description: Add create-ATA CPI to an Anchor program
            allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
            ---

            ## Add create-ATA CPI to an Anchor program

            Context:
            - Guide: https://zkcompression.com/light-token/cookbook/create-ata
            - Skills and resources index: https://zkcompression.com/skill.md
            - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
            - Crate: light-token (CreateAssociatedAccountCpi)
            - Example: https://github.com/Lightprotocol/examples-light-token/tree/main/programs/anchor/basic-instructions/create-associated-token-account

            Key CPI struct: `light_token::instruction::CreateAssociatedAccountCpi`

            ### 1. Index project
            - Grep `declare_id|#\[program\]|anchor_lang|Account<|Pubkey|invoke|ata|associated|owner|mint` across src/
            - Glob `**/*.rs` and `**/Cargo.toml` for project structure
            - Identify: program ID, existing instructions, account structs, ATA derivation
            - Read Cargo.toml — note existing dependencies and framework version
            - Task subagent (Grep/Read/WebFetch) if project has multiple crates to scan in parallel

            ### 2. Read references
            - WebFetch the guide above — review the CPI tab under Program: ATA creation with .rent_free() chain
            - WebFetch skill.md — check for a dedicated skill and resources matching this task
            - TaskCreate one todo per phase below to track progress

            ### 3. Clarify intention
            - AskUserQuestion: what is the goal? (add create-ATA to existing program, new program from scratch, migrate from SPL create_associated_token_account)
            - AskUserQuestion: should the payer be an external signer or a PDA? (determines invoke vs invoke_signed)
            - Summarize findings and wait for user confirmation before implementing

            ### 4. Create plan
            - Based on steps 1–3, draft an implementation plan: which files to modify, what code to add, dependency changes
            - Follow the guide's step order: Build CreateAssociatedAccountCpi → .rent_free() → .invoke() or .invoke_signed()
            - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
            - Present the plan to the user for approval before proceeding

            ### 5. Implement
            - Add deps if missing: Bash `cargo add light-token anchor-lang@0.31`
            - Follow the guide and the approved plan
            - Write/Edit to create or modify files
            - TaskUpdate to mark each step done

            ### 6. Verify
            - Bash `anchor build`
            - Bash `anchor test` if tests exist
            - TaskUpdate to mark complete

            ### Tools
            - mcp__zkcompression__SearchLightProtocol("<query>") for API details
            - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
            - Task subagent with Grep/Read/WebFetch for parallel lookups
            - TaskList to check remaining work
            ```
          </Tab>
        </Tabs>
      </Tab>

      <Tab title="Anchor Macros">
        <Tabs>
          <Tab title="Guide">
            Compare to SPL:

            <CodeCompare firstCode={lightCreateAtaMacroCode} secondCode={splCreateAtaMacroCode} firstLabel="light-token" secondLabel="SPL" language="rust" />

            <Note>
              Find [a full code example at the end](#full-code-example-1).
            </Note>

            <Steps>
              <Step>
                ### Dependencies

                ```toml theme={null}
                [dependencies]
                light-sdk = { version = "0.23.0", features = ["anchor", "v2", "cpi-context"] }
                light-sdk-macros = "0.23.0"
                light-compressible = "0.6.0"
                anchor-lang = "0.31"
                ```
              </Step>

              <Step>
                ### Program

                Add `#[light_program]` above `#[program]`:

                ```rust theme={null}
                use light_sdk_macros::light_program;

                #[light_program]
                #[program]
                pub mod light_token_macro_create_ata {
                    use super::*;

                    pub fn create_ata<'info>(
                        ctx: Context<'_, '_, '_, 'info, CreateAta<'info>>,
                        params: CreateAtaParams,
                    ) -> Result<()> {
                        Ok(())
                    }
                }
                ```
              </Step>

              <Step>
                ### Accounts struct

                Derive `LightAccounts` on your `Accounts` struct and add `#[light_account(...)]` next to `#[account(...)]`.

                ```rust theme={null}
                /// CHECK: Validated by light-token CPI
                #[account(mut)]
                #[light_account(
                    init,
                    associated_token::authority = ata_owner,
                    associated_token::mint = ata_mint,
                    associated_token::bump = params.ata_bump
                )]
                pub ata: UncheckedAccount<'info>,
                ```
              </Step>
            </Steps>

            # Full code example

            <Info>
              View the [source code](https://github.com/Lightprotocol/light-protocol/blob/main/sdk-libs/token-sdk/src/instruction/create_ata.rs) and [full example](https://github.com/Lightprotocol/examples-light-token/tree/main/programs/anchor/basic-macros/create-associated-token-account) with shared test utilities.
            </Info>

            <CodeGroup>
              ```rust lib.rs theme={null}
              #![allow(deprecated)]

              use anchor_lang::prelude::*;
              use light_account::{
                  derive_light_cpi_signer, light_program, CreateAccountsProof, CpiSigner, LightAccounts,
                  LIGHT_TOKEN_PROGRAM_ID,
              };
              use light_token::instruction::{LIGHT_TOKEN_CONFIG, LIGHT_TOKEN_RENT_SPONSOR};

              declare_id!("CLsn9MTFv97oMTsujRoQAw1u2rSm2HnKtGuWUbbc8Jfn");

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

              #[light_program]
              #[program]
              pub mod light_token_macro_create_associated_token_account {
                  use super::*;

                  #[allow(unused_variables)]
                  pub fn create_associated_token_account<'info>(
                      ctx: Context<'_, '_, '_, 'info, CreateAssociatedTokenAccount<'info>>,
                      params: CreateAssociatedTokenAccountParams,
                  ) -> Result<()> {
                      Ok(())
                  }
              }

              #[derive(AnchorSerialize, AnchorDeserialize, Clone)]
              pub struct CreateAssociatedTokenAccountParams {
                  pub create_accounts_proof: CreateAccountsProof,
              }

              #[derive(Accounts, LightAccounts)]
              #[instruction(params: CreateAssociatedTokenAccountParams)]
              pub struct CreateAssociatedTokenAccount<'info> {
                  #[account(mut)]
                  pub fee_payer: Signer<'info>,

                  /// CHECK: Token mint for the associated token account
                  pub associated_token_account_mint: AccountInfo<'info>,

                  /// CHECK: Owner of the associated token account
                  pub associated_token_account_owner: AccountInfo<'info>,

                  /// CHECK: Validated by light_account macro
                  #[account(mut)]
                  #[light_account(init, associated_token::authority = associated_token_account_owner, associated_token::mint = associated_token_account_mint)]
                  pub associated_token_account: UncheckedAccount<'info>,

                  /// CHECK: Validated by address constraint
                  #[account(address = LIGHT_TOKEN_CONFIG)]
                  pub light_token_config: AccountInfo<'info>,

                  /// CHECK: Validated by address constraint
                  #[account(mut, address = LIGHT_TOKEN_RENT_SPONSOR)]
                  pub light_token_rent_sponsor: AccountInfo<'info>,

                  /// CHECK: Light Token program for CPI
                  #[account(address = LIGHT_TOKEN_PROGRAM_ID.into())]
                  pub light_token_program: AccountInfo<'info>,

                  pub system_program: Program<'info, System>,
              }
              ```

              ```rust test.rs theme={null}
              use anchor_lang::{InstructionData, ToAccountMetas};
              use light_client::interface::{get_create_accounts_proof, InitializeRentFreeConfig};
              use light_program_test::{
                  program_test::{setup_mock_program_data, LightProgramTest},
                  ProgramTestConfig, Rpc,
              };
              use light_account::{derive_rent_sponsor_pda, LIGHT_TOKEN_PROGRAM_ID};
              use light_token::instruction::{LIGHT_TOKEN_CONFIG, LIGHT_TOKEN_RENT_SPONSOR};
              use solana_instruction::Instruction;
              use solana_signer::Signer;
              use test_utils::create_mint;

              /// Test creating a Light Protocol associated token account using the macro.
              #[tokio::test]
              async fn test_create_associated_token_account() {
                  use light_token_macro_create_associated_token_account::CreateAssociatedTokenAccountParams;

                  let program_id = light_token_macro_create_associated_token_account::ID;
                  let mut config =
                      ProgramTestConfig::new_v2(true, Some(vec![("light_token_macro_create_associated_token_account", program_id)]));
                  config = config.with_light_protocol_events();

                  let mut rpc = LightProgramTest::new(config).await.unwrap();
                  let payer = rpc.get_payer().insecure_clone();

                  let program_data_pda = setup_mock_program_data(&mut rpc, &payer, &program_id);

                  let (rent_sponsor, _) = derive_rent_sponsor_pda(&program_id);

                  let (init_config_ix, _config_pda) = InitializeRentFreeConfig::new(
                      &program_id,
                      &payer.pubkey(),
                      &program_data_pda,
                      rent_sponsor,
                      payer.pubkey(),
                  )
                  .build();

                  rpc.create_and_send_transaction(&[init_config_ix], &payer.pubkey(), &[&payer])
                      .await
                      .expect("Initialize config should succeed");

                  let (mint, _mint_seed) = create_mint(&mut rpc, &payer, None).await;

                  // The associated token account owner will be the payer
                  let associated_token_account_owner = payer.pubkey();

                  // Derive the associated token account address using Light Token SDK's derivation
                  let associated_token_account = light_token::instruction::derive_token_ata(&associated_token_account_owner, &mint);

                  // Get proof (no PDA accounts for associated token account-only instruction)
                  let proof_result = get_create_accounts_proof(&rpc, &program_id, vec![])
                      .await
                      .unwrap();

                  // Build instruction
                  let accounts = light_token_macro_create_associated_token_account::accounts::CreateAssociatedTokenAccount {
                      fee_payer: payer.pubkey(),
                      associated_token_account_mint: mint,
                      associated_token_account_owner,
                      associated_token_account,
                      light_token_config: LIGHT_TOKEN_CONFIG,
                      light_token_rent_sponsor: LIGHT_TOKEN_RENT_SPONSOR,
                      light_token_program: LIGHT_TOKEN_PROGRAM_ID.into(),
                      system_program: solana_sdk::system_program::ID,
                  };

                  let instruction_data = light_token_macro_create_associated_token_account::instruction::CreateAssociatedTokenAccount {
                      params: CreateAssociatedTokenAccountParams {
                          create_accounts_proof: proof_result.create_accounts_proof,
                      },
                  };

                  let instruction = Instruction {
                      program_id,
                      accounts: [
                          accounts.to_account_metas(None),
                          proof_result.remaining_accounts,
                      ]
                      .concat(),
                      data: instruction_data.data(),
                  };

                  rpc.create_and_send_transaction(&[instruction], &payer.pubkey(), &[&payer])
                      .await
                      .expect("CreateAssociatedTokenAccount instruction should succeed");

                  // Verify associated token account exists on-chain
                  let associated_token_account_data = rpc
                      .get_account(associated_token_account)
                      .await
                      .unwrap()
                      .expect("Associated token account should exist on-chain");

                  // Parse and verify token data
                  use light_token_interface::state::Token;
                  let token: Token = borsh::BorshDeserialize::deserialize(&mut &associated_token_account_data.data[..])
                      .expect("Failed to deserialize Token");

                  // Verify owner
                  assert_eq!(token.owner, associated_token_account_owner.to_bytes(), "Associated token account owner should match");

                  // Verify mint
                  assert_eq!(token.mint, mint.to_bytes(), "Associated token account mint should match");

                  // Verify initial amount is 0
                  assert_eq!(token.amount, 0, "Associated token account amount should be 0 initially");
              }
              ```
            </CodeGroup>
          </Tab>

          <Tab title="AI Prompt">
            <Prompt description="Create a rent-free ATA with Anchor macros" actions={["copy", "cursor"]}>
              {`---
                            description: Create a rent-free ATA with Anchor macros
                            allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
                            ---

                            ## Create a rent-free ATA with Anchor macros

                            Context:
                            - Guide: https://zkcompression.com/light-token/cookbook/create-ata
                            - Skills and resources index: https://zkcompression.com/skill.md
                            - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
                            - Crates: light-sdk, light-sdk-macros, light-compressible, anchor-lang
                            - Example: https://github.com/Lightprotocol/examples-light-token/tree/main/programs/anchor/basic-macros/create-associated-token-account

                            Key macros: \`#[light_program]\`, \`LightAccounts\`, \`#[light_account(init, associated_token::...)]\`

                            ### 1. Index project
                            - Grep \`#\[program\]|anchor_lang|Account<|Accounts|seeds|init|payer|ata|associated\` across src/
                            - Glob \`**/*.rs\` and \`**/Cargo.toml\` for project structure
                            - Identify: existing program module, account structs, ATA patterns
                            - Read Cargo.toml — note existing dependencies and framework version
                            - Task subagent (Grep/Read/WebFetch) if project has multiple crates to scan in parallel

                            ### 2. Read references
                            - WebFetch the guide above — review the Anchor Macros tab under Program
                            - WebFetch skill.md — check for a dedicated skill and resources matching this task
                            - TaskCreate one todo per phase below to track progress

                            ### 3. Clarify intention
                            - AskUserQuestion: what is the goal? (new program from scratch, add rent-free ATA to existing program, migrate from SPL create_associated_token_account)
                            - Summarize findings and wait for user confirmation before implementing

                            ### 4. Create plan
                            - Based on steps 1–3, draft an implementation plan
                            - Follow the guide's step order: Dependencies → Program Module (#[light_program]) → Accounts Struct (#[light_account(init, associated_token::...)])
                            - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
                            - Present the plan to the user for approval before proceeding

                            ### 5. Implement
                            - Add deps if missing: Bash \`cargo add light-sdk@0.23 --features anchor,v2,cpi-context\` and \`cargo add light-sdk-macros@0.23 light-compressible@0.6 anchor-lang@0.31\`
                            - Follow the guide and the approved plan
                            - Write/Edit to create or modify files
                            - TaskUpdate to mark each step done

                            ### 6. Verify
                            - Bash \`anchor build\`
                            - Bash \`anchor test\` if tests exist
                            - TaskUpdate to mark complete

                            ### Tools
                            - mcp__zkcompression__SearchLightProtocol("<query>") for API details
                            - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
                            - Task subagent with Grep/Read/WebFetch for parallel lookups
                            - TaskList to check remaining work`}
            </Prompt>

            ```text theme={null}
            ---
            description: Create a rent-free ATA with Anchor macros
            allowed-tools: Bash, Read, Write, Edit, Glob, Grep, WebFetch, AskUserQuestion, Task, TaskCreate, TaskGet, TaskList, TaskUpdate, TaskOutput, mcp__deepwiki, mcp__zkcompression
            ---

            ## Create a rent-free ATA with Anchor macros

            Context:
            - Guide: https://zkcompression.com/light-token/cookbook/create-ata
            - Skills and resources index: https://zkcompression.com/skill.md
            - SPL to Light reference: https://zkcompression.com/api-reference/solana-to-light-comparison
            - Crates: light-sdk, light-sdk-macros, light-compressible, anchor-lang
            - Example: https://github.com/Lightprotocol/examples-light-token/tree/main/programs/anchor/basic-macros/create-associated-token-account

            Key macros: `#[light_program]`, `LightAccounts`, `#[light_account(init, associated_token::...)]`

            ### 1. Index project
            - Grep `#\[program\]|anchor_lang|Account<|Accounts|seeds|init|payer|ata|associated` across src/
            - Glob `**/*.rs` and `**/Cargo.toml` for project structure
            - Identify: existing program module, account structs, ATA patterns
            - Read Cargo.toml — note existing dependencies and framework version
            - Task subagent (Grep/Read/WebFetch) if project has multiple crates to scan in parallel

            ### 2. Read references
            - WebFetch the guide above — review the Anchor Macros tab under Program
            - WebFetch skill.md — check for a dedicated skill and resources matching this task
            - TaskCreate one todo per phase below to track progress

            ### 3. Clarify intention
            - AskUserQuestion: what is the goal? (new program from scratch, add rent-free ATA to existing program, migrate from SPL create_associated_token_account)
            - Summarize findings and wait for user confirmation before implementing

            ### 4. Create plan
            - Based on steps 1–3, draft an implementation plan
            - Follow the guide's step order: Dependencies → Program Module (#[light_program]) → Accounts Struct (#[light_account(init, associated_token::...)])
            - If anything is unclear or ambiguous, loop back to step 3 (AskUserQuestion)
            - Present the plan to the user for approval before proceeding

            ### 5. Implement
            - Add deps if missing: Bash `cargo add light-sdk@0.23 --features anchor,v2,cpi-context` and `cargo add light-sdk-macros@0.23 light-compressible@0.6 anchor-lang@0.31`
            - Follow the guide and the approved plan
            - Write/Edit to create or modify files
            - TaskUpdate to mark each step done

            ### 6. Verify
            - Bash `anchor build`
            - Bash `anchor test` if tests exist
            - TaskUpdate to mark complete

            ### Tools
            - mcp__zkcompression__SearchLightProtocol("<query>") for API details
            - mcp__deepwiki__ask_question("Lightprotocol/light-protocol", "<q>") for architecture
            - Task subagent with Grep/Read/WebFetch for parallel lookups
            - TaskList to check remaining work
            ```
          </Tab>
        </Tabs>
      </Tab>
    </Tabs>
  </Tab>
</Tabs>

## Related Guides

<CardGroup cols={2}>
  <Card title="Transfer interface" icon="arrow-right-left" href="/light-token/cookbook/transfer-interface" horizontal />

  <Card title="Wrap and unwrap" icon="rotate" href="/light-token/cookbook/wrap-unwrap" horizontal />
</CardGroup>

***

## Didn't find what you were looking for?

<Callout type="info">
  Reach out! [Telegram](https://t.me/swen_light) | [email](mailto:support@lightprotocol.com) | [Discord](https://discord.com/invite/7cJ8BhAXhu)
</Callout>
