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);
}
}
}