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

# Propose a vault change: runnable example

> Create, finalize, and execute a fee or deposit-asset proposal.

This script proposes either a 1% annual management fee (`10_000n`) or a new deposit asset, then finalizes and executes it in separate runs. Use [Propose a vault change](https://docs.exponent.finance/developer-strategy-vaults/typescript/governance/overview.md) for the workflow.

## Set up

```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 MANAGER_KEYPAIR_PATH="/absolute/path/to/manager.json"
export VAULT_ADDRESS="<vault-address>"
```

The keypair signs and pays transaction fees. Creation requires a manager. Finalization permits any signer; execution requires a vault role for the first 24 hours after `executableAt`, then permits any signer. The program enforces those permissions.

## Script

Save as `propose-vault-change.mts`. The script simulates and submits transactions to the network selected by `RPC_URL`. Set `CHANGE=fee` (default) or `CHANGE=deposit-asset`. The asset option demonstrates the additional validation accounts required at execution. Both options compare the stored actions before executing.

```typescript propose-vault-change.mts theme={null}
import { readFileSync } from "node:fs";
import {
  ExponentVault,
  ProposalStatus,
  SQUADS_PROGRAM_ID,
  coalesceScopeRefreshInstructions,
  createActivateProposalInstruction,
  createAppendProposalActionsInstruction,
  createExecuteProposalInstruction,
  createFinalizeProposalInstruction,
  createInitProposalInstruction,
  fetchActionProposalAccount,
  getKaminoRefreshIxs,
  type ProposalAction,
  proposalActionsCodec,
  vaultSettingsAction,
  resolvePriceIdFromMintToUnderlying,
} from "@exponent-labs/exponent-sdk";
import {
  ComputeBudgetProgram,
  Connection,
  Keypair,
  PublicKey,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
  type TransactionInstruction,
} from "@solana/web3.js";

import {
  getAssociatedTokenAddressSync, createAssociatedTokenAccountIdempotentInstruction,
  TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}

const phase = process.argv[2];
if (!["create", "finalize", "execute"].includes(phase)) {
  throw new Error("Usage: npx tsx propose-vault-change.mts create|finalize|execute");
}
const connection = new Connection(requiredEnv("RPC_URL"), "confirmed");
const manager = Keypair.fromSecretKey(Uint8Array.from(
  JSON.parse(readFileSync(requiredEnv("MANAGER_KEYPAIR_PATH"), "utf8")),
));
const vault = await ExponentVault.load({
  connection, address: new PublicKey(requiredEnv("VAULT_ADDRESS")),
});
const [eventAuthority] = PublicKey.findProgramAddressSync(
  [Buffer.from("__event_authority")], vault.programId,
);
const change = process.env.CHANGE ?? "fee";
if (!["fee", "deposit-asset"].includes(change)) throw new Error("Unknown CHANGE");
const setup: TransactionInstruction[] = [];
const actionAccounts: PublicKey[] = [];
let actions: ProposalAction[];
if (change === "fee") {
  actions = [{
    __kind: "VaultSettingsAction",
    fields: [[vaultSettingsAction("SetManagementFee", { managementFeeBps: 10_000n })]],
  }];
} else {
  const mint = new PublicKey(requiredEnv("ASSET_MINT"));
  const account = await connection.getAccountInfo(mint);
  if (!account || ![TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID].some((p) => p.equals(account.owner))) {
    throw new Error("Unsupported asset mint");
  }
  const prices = await vault.fetcher.fetchExponentPrices();
  const assetPriceId = resolvePriceIdFromMintToUnderlying(prices, mint, vault.state.underlyingMint);
  if (!assetPriceId) throw new Error("No registered price path");
  const tokenSquadsAccount = getAssociatedTokenAddressSync(mint, vault.state.squadsVault, true, account.owner);
  const tokenAccountVault = getAssociatedTokenAddressSync(mint, vault.selfAddress, true, account.owner);
  for (const [owner, ata] of [[vault.state.squadsVault, tokenSquadsAccount], [vault.selfAddress, tokenAccountVault]]) {
    setup.push(createAssociatedTokenAccountIdempotentInstruction(manager.publicKey, ata, owner, mint, account.owner));
  }
  actions = [{ __kind: "VaultSettingsAction", fields: [[vaultSettingsAction("AddTokenEntry", [{
    mint, priceId: assetPriceId, tokenSquadsAccount, tokenAccountVault,
    lastObservedAmount: 0n, forceDeallocatePolicyIds: [],
  }])]] }];
  actionAccounts.push(tokenSquadsAccount, tokenAccountVault);
}

async function send(
  instructions: TransactionInstruction[],
  lookupTableAddresses: PublicKey[] = [],
): Promise<string> {
  const lookupTables = await Promise.all(lookupTableAddresses.map(async (address) => {
    const { value } = await connection.getAddressLookupTable(address);
    if (!value) throw new Error(`Lookup table not found: ${address.toBase58()}`);
    return value;
  }));
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
  const transaction = new VersionedTransaction(new TransactionMessage({
    payerKey: manager.publicKey,
    recentBlockhash: blockhash,
    instructions: [
      ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }),
      ComputeBudgetProgram.requestHeapFrame({ bytes: 256 * 1024 }),
      ...coalesceScopeRefreshInstructions(instructions),
    ],
  }).compileToV0Message(lookupTables));
  transaction.sign([manager]);
  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(
    { signature, blockhash, lastValidBlockHeight }, "confirmed",
  );
  if (confirmation.value.err) throw new Error(JSON.stringify(confirmation.value.err));
  console.log({ signature });
  return signature;
}

async function refreshSequence() {
  await vault.reload();
  const prices = await vault.fetcher.fetchExponentPrices();
  const pricePlan = await vault.buildStrategyVaultPriceRefreshPlan(prices);
  return {
    instructions: coalesceScopeRefreshInstructions([
      ...await getKaminoRefreshIxs(vault),
      ...pricePlan.instructions,
      vault.ixRefreshAum({
        remainingAccounts: await vault.getResolvedAumRemainingAccountMetas(),
      }),
    ]),
    lookupTableAddresses: pricePlan.lookupTableAddresses,
  };
}

if (phase === "create") {
  if (!vault.state.roles.manager.some((key) => key.equals(manager.publicKey))) {
    throw new Error("Creating a proposal requires a vault manager");
  }
  const proposalId = BigInt(vault.state.proposalVoteConfig.nextProposalId.toString());
  const idBytes = Buffer.alloc(8);
  idBytes.writeBigUInt64LE(proposalId);
  const [proposalAddress] = PublicKey.findProgramAddressSync(
    [Buffer.from("proposal"), vault.selfAddress.toBuffer(), idBytes], vault.programId,
  );
  const draftAccounts = {
    payer: manager.publicKey,
    manager: manager.publicKey,
    vault: vault.selfAddress,
    proposal: proposalAddress,
    systemProgram: SystemProgram.programId,
  };
  if (setup.length) await send(setup);
  await send([
    createInitProposalInstruction(draftAccounts, { proposalId }, vault.programId),
    createAppendProposalActionsInstruction(draftAccounts, { actions }, vault.programId),
    createActivateProposalInstruction(
      {
        manager: manager.publicKey,
        vault: vault.selfAddress,
        proposal: proposalAddress,
        mintLp: vault.state.mintLp,
        eventAuthority,
        program: vault.programId,
      },
      { votingPeriodSeconds: null, timelockSeconds: null },
      vault.programId,
    ),
  ]);
  console.log({ proposalAddress: proposalAddress.toBase58(), proposalId: proposalId.toString() });
} else {
  const proposalAddress = new PublicKey(requiredEnv("PROPOSAL_ADDRESS"));
  const { data: proposal } = await fetchActionProposalAccount(connection, proposalAddress);
  if (!proposal.vault.equals(vault.selfAddress)) throw new Error("Proposal belongs to another vault");
  const now = BigInt(Math.floor(Date.now() / 1000));
  const eventAccounts = {
    payer: manager.publicKey,
    vault: vault.selfAddress,
    proposal: proposalAddress,
    eventAuthority,
    program: vault.programId,
  };
  if (phase === "finalize") {
    if (proposal.status !== ProposalStatus.Active || now < proposal.votingEndsAt) {
      throw new Error("Finalize an active proposal after voting ends");
    }
    await send([createFinalizeProposalInstruction(eventAccounts, vault.programId)]);
    const { data: result } = await fetchActionProposalAccount(connection, proposalAddress);
    console.log({ status: ProposalStatus[result.status], executableAt: result.executableAt.toString() });
  } else {
    if (proposal.status !== ProposalStatus.Approved || now < proposal.executableAt) {
      throw new Error("Execute an approved proposal at or after executableAt");
    }
    if (!Buffer.from(proposal.actionData).equals(Buffer.from(proposalActionsCodec.encode(actions)))) {
      throw new Error("Stored actions do not match the selected CHANGE and inputs");
    }
    if (BigInt(vault.state.financials.totalLpPendingWithdrawals.toString()) !== 0n) {
      throw new Error("Fill all pending withdrawal LP before execution");
    }
    const execute = createExecuteProposalInstruction({
      ...eventAccounts,
      squadsSettings: vault.state.squadsSettings,
      squadsProgram: SQUADS_PROGRAM_ID,
      exponentPrices: vault.pda.exponentPrices()[0],
      systemProgram: SystemProgram.programId,
    }, vault.programId);
    execute.keys.push(...await vault.getResolvedAumRemainingAccountMetas(
      actionAccounts.map((pubkey) => ({ pubkey, isSigner: false, isWritable: false })),
    ));
    const before = await refreshSequence();
    await send([...before.instructions, execute], before.lookupTableAddresses);
    const after = await refreshSequence();
    await send(after.instructions, after.lookupTableAddresses);
  }
}
```

## Run each phase

Choose the change, then create the proposal and save its printed address. For a deposit asset, its mint must not already be tracked and its price path must be registered:

```bash theme={null}
export CHANGE="deposit-asset" # Or fee; keep this value for execution.
export ASSET_MINT="<deposit-token-mint>" # Required only for deposit-asset.
```

Creation prepares the two canonical token accounts. Execution supplies those read-only accounts **before** existing-position valuation accounts. The fee option has no action-specific prefix. Policy actions require different Squads account trios, documented in [Policies and proposal actions](https://docs.exponent.finance/developer-strategy-vaults/reference/manage-policies.md#execute-a-policy-proposal).

Create the draft and activate:

```bash theme={null}
npx tsx propose-vault-change.mts create
export PROPOSAL_ADDRESS="<printed-proposal-address>"
```

After voting ends:

```bash theme={null}
npx tsx propose-vault-change.mts finalize
```

If approved, [fill all pending withdrawals](https://docs.exponent.finance/developer-strategy-vaults/fill-withdrawal-requests.md), then run at or after the proposal's stored `executableAt`:

```bash theme={null}
npx tsx propose-vault-change.mts execute
```

The execution phase updates supported price inputs, refreshes AUM, executes the proposal, and refreshes again afterward. Keep any other required oracle or protocol inputs current. If that sequence exceeds one transaction's limits, use the [refresh and bundle guidance](https://docs.exponent.finance/developer-strategy-vaults/refresh-aum.md#when-one-transaction-is-not-enough).

Resolve an uncertain transaction status before retrying a phase. Creating another proposal uses another ID; an already executed proposal cannot execute again.


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