lana-pubkey = "2.1"
solana-instruction = "2.1"
solana-sdk = "~2.3"
solana-client = "~2.3"
spl-token = "7"
spl-associated-token-account = "6"
```
<Note>
`klend-interface` is a lightweight Rust instruction builder that creates `Vec<Instruction>` with required refresh instructions prepended automatically.
</Note>
</Step>
<Step>
### Set Up RPC Client
```rust theme={null}
use solana_client::rpc_client::RpcClient;
use solana_sdk::signer::keypair::read_keypair_file;
use solana_sdk::signer::Signer;
let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com");
let signer = read_keypair_file("/path/to/your/keypair.json")
.expect("Failed to read keypair file");
let owner = signer.pubkey();
```
</Step>
<Step>
### Derive PDAs and Build Instruction
Create the `init_user_metadata` instruction linking the user to a referrer without requiring a deposit.
```rust theme={null}
use klend_interface::instructions::referrer::{
init_user_metadata,
InitUserMetadataAccounts,
};
use klend_interface::pda;
use klend_interface::KLEND_PROGRAM_ID;
use solana_pubkey::Pubkey;
use std::str::FromStr;
let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCfqY").unwrap();
// Derive PDAs
let (user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &owner);
let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer);
// Your user's address lookup table (created during onboarding)
let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap();
let ix = init_user_metadata(
InitUserMetadataAccounts {
owner,
fee_payer: owner,
user_metadata,
referrer_user_metadata: Some(referrer_user_metadata),
},
user_lookup_table,
);
```
<Warning>
Once UserMetadata is created with a referrer, the referrer cannot be changed. Always check if UserMetadata exists before attempting to create it.
</Warning>
</Step>
<Step>
### Send Transaction
```rust theme={null}
use solana_sdk::transaction::Transaction;
use solana_sdk::message::Message;
let message = Message::new(&[ix], Some(&owner));
let recent_blockhash = rpc_client.get_latest_blockhash()?;
let tx = Transaction::new(&[&signer], message, recent_blockhash);
let signature = rpc_client.send_and_confirm_transaction(&tx)?;
println!("UserMetadata created with referrer! Signature: {signature}");
```
</Step>
</Steps>
</Tab>
</Tabs>
<Accordion title="When to Use This vs Deposit with Referral">
**Use this method when:**
* You want to link a referrer to a user before they make their first deposit
* You're creating UserMetadata as a separate step from deposit operations
* You have a simpler flow that doesn't require immediate deposit
**Use Deposit with Referral when:**
* You want to combine UserMetadata creation and deposit in a single transaction
* The user is ready to deposit immediately
* You want to minimize the number of transactions
</Accordion>
# Referral Code Setup
Source: https://kamino.com/docs/build/developers/borrow/operations/advanced-concepts/referrer-setup
Set up referrer state with a unique referral code
## How Referral Codes Work
Kamino's referral system allows referrers to earn commission from the borrowing activity of referred users. Each referrer creates a unique referral code that can be shared publicly without revealing a wallet address, providing a user-friendly way to distribute referral codes.
<Note>In the SDK, the `shortUrl` field represents the referral code.</Note>
<Tabs>
<Tab title="TypeScript">
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building.
```typescript theme={null}
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
address,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
} from '@solana/kit';
import {
getInitReferrerStateAndShortUrlIxs,
getReferrerForShortUrl,
PROGRAM_ID,
} from '@kamino-finance/klend-sdk';
import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js';
```
</Step>
<Step>
### Initialize RPC
Load the keypair and initialize RPC connections.
```typescript theme={null}
const KEYPAIR_FILE = '/path/to/your/keypair.json';
const signer = await parseKeypairFile(KEYPAIR_FILE);
const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com');
const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com');
```
</Step>
<Step>
### Create Referrer State with Short URL
Generate a unique short URL and create the referrer state initialization instruction.
```typescript theme={null}
const shortUrl = `ref-${Date.now()}`;
const initReferrerIx = await getInitReferrerStateAndShortUrlIxs({
referrer: signer,
shortUrl,
programId: PROGRAM_ID,
});
```
<Note>
The short URL must be unique, contain a maximum of 32 characters, and use only ASCII alphanumeric characters plus underscore and hyphen.
</Note>
</Step>
<Step>
### Send Referrer Setup Transaction
Build and send the transaction to initialize the referrer state on-chain.
```typescript theme={null}
const { value: setupBlockhash } = await rpc
.getLatestBlockhash({ commitment: 'finalized' })
.send();
const setupTx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx),
(tx) => appendTransactionMessageInstructions([initReferrerIx], tx)
);
const setupSigned = await signTransactionMessageWithSigners(setupTx);
const setupSignature = getSignatureFromTransaction(setupSigned);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(setupSigned, {
commitment: 'confirmed',
skipPreflight: true,
});
console.log(`Referrer setup successful! Signature: ${setupSignature}`);
```
</Step>
<Step>
### Verify Short URL Resolution
Confirm that the short URL correctly resolves to the referrer wallet address.
```typescript theme={null}
const lookedUpReferrer = await getReferrerForShortUrl(rpc, shortUrl, PROGRAM_ID);
console.log(`Short URL "${shortUrl}" resolves to: ${lookedUpReferrer}`);
```
<Check>
Referrer setup complete. The short URL is active and can be shared with users to establish referral relationships.
</Check>
</Step>
</Steps>
</Tab>
<Tab title="Rust">
<Steps>
<Step>
### Add Dependencies
```toml theme={null}
[dependencies]
klend-interface = "0.1.0"
solana-pubkey = "2.1"
solana-instruction = "2.1"
solana-sdk = "~2.3"
solana-client = "~2.3"
spl-token = "7"
spl-associated-token-account = "6"
```
<Note>
`klend-interface` is a lightweight Rust instruction builder that creates `Vec<Instruction>` with required refresh instructions prepended automatically.
</Note>
</Step>
<Step>
### Set Up RPC Client
```rust theme={null}
use solana_client::rpc_client::RpcClient;
use solana_sdk::signer::keypair::read_keypair_file;
use solana_sdk::signer::Signer;
let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com");
let signer = read_keypair_file("/path/to/your/keypair.json")
.expect("Failed to read keypair file");
let owner = signer.pubkey();
```
</Step>
<Step>
### Derive PDAs and Build Instruction
```rust theme={null}
use klend_interface::instructions::referrer::{
init_referrer_state_and_short_url,
InitReferrerStateAndShortUrlAccounts,
};
use klend_interface::pda;
use klend_interface::KLEND_PROGRAM_ID;
use solana_pubkey::Pubkey;
let referrer = signer.pubkey();
let short_url = format!("ref-{}", std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs());
// Derive required PDAs
let (referrer_state, _) = pda::referrer_state(&KLEND_PROGRAM_ID, &referrer);
let (referrer_short_url, _) = pda::referrer_short_url(&KLEND_PROGRAM_ID, &short_url);
let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer);
let ix = init_referrer_state_and_short_url(
InitReferrerStateAndShortUrlAccounts {
referrer,
referrer_state,
referrer_short_url,
referrer_user_metadata,
},
short_url.clone(),
);
```
<Note>
The short URL must be unique, contain a maximum of 32 characters, and use only ASCII alphanumeric characters plus underscore and hyphen.
</Note>
</Step>
<Step>
### Send Transaction
```rust theme={null}
use solana_sdk::transaction::Transaction;
use solana_sdk::message::Message;
let message = Message::new(&[ix], Some(&referrer));
let recent_blockhash = rpc_client.get_latest_blockhash()?;
let tx = Transaction::new(&[&signer], message, recent_blockhash);
let signature = rpc_client.send_and_confirm_transaction(&tx)?;
println!("Referrer setup successful! Short URL: {short_url}");
println!("Signature: {signature}");
```
</Step>
</Steps>
</Tab>
</Tabs>
# Repay with Collateral using KSwap
Source: https://kamino.com/docs/build/developers/borrow/operations/advanced-concepts/repay-with-collateral-kswap
Reduce debt by converting collateral using flash loans in a single atomic transaction
<p>Repay with collateral reduces debt in a single atomic transaction by converting collateral into the debt token without requiring additional funds. The protocol flash borrows the debt token, repays the debt, withdraws the freed collateral, swaps it to the debt token via KSwap, and repays the flash loan—all in one transaction.</p>
## Repay with Collateral using KSwap
Reduce debt in a single transaction by converting collateral using a flash loan and KSwap.
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication, Kamino SDK operations, KSwap routing, and transaction building.
```typescript theme={null}
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
address,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
none,
compressTransactionMessageUsingAddressLookupTables,
} from '@solana/kit';
import type { Address } from '@solana/kit';
import {
KaminoMarket,
MultiplyObligation,
PROGRAM_ID,
parseKeypairFile,
getRepayWithCollIxs,
getUserLutAddressAndSetupIxs,
getScopeRefreshIxForObligationAndReserves,
getComputeBudgetAndPriorityFeeIxs,
lamportsToNumberDecimal,
simulateTx,
DEFAULT_RECENT_SLOT_DURATION_MS,
} from '@kamino-finance/klend-sdk';
import { KswapSdk } from '@kamino-finance/kswap-sdk';
import { Scope } from '@kamino-finance/scope-sdk';
import Decimal from 'decimal.js';
import { getKswapQuoter, getKswapSwapper } from './kswap_utils.js';
import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table';
```
</Step>
<Step>
### Load Configuration and Initialize SDKs
Load the keypair, initialize RPC connections, and set up the market and SDKs.
```typescript theme={null}
const KEYPAIR_FILE = '/path/to/your/keypair.json';
const CDN_ENDPOINT = 'https://cdn.kamino.finance';
const signer = await parseKeypairFile(KEYPAIR_FILE);
const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com');
const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com');
const marketPubkey = address('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market
const debtTokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC
const XSTOCKS_MARKET_LUT = address('8ofreL6hKfEet1DnhHVGvCTnSdz4pg85PpbuCUHnEcKm');
const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS);
const scope = new Scope('mainnet-beta', rpc);
const kswapSdk = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions);
```
</Step>
<Step>
### Find Collateral Reserve
Dynamically discover the collateral token mint by searching the market reserves by symbol.
```typescript theme={null}
const tslaReserve = Array.from(market!.reserves.values()).find((reserve) => reserve.symbol === 'TSLAx');
if (!tslaReserve) {
console.log('TSLAx reserve not found in xStocks market');
}
const collTokenMint = tslaReserve.getLiquidityMint();
```
</Step>
<Step>
### Fetch Multiply Lookup Tables
Retrieve the multiply-specific lookup tables from Kamino's CDN.
```typescript theme={null}
const kaminoResourcesResponse = await fetch(`${CDN_ENDPOINT}/resources.json`);
const kaminoResourcesData = await kaminoResourcesResponse.json();
const kaminoResources = kaminoResourcesData['mainnet-beta'];
const multiplyColPairs = kaminoResources.multiplyLUTsPairs[collTokenMint] || {};
const multiplyLut = multiplyColPairs[debtTokenMint] || [];
const multiplyLutKeys = multiplyLut.map((lut: string) => address(lut));
```
</Step>
<Step>
### Configure Repay Parameters
Set the amount of debt to repay using collateral and the slippage tolerance.
```typescript theme={null}
const repayAmount = new Decimal(5); // $5 worth of debt to repay using collateral
const slippageBps = 100; // 1% slippage
```
<Note>
Some assets may require higher slippage than others.
</Note>
</Step>
<Step>
### Setup Lookup Tables
Initialize the user's lookup table and execute any required setup transactions.
```typescript theme={null}
const multiplyMints: { coll: Address; debt: Address }[] = [{ coll: collTokenMint, debt: debtTokenMint }];
const leverageMints: { coll: Address; debt: Address }[] = [];
const [userLookupTable, setupTxsIxs] = await getUserLutAddressAndSetupIxs(
market!,
signer,
none(),
true,
multiplyMints,
leverageMints
);
for (const setupIxs of setupTxsIxs) {
const { value: setupBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send();
const setupTx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx),
(tx) => appendTransactionMessageInstructions(setupIxs, tx)
);
const signedSetupTx = await signTransactionMessageWithSigners(setupTx);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedSetupTx, {
commitment: 'confirmed',
skipPreflight: true,
});
await new Promise((resolve) => setTimeout(resolve, 2000));
}
```
<Note>
Setup transactions extend the lookup table with addresses specific to the position. This is a one-time operation per collateral/debt pair.
</Note>
</Step>
<Step>
### Fetch Existing Obligation
Retrieve the current obligation and display position details.
```typescript theme={null}
const currentSlot = await rpc.getSlot().send();
const collTokenReserve = market!.getReserveByMint(collTokenMint)!;
const debtTokenReserve = market!.getReserveByMint(debtTokenMint)!;
const obligationType = new MultiplyObligation(collTokenMint, debtTokenMint, PROGRAM_ID);
const obligationAddress = await obligationType.toPda(market!.getAddress(), signer.address);
const obligation = await market!.getObligationByAddress(obligationAddress);
if (!obligation) {
console.log('No obligation found. You must have an active position to repay with collateral.');
}
const deposited = lamportsToNumberDecimal(
Array.from(obligation.deposits.values())[0]?.amount.toString() || '0',
collTokenReserve.state.liquidity.mintDecimals.toNumber()
);
const borrowed = lamportsToNumberDecimal(
Array.from(obligation.borrows.values())[0]?.amount.toString() || '0',
debtTokenReserve.state.liquidity.mintDecimals.toNumber()
);
console.log(`Current position: ${deposited.toString()} TSLAx deposited, ${borrowed.toString()} USDC borrowed`);
```
<Note>
This example uses `MultiplyObligation`. For standard borrow positions, use `VanillaObligation` instead.
</Note>
</Step>
<Step>
### Build Repay Instructions
Generate repay with collateral instructions with scope price refresh and compute budget.
```typescript theme={null}
const scopeConfiguration = { scope, scopeConfigurations: await scope.getAllConfigurations() };
const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves(
market!,
collTokenReserve,
debtTokenReserve,
obligation,
scopeConfiguration
);
const computeIxs = getComputeBudgetAndPriorityFeeIxs(1_400_000, new Decimal(500000));
const repayWithCollRoutes = await getRepayWithCollIxs({
owner: signer,
kaminoMarket: market!,
debtTokenMint: debtTokenMint,
collTokenMint: collTokenMint,
obligation: obligation,
referrer: none(),
currentSlot,
repayAmount,
isClosingPosition: false,
budgetAndPriorityFeeIxs: computeIxs,
scopeRefreshIx,
quoter: getKswapQuoter(kswapSdk, signer.address, slippageBps, collTokenReserve, debtTokenReserve),
swapper: getKswapSwapper(kswapSdk, signer.address, slippageBps),
useV2Ixs: true,
});
```
</Step>
<Step>
### Simulate Routes
Prepare lookup tables, simulate all routes to filter out failures.
```typescript theme={null}
const klendLookupTableKeys: Address[] = [];
klendLookupTableKeys.push(userLookupTable);
klendLookupTableKeys.push(...multiplyLutKeys);
klendLookupTableKeys.push(XSTOCKS_MARKET_LUT);
const klendLutAccounts = await fetchAllAddressLookupTable(rpc, klendLookupTableKeys);
const simulationResults = await Promise.all(
repayWithCollRoutes.map(async (route) => {
const lookupTables = route.lookupTables;
lookupTables.push(...klendLutAccounts);
const simulation = await simulateTx(rpc, signer.address, route.ixs, lookupTables).catch(() => undefined);
if (!simulation || simulation.value.err) {
return undefined;
}
return {
ixs: route.ixs,
luts: lookupTables.map((l) => l.address),
routeOutput: route.quote!,
swapInputs: route.swapInputs,
};
})
);
const passingSimulations = simulationResults.filter((tx) => tx !== undefined);
```
</Step>
<Step>
### Select Best Route
Compare passing routes by price and select the best one.
```typescript theme={null}
const bestRoute =
passingSimulations.length > 0
? passingSimulations.reduce((best, current) => {
const inputMintReserve = market!.getReserveByMint(best.swapInputs.inputMint)!;
const outputMintReserve = market!.getReserveByMint(best.swapInputs.outputMint)!;
const bestPrice = new Decimal(best.routeOutput.amountsExactIn.amountOutGuaranteed.toString())
.div(outputMintReserve.getMintFactor())
.div(new Decimal(best.routeOutput.amountsExactIn.amountIn.toString()).div(inputMintReserve.getMintFactor()));
const currentPrice = new Decimal(current.routeOutput.amountsExactIn.amountOutGuaranteed.toString())
.div(outputMintReserve.getMintFactor())
.div(
new Decimal(current.routeOutput.amountsExactIn.amountIn.toString()).div(inputMintReserve.getMintFactor())
);
return bestPrice.greaterThan(currentPrice) ? best : current;
})
: (() => {
const lookupTables = repayWithCollRoutes[0].lookupTables;
lookupTables.push(...klendLutAccounts);
return { ixs: repayWithCollRoutes[0].ixs, luts: lookupTables.map((l) => l.address) };
})();
if (!bestRoute) {
console.log('No route found');
}
```
</Step>
<Step>
### Build, Sign, and Send Transaction
Wait briefly to avoid rate limiting, get a fresh blockhash, compress the transaction with LUTs, and send it.
```typescript theme={null}
await new Promise((resolve) => setTimeout(resolve, 2000));
const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send();
const lutsByAddress: Record<Address, Address[]> = {};
const bestRouteLutAccounts = await fetchAllAddressLookupTable(rpc, bestRoute.luts || []);
for (const acc of bestRouteLutAccounts) {
lutsByAddress[acc.address] = acc.data.addresses;
}
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
(tx) => appendTransactionMessageInstructions(bestRoute.ixs, tx),
(tx) => setTransactionMessageFeePayerSigner(signer, 프로젝트로 돌아가기