> ## 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.

# Create a vault: runnable example

> Run the vault-creation example with RPC setup, state checks, and retry handling.

Use this script to run the steps in [Create a vault](https://docs.exponent.finance/developer-strategy-vaults/create-vault.md). That page explains the initialization arguments and required accounts.

Every initial manager must be an authorized vault creator. The payer needs SOL for account rent, transaction fees, and the Squads creation fee. The example uses TypeScript and the Exponent SDK.

The script uses SOL accounting, 9 LP decimals, and a 1,000 SOL AUM cap. It assigns one manager, who also pays for creation and owns the fee-treasury LP token account.

## Set up the example

Install the dependencies:

```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
```

Set the RPC endpoint and the path to a manager keypair stored as a JSON byte array:

```bash theme={null}
export RPC_URL="https://your-mainnet-rpc-endpoint"
export MANAGER_KEYPAIR_PATH="/absolute/path/to/manager.json"
```

## Create the vault

Save the following as `create-vault.mts`. Review `settings`, `feeTreasuryOwner`, and `roles` before running it.

The script generates a new vault seed with `randomBytes(8)` when `VAULT_SEED_HEX` is unset.

```typescript create-vault.mts theme={null}
import assert from "node:assert/strict";
import { randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import {
  ExponentVault,
  ExponentVaultsFetcher,
  EXPONENT_VAULTS_PROGRAM_ID,
  LOCAL_ENV,
  SQUADS_PROGRAM_ID,
  findFreshVaultSquadsAccounts,
} from "@exponent-labs/exponent-sdk";
import {
  createAssociatedTokenAccountIdempotentInstruction,
  getAssociatedTokenAddressSync,
  NATIVE_MINT,
} from "@solana/spl-token";
import {
  ComputeBudgetProgram,
  Connection,
  Keypair,
  PublicKey,
  Transaction,
  sendAndConfirmTransaction,
} from "@solana/web3.js";

const settings = {
  accountingMint: NATIVE_MINT,
  maxAum: 1_000_000_000_000n, // 1,000 SOL, with 9 decimals
  managementFeeBps: 10_000n, // 1% annually; 1_000_000 = 100%
  normalWithdrawalFeeBps: 10, // 0.1%; 10_000 = 100%
  reservesShareBp: 1_000, // 10%; 10_000 = 100%
  fastWithdrawalCutBp: 0,
  lpDecimals: 9,
};

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 manager = Keypair.fromSecretKey(
  Uint8Array.from(
    JSON.parse(readFileSync(requiredEnv("MANAGER_KEYPAIR_PATH"), "utf8")),
  ),
);
const programId = new PublicKey(EXPONENT_VAULTS_PROGRAM_ID);
const env = { ...LOCAL_ENV, exponentVaultsProgramId: programId };

const prices = await new ExponentVaultsFetcher(
  connection,
  programId,
).fetchExponentPrices();
assert.ok(
  prices.authorizedVaultCreators.some((key) => key.equals(manager.publicKey)),
  "The manager must be an authorized vault creator",
);

const seedHex = process.env.VAULT_SEED_HEX;
assert.ok(!seedHex || /^[0-9a-f]{16}$/i.test(seedHex), "Invalid VAULT_SEED_HEX");
const seedId = seedHex ? Buffer.from(seedHex, "hex") : randomBytes(8);
const [vaultAddress] = ExponentVault.deriveVaultAddress(seedId, programId);
assert.equal(
  await connection.getAccountInfo(vaultAddress),
  null,
  "This vault already exists; load it instead of initializing it again",
);
const [mintLp] = PublicKey.findProgramAddressSync(
  [Buffer.from("mint_lp"), vaultAddress.toBuffer()],
  programId,
);
const feeTreasuryOwner = manager.publicKey;
const feeTreasury = getAssociatedTokenAddressSync(mintLp, feeTreasuryOwner);
const squads = await findFreshVaultSquadsAccounts(connection, {
  squadsProgram: SQUADS_PROGRAM_ID,
  vaultProgramId: programId,
  lookahead: 1,
});

const initialize = ExponentVault.ixInitializeVault(
  {
    payer: manager.publicKey,
    manager: manager.publicKey,
    mint: settings.accountingMint,
    seedId,
    feeTreasury,
    normalWithdrawalFeeBps: settings.normalWithdrawalFeeBps,
    managementFeeBps: settings.managementFeeBps,
    reservesShareBp: settings.reservesShareBp,
    fastWithdrawalCutBp: settings.fastWithdrawalCutBp,
    tokenEntries: [],
    maxLpSupply: settings.maxAum,
    lpDecimals: settings.lpDecimals,
    roles: {
      manager: [manager.publicKey],
      curator: [],
      allocator: [],
      sentinel: [
        new PublicKey("7me39wqdi9Chh7WeZEmf16v7GASNa88EXj3KZeVK6JHq"),
      ],
    },
    addressLookupTable: PublicKey.default,
    squadsProgram: SQUADS_PROGRAM_ID,
    squadsProgramConfig: squads.squadsProgramConfig,
    squadsTreasury: squads.squadsTreasury,
    squadsSettings: squads.squadsSettings,
    squadsVault: squads.squadsVault,
  },
  env,
);
const transaction = new Transaction().add(
  ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }),
  ComputeBudgetProgram.requestHeapFrame({ bytes: 256 * 1024 }),
  initialize,
  // The LP mint must exist before its fee-treasury account can be created.
  createAssociatedTokenAccountIdempotentInstruction(
    manager.publicKey,
    feeTreasury,
    feeTreasuryOwner,
    mintLp,
  ),
);

// Keep these values if submission or confirmation is interrupted.
console.log({
  vaultAddress: vaultAddress.toBase58(),
  vaultSeed: seedId.toString("hex"),
});
const signature = await sendAndConfirmTransaction(
  connection,
  transaction,
  [manager],
  { commitment: "confirmed" },
);

const vault = await ExponentVault.load({
  connection,
  address: vaultAddress,
  env,
});
const lpSupply = await connection.getTokenSupply(vault.mintLp);

assert.ok(vault.state.underlyingMint.equals(settings.accountingMint));
assert.ok(vault.state.squadsVault.equals(squads.squadsVault));
assert.ok(vault.state.feeTreasury.equals(feeTreasury));
assert.deepEqual(
  vault.state.roles.manager.map((key) => key.toBase58()),
  [manager.publicKey.toBase58()],
);
assert.equal(vault.state.maxAumSupply, settings.maxAum);
assert.equal(vault.state.normalWithdrawalCutBp, settings.normalWithdrawalFeeBps);
assert.equal(vault.state.reservesConfig.managementFeeBps, settings.managementFeeBps);
assert.equal(vault.state.reservesConfig.reservesShareBp, settings.reservesShareBp);
assert.equal(vault.state.tokenEntries.length, 0);
assert.equal(vault.state.strategyPositions.length, 0);
assert.equal(vault.getTotalAum(), 0n);
assert.equal(lpSupply.value.amount, "0");
assert.equal(lpSupply.value.decimals, settings.lpDecimals);

console.log({
  signature,
  vaultAddress: vault.selfAddress.toBase58(),
  squadsVault: vault.state.squadsVault.toBase58(),
  mintLp: vault.mintLp.toBase58(),
  feeTreasury: vault.state.feeTreasury.toBase58(),
  aum: vault.getTotalAum().toString(),
  lpSupply: lpSupply.value.amount,
  votingPeriodSeconds: vault.state.proposalVoteConfig.defaultVotingPeriodSeconds,
  timelockSeconds: vault.state.proposalVoteConfig.defaultTimelockSeconds,
  rejectionThreshold: vault.state.proposalVoteConfig.rejectionThresholdBps.toString(),
});
```

Submit the creation transaction:

```bash theme={null}
npx tsx create-vault.mts
```

This submits a transaction on Solana mainnet. The output includes the transaction signature, vault address, seed, LP mint, and stored voting configuration. The assertions check the example's expected settings and empty state.

## Retry an interrupted or failed transaction

If submission or confirmation times out, check the original transaction's status before retrying.

To preserve the vault address, reuse the seed printed before submission:

```bash theme={null}
VAULT_SEED_HEX="<printed vaultSeed>" npx tsx create-vault.mts
```

The example stops if that vault already exists. If the Squads account index changes before execution, rebuilding with the same seed obtains fresh Squads accounts while preserving the vault address. A run without `VAULT_SEED_HEX` generates a new vault address.


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