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

# Queued withdrawal

> Queue as a depositor, fill as a manager, then claim the recorded payouts.

This script handles an **ordinary** withdrawal request in separate runs. Queue and claim use the depositor keypair; fill uses an authorized manager or allocator with the installed fill policy. Governance OptOut requests use the separate [proposal-aware fill contract](https://docs.exponent.finance/developer-strategy-vaults/typescript/vault-operations/overview.md#instruction-builder).

## Set up

Use a funded vault with configured prices and enough payout liquidity for a full fill. Queueing requires the depositor's LP ATA. The program enforces claim timing and cancellation cooldown.

```bash theme={null}
npm install @exponent-labs/exponent-sdk @solana/web3.js@1.98.4 @solana/spl-token@0.4.8
npm install --save-dev typescript tsx @types/node
export RPC_URL="https://your-mainnet-rpc-endpoint"
export VAULT_ADDRESS="<vault-address>"
export SIGNER_KEYPAIR_PATH="/absolute/path/to/depositor.json"
```

## Script

Save as `queued-withdrawal.mts`. Running a phase simulates and **submits** transactions. The manual claim sender targets vaults whose refresh and claim fit one transaction with the supplied price-plan tables; larger accounts need the [refresh and bundle pattern](https://docs.exponent.finance/developer-strategy-vaults/refresh-aum.md#when-one-transaction-is-not-enough), including any additional vault lookup tables.

```typescript queued-withdrawal.mts theme={null}
import {
  ExponentVault, VaultTransactionBuilder, managerAction,
  getKaminoRefreshIxs, coalesceScopeRefreshInstructions,
} from "@exponent-labs/exponent-sdk";
import {
  ComputeBudgetProgram, TransactionMessage, VersionedTransaction,
  type TransactionInstruction, type Signer,
} from "@solana/web3.js";
import {
  TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID,
  getAssociatedTokenAddressSync, createAssociatedTokenAccountIdempotentInstruction,
} from "@solana/spl-token";
import { readFileSync } from "node:fs";
import {
  Connection, Keypair, PublicKey,
} from "@solana/web3.js";

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const connection = new Connection(requiredEnv("RPC_URL"), "confirmed");
const signer = Keypair.fromSecretKey(Uint8Array.from(
  JSON.parse(readFileSync(requiredEnv("SIGNER_KEYPAIR_PATH"), "utf8")),
));

const phase = process.argv[2];
if (!["queue", "fill", "claim", "cancel"].includes(phase)) {
  throw new Error("Usage: npx tsx queued-withdrawal.mts queue|fill|claim|cancel");
}
const vault = await ExponentVault.load({
  connection, address: new PublicKey(requiredEnv("VAULT_ADDRESS")),
});

async function send(
  instructions: TransactionInstruction[],
  extraSigners: Signer[] = [],
  lookupTableAddresses: PublicKey[] = [],
) {
  const tables = await Promise.all(lookupTableAddresses.map(async (address) => {
    const { value } = await connection.getAddressLookupTable(address);
    if (!value) throw new Error(`Missing lookup table: ${address.toBase58()}`);
    return value;
  }));
  const latest = await connection.getLatestBlockhash("confirmed");
  const transaction = new VersionedTransaction(new TransactionMessage({
    payerKey: signer.publicKey, recentBlockhash: latest.blockhash,
    instructions: [
      ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }),
      ComputeBudgetProgram.requestHeapFrame({ bytes: 256 * 1024 }),
      ...coalesceScopeRefreshInstructions(instructions),
    ],
  }).compileToV0Message(tables));
  transaction.sign([signer, ...extraSigners]);
  const simulation = await connection.simulateTransaction(transaction);
  if (simulation.value.err) throw new Error(JSON.stringify(simulation.value));
  const signature = await connection.sendRawTransaction(transaction.serialize());
  const confirmation = await connection.confirmTransaction({ ...latest, signature }, "confirmed");
  if (confirmation.value.err) throw new Error(JSON.stringify(confirmation.value.err));
  console.log({ signature });
}

if (phase === "queue") {
  const amount = requiredEnv("LP_ATOMIC");
  if (!/^[1-9][0-9]*$/.test(amount)) throw new Error("LP_ATOMIC must be positive");
  const { ix, withdrawalKeypair } = vault.ixQueueWithdrawal({
    depositor: signer.publicKey, lpAmount: BigInt(amount),
  });
  console.log({ withdrawalAddress: withdrawalKeypair.publicKey.toBase58() });
  await send([ix], [withdrawalKeypair]);
} else {
  const withdrawalAddress = new PublicKey(requiredEnv("WITHDRAWAL_ADDRESS"));
  const request = await vault.fetchWithdrawalAccount(withdrawalAddress);
  if (!request.vault.equals(vault.selfAddress)) throw new Error("Request belongs to another vault");
  if (phase === "fill") {
    const plan = await VaultTransactionBuilder
      .create({ vault, connection, signer: signer.publicKey })
      .addActions([managerAction.fillWithdrawal({
        withdrawalAccount: withdrawalAddress, amount: { kind: "full" },
      })])
      .build();
    console.log((await plan.send({ signers: [signer] })).signatures);
  } else {
    if (!request.owner.equals(signer.publicKey)) throw new Error("Use the original depositor");
    const lpAta = getAssociatedTokenAddressSync(vault.state.mintLp, signer.publicKey);
    const setup = [createAssociatedTokenAccountIdempotentInstruction(
      signer.publicKey, lpAta, signer.publicKey, vault.state.mintLp,
    )];
    if (phase === "cancel") {
      if (request.fills.length !== 0) throw new Error("Cannot cancel after any fill");
      await send([...setup, vault.ixCancelWithdrawal({
        owner: signer.publicKey, withdrawalAccount: withdrawalAddress,
      })]);
    } else {
      if (request.fills.length === 0) throw new Error("Nothing has been filled yet");
      const tokenAccountPairs = [];
      // Preserve request.fills order, including mints no longer in tokenEntries.
      for (const fill of request.fills) {
        const mint = await connection.getAccountInfo(fill.mint);
        if (!mint || ![TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID].some((p) => p.equals(mint.owner))) {
          throw new Error("Unsupported payout mint");
        }
        const destination = getAssociatedTokenAddressSync(fill.mint, signer.publicKey, false, mint.owner);
        setup.push(createAssociatedTokenAccountIdempotentInstruction(
          signer.publicKey, destination, signer.publicKey, fill.mint, mint.owner,
        ));
        tokenAccountPairs.push({ tokenSrc: fill.sourceTokenAccount, mint: fill.mint, tokenDst: destination });
      }
      const prices = await vault.fetcher.fetchExponentPrices();
      const pricePlan = await vault.buildStrategyVaultPriceRefreshPlan(prices);
      const claim = await vault.ixExecuteWithdrawalWithResolvedAumAccounts({
        owner: signer.publicKey, withdrawalAccount: withdrawalAddress, tokenAccountPairs,
      });
      await send([
        ...setup, ...await getKaminoRefreshIxs(vault), ...pricePlan.instructions, claim,
      ], [], pricePlan.lookupTableAddresses);
    }
  }
}

```

## Run each phase

```bash theme={null}
export LP_ATOMIC="1000000"
npx tsx queued-withdrawal.mts queue
export WITHDRAWAL_ADDRESS="<printed-request-address>"
export SIGNER_KEYPAIR_PATH="/absolute/path/to/manager.json"
npx tsx queued-withdrawal.mts fill
# After the request's claim time:
export SIGNER_KEYPAIR_PATH="/absolute/path/to/depositor.json"
npx tsx queued-withdrawal.mts claim
```

Alternatively, before any fill and after cancellation cooldown, the depositor can run `cancel`. A partial fill can be claimed once: it pays every recorded fill, returns unfilled LP, and closes the request. Resolve uncertain confirmation before retrying any phase.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.