Build and send a flashloan transaction using the Jupiter Lend SDK.
If your custom logic is compute-heavy, add ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }) (or higher) as the first instruction in your transaction.
The @jup-ag/lend SDK provides helper functions to retrieve the instructions needed to execute a flashloan.To perform a flashloan, construct a transaction where the borrow instruction occurs first, followed by your custom logic (which uses the borrowed funds), and ending with the payback instruction.
Transaction Atomicity
Solana processes the entire list of instructions atomically. If your custom logic fails to return the borrowed amount via paybackIx, the entire transaction reverts and you only pay network fees.
Import the required packages for Solana RPC, Jupiter Lend flashloan SDK, and versioned transaction building.
Copy
Ask AI
import { Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction,} from "@solana/web3.js";import BN from "bn.js";import { getFlashloanIx } from "@jup-ag/lend/flashloan";import fs from "fs";import path from "path";
2
Load Keypair and Initialise Connection
Load the signer and create the RPC connection. Define the asset and borrow amount.
Copy
Ask AI
const KEYPAIR_PATH = "/path/to/your/keypair.json";const RPC_URL = "https://api.mainnet-beta.solana.com";const ASSET = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); // USDCconst BORROW_AMOUNT = new BN(100_000_000); // Amount in base units (e.g. 100 USDC = 100_000_000)function loadKeypair(keypairPath: string): Keypair { const fullPath = path.resolve(keypairPath); const secret = JSON.parse(fs.readFileSync(fullPath, "utf8")); return Keypair.fromSecretKey(new Uint8Array(secret));}const userKeypair = loadKeypair(KEYPAIR_PATH);const connection = new Connection(RPC_URL, { commitment: "confirmed" });const signer = userKeypair.publicKey;
3
Get Flashloan Instructions
Fetch the borrow and payback instructions from the SDK. You borrow and return the same amount with no flashloan fees.
You can also use getFlashBorrowIx and getFlashPaybackIx separately if you need to fetch the instructions independently.
4
Define Custom Logic
Define the instructions that use the borrowed funds. This could be trades, clearing bad debt, collateral swapping, or any custom flashloan logic.
Copy
Ask AI
const customIxs = [ // ... your custom instructions here];
5
Build and Sign Transaction
Assemble the transaction. Order is critical: your custom logic must be placed exactly between the borrow and payback instructions.
Copy
Ask AI
const instructions = [ borrowIx, ...customIxs, paybackIx];const latestBlockhash = await connection.getLatestBlockhash();const message = new TransactionMessage({ payerKey: signer, recentBlockhash: latestBlockhash.blockhash, instructions,}).compileToV0Message(); // Include ALTs here if your custom instructions need themconst transaction = new VersionedTransaction(message);transaction.sign([userKeypair]);