tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => compressTransactionMessageUsingAddressLookupTables(tx, lutsByAddress)
);
const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
const signature = getSignatureFromTransaction(signedTransaction);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, {
commitment: 'processed',
preflightCommitment: 'processed',
skipPreflight: true,
});
console.log(`Repay with collateral successful! Sold TSLAx collateral to repay ${repayAmount.toString()} USDC debt.`);
console.log(`Transaction signature: ${signature}`);
```
<Check>
The repay with collateral transaction is complete. Collateral was sold to repay debt without requiring external funds.
</Check>
</Step>
</Steps>
## Helper Functions
The tutorial requires KSwap helper functions for quote retrieval and swap execution.
<AccordionGroup>
<Accordion title="kswap_utils.ts">
```typescript theme={null}
import BN from 'bn.js';
import { KaminoReserve } from '@kamino-finance/klend-sdk';
import type { SwapInputs, SwapQuote, SwapIxs, SwapIxsProvider, SwapQuoteProvider } from '@kamino-finance/klend-sdk';
import { KswapSdk } from '@kamino-finance/kswap-sdk/dist';
import type { RouteOutput, RouteParams, RouterType } from '@kamino-finance/kswap-sdk/dist';
import Decimal from 'decimal.js';
import type { Address } from '@solana/kit';
import { PublicKey } from '@solana/web3.js';
function toLegacyPublicKey(address: Address) {
return new PublicKey(address.toString());
}
export const KSWAP_API = 'https://api.kamino.finance/kswap';
const ALLOWED_ROUTERS: RouterType[] = ['dflow', 'jupiter', 'jupiterU', 'okx', 'jupiterLite'];
export async function getTokenPriceFromJupWithFallback(
kswapSdk: KswapSdk,
inputMint: Address,
outputMint: Address
): Promise<number> {
const params = {
ids: inputMint.toString(),
vsToken: outputMint.toString(),
};
const res = await kswapSdk.getJupiterPriceWithFallback(params);
return Number(res[inputMint.toString()]?.usdPrice || 0);
}
export async function getTokenPriceFromBirdeye(
kswapSdk: KswapSdk,
inputMint: Address,
outputMint: Address
): Promise<number> {
const prices = await kswapSdk.getBatchTokenPrices([toLegacyPublicKey(inputMint), toLegacyPublicKey(outputMint)]);
return prices[inputMint.toString()] / prices[outputMint.toString()];
}
export function getKswapQuoter(
kswapSdk: KswapSdk,
executor: Address,
slippageBps: number,
inputMintReserve: KaminoReserve,
outputMintReserve: KaminoReserve
): SwapQuoteProvider<RouteOutput> {
const quoter: SwapQuoteProvider<RouteOutput> = async (
inputs: SwapInputs,
klendAccounts: Array<Address>
): Promise<SwapQuote<RouteOutput>> => {
const routeParams: RouteParams = {
executor: toLegacyPublicKey(executor),
tokenIn: toLegacyPublicKey(inputs.inputMint),
tokenOut: toLegacyPublicKey(inputs.outputMint),
amount: new BN(inputs.inputAmountLamports.toDP(0).toString()),
maxSlippageBps: slippageBps,
wrapAndUnwrapSol: false,
swapType: 'exactIn',
routerTypes: ALLOWED_ROUTERS,
includeRfq: false,
includeLimoLogs: false,
};
const routeOutputs = await kswapSdk.getAllRoutes(routeParams);
const bestRoute = routeOutputs.routes.reduce((best, current) => {
const inAmountBest = new Decimal(best.amountsExactIn.amountIn.toString()).div(inputMintReserve.getMintFactor());
const minAmountOutBest = new Decimal(best.amountsExactIn.amountOutGuaranteed.toString()).div(
outputMintReserve.getMintFactor()
);
const priceAInBBest = minAmountOutBest.div(inAmountBest);
const inAmountCurrent = new Decimal(current.amountsExactIn.amountIn.toString()).div(
inputMintReserve.getMintFactor()
);
const minAmountOutCurrent = new Decimal(current.amountsExactIn.amountOutGuaranteed.toString()).div(
outputMintReserve.getMintFactor()
);
const priceAInBCurrent = minAmountOutCurrent.div(inAmountCurrent);
return priceAInBBest.greaterThan(priceAInBCurrent) ? best : current;
});
const inAmountBest = new Decimal(bestRoute.amountsExactIn.amountIn.toString()).div(
inputMintReserve.getMintFactor()
);
const minAmountOutBest = new Decimal(bestRoute.amountsExactIn.amountOutGuaranteed.toString()).div(
outputMintReserve.getMintFactor()
);
const priceAInBBest = minAmountOutBest.div(inAmountBest);
return {
priceAInB: priceAInBBest,
quoteResponse: bestRoute,
};
};
return quoter;
}
export function getKswapSwapper(
kswapSdk: KswapSdk,
executor: Address,
slippageBps: number
): SwapIxsProvider<RouteOutput> {
const swapper: SwapIxsProvider<RouteOutput> = async (
inputs: SwapInputs,
klendAccounts: Array<Address>,
quote: SwapQuote<RouteOutput>
): Promise<Array<SwapIxs<RouteOutput>>> => {
const routeParams: RouteParams = {
executor: toLegacyPublicKey(executor),
tokenIn: toLegacyPublicKey(inputs.inputMint),
tokenOut: toLegacyPublicKey(inputs.outputMint),
amount: new BN(inputs.inputAmountLamports.toString()),
maxSlippageBps: slippageBps,
wrapAndUnwrapSol: false,
swapType: 'exactIn',
routerTypes: ALLOWED_ROUTERS,
includeRfq: false,
includeLimoLogs: false,
};
const routeOutputs = await kswapSdk.getAllRoutes(routeParams);
return routeOutputs.routes.map((routeOutput) => {
const inAmount = new Decimal(routeOutput.amountsExactIn.amountIn.toString()).div(
new Decimal(10).pow(routeOutput.inputTokenDecimals!)
);
const minAmountOut = new Decimal(routeOutput.amountsExactIn.amountOutGuaranteed.toString()).div(
new Decimal(10).pow(routeOutput.outputTokenDecimals!)
);
const priceAInB = minAmountOut.div(inAmount);
const allSwapIxs = [
...(routeOutput.instructions?.createInAtaIxs || []),
...(routeOutput.instructions?.wrapSolIxs || []),
...(routeOutput.instructions?.swapIxs || []),
...(routeOutput.instructions?.unwrapSolIxs || []),
...(routeOutput.instructions?.createOutAtaIxs || []),
];
return {
preActionIxs: [],
swapIxs: allSwapIxs,
lookupTables: routeOutput.lookupTableAccounts || [],
quote: {
priceAInB: new Decimal(priceAInB),
quoteResponse: routeOutput,
},
};
});
};
return swapper;
}
```
</Accordion>
</AccordionGroup>
# Withdraw Referrer Fees
Source: https://kamino.com/docs/build/developers/borrow/operations/advanced-concepts/withdraw-referrer-fees
Withdraw accumulated referral fees from borrowing activity
## Withdraw Referrer Fees
<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 { KaminoMarket, KaminoAction, parseKeypairFile } from '@kamino-finance/klend-sdk';
```
</Step>
<Step>
### Load Market and Initialize RPC
Load the keypair, initialize RPC connections, and load the Kamino market.
```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');
const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF');
const market = await KaminoMarket.load(rpc, marketPubkey, 400);
const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
```
</Step>
<Step>
### Check Accumulated Fees
Check all accumulated fees across all tokens.
```typescript theme={null}
const allFees = await market!.getAllReferrerFeesCumulative(signer.address);
for (const [mint, fees] of allFees.entries()) {
console.log(`Token ${mint}: ${fees.toString()}`);
}
```
Check fees for specific reserve (USDC).
```typescript theme={null}
const usdcReserve = market!.getReserveByMint(usdcMint);
if (usdcReserve) {
const cumulativeFees = await market!.getReferrerFeesCumulativeForReserve(signer.address, usdcReserve);
const unclaimedFees = await market!.getReferrerFeesUnclaimedForReserve(signer.address, usdcReserve);
console.log(`USDC Cumulative: ${cumulativeFees.toString()}`);
console.log(`USDC Unclaimed: ${unclaimedFees.toString()}`);
}
```
</Step>
<Step>
### Build Withdraw Instructions
Generate instructions to withdraw accumulated referral fees for USDC.
```typescript theme={null}
const withdrawAction = await KaminoAction.buildWithdrawReferrerFeeTxns(signer, usdcMint, market!);
const instructions = [...withdrawAction.setupIxs, ...withdrawAction.lendingIxs, ...withdrawAction.cleanupIxs];
```
</Step>
<Step>
### Send Withdraw Transaction
Fetch the latest blockhash and build the transaction message.
```typescript theme={null}
const { value: withdrawBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send();
const withdrawTx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(withdrawBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
```
Sign and send the transaction.
```typescript theme={null}
const withdrawSigned = await signTransactionMessageWithSigners(withdrawTx);
const withdrawSignature = getSignatureFromTransaction(withdrawSigned);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(withdrawSigned, {
commitment: 'confirmed',
skipPreflight: true,
});
console.log(`Withdraw fees successful! Signature: ${withdrawSignature}`);
```
<Check>
Fee withdrawal complete. The accumulated referral fees have been transferred to the referrer wallet.
</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::{
withdraw_referrer_fees,
WithdrawReferrerFeesAccounts,
};
use klend_interface::pda::{self, ReservePdas};
use klend_interface::KLEND_PROGRAM_ID;
use solana_pubkey::Pubkey;
use std::str::FromStr;
use spl_associated_token_account::get_associated_token_address;
let referrer = signer.pubkey();
let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap();
let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap();
let reserve_liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap();
// Derive PDAs
let (referrer_token_state, _) = pda::referrer_token_state(
&KLEND_PROGRAM_ID, &referrer, &reserve_pubkey
);
let (lending_market_authority, _) = pda::lending_market_authority(
&KLEND_PROGRAM_ID, &lending_market
);
let reserve_pdas = ReservePdas::derive(&KLEND_PROGRAM_ID, &reserve_pubkey);
// Derive referrer's ATA for the reserve liquidity mint
let referrer_token_account = get_associated_token_address(&referrer, &reserve_liquidity_mint);
let ix = withdraw_referrer_fees(WithdrawReferrerFeesAccounts {
referrer,
referrer_token_state,
reserve: reserve_pubkey,
reserve_liquidity_mint,
reserve_supply_liquidity: reserve_pdas.liquidity_supply_vault,
referrer_token_account,
lending_market,
lending_market_authority,
token_program: spl_token::ID,
});
```
</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!("Withdraw fees successful! Signature: {signature}");
```
</Step>
</Steps>
</Tab>
</Tabs>
# Borrow
Source: https://kamino.com/docs/build/developers/borrow/operations/borrow
Borrow assets against collateral
Borrow assets against your collateral in Kamino lending markets. The SDK handles transaction building, instruction creation, and obligation management for borrowing operations.
## Borrow
Borrow assets against your collateral.
<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 "dotenv/config";
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
address,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
} from "@solana/kit";
import {
KaminoMarket,
KaminoAction,
VanillaObligation,
PROGRAM_ID,
DEFAULT_RECENT_SLOT_DURATION_MS,
} from "@kamino-finance/klend-sdk";
import BN from "bn.js";
import { getKeypair } from "../../utils/keypair";
```
<Note>
`@solana/kit` provides modern utilities for RPC, transaction building, and
signing. `@kamino-finance/klend-sdk` contains market operation methods.
</Note>
</Step>
<Step>
### Initialize RPC and Load Market
Initialize the RPC connection and load the Kamino market instance.
```typescript theme={null}
const signer = await getKeypair();
const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com");
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.mainnet-beta.solana.com");
const marketPubkey = address("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF");
const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS);
```
<Note>
`KaminoMarket.load()` fetches the current market state including all reserve
data and configuration.
</Note>
</Step>
<Step>
### Check for Existing Obligation
Verify that an obligation exists before attempting to borrow.
```typescript theme={null}
// Check if obligation exists
const existingObligation = await market!.getObligationByWallet(
signer.address,
new VanillaObligation(PROGRAM_ID)
);
if (!existingObligation) {
throw new Error(
"No existing obligation found. Please deposit collateral first."
);
}
```
<Warning>
You must have an existing obligation with deposited collateral before you can
borrow. If you haven't deposited collateral yet, do that first.
</Warning>
</Step>
<Step>
### Build Borrow Instructions
Generate borrow instructions for the specified token and amount.
```typescript theme={null}
const usdtMint = address("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
const borrowAmount = new BN(1_000_000); // 1.00 USDT (6 decimals)
const borrowAction = await KaminoAction.buildBorrowTxns(
market!,
borrowAmount,
usdtMint,
signer,
new VanillaObligation(PROGRAM_ID),
true, // useV2Ixs
undefined, // scopeRefreshConfig
1_000_000, // extraComputeBudget
true, // includeAtaIxs
false // requestElevationGroup
);
```
<Info>
`buildBorrowTxns` creates borrow instructions that withdraw assets from the
reserve pool to your wallet. The amount borrowed is added to your debt
obligation.
</Info>
</Step>
<Step>
### Build and Sign Transaction
Combine all instructions and build the transaction using Kit's functional pipe pattern.
```typescript theme={null}
// Combine all instructions
const allInstructions = [
...(borrowAction.setupIxs || []),
...(borrowAction.lendingIxs || []),
...(borrowAction.cleanupIxs || []),
];
// Get fresh blockhash
const { value: latestBlockhash } = await rpc
.getLatestBlockhash({
commitment: "finalized",
})
.send();
// Build transaction using functional pipe pattern
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions(allInstructions, tx)
);
// Sign transaction
const signedTransaction = await signTransactionMessageWithSigners(
transactionMessage
);
```
<Note>
All setup, lending, and cleanup instructions are combined in a single
transaction for borrowing.
</Note>
</Step>
<Step>
### Send and Confirm Transaction
Send the transaction and confirm it using WebSocket.
```typescript theme={null}
// Send and confirm transaction
const signature = getSignatureFromTransaction(signedTransaction);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, {
commitment: "confirmed",
skipPreflight: true,
});
console.log("Borrow successful! Signature:", signature);
```
<Info>
Borrowing increases your debt and LTV ratio. Monitor your position to avoid
liquidation risk.
</Info>
</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>
### Build Obligation Context
The obligation must already have deposited collateral before you can borrow.
```rust theme={null}
use klend_interface::ObligationContext;
use klend_interface::pda;
use klend_interface::KLEND_PROGRAM_ID;
use solana_pubkey::Pubkey;
use std::str::FromStr;
let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap();
let borrow_reserve_pubkey = Pubkey::from_str("FBSyPnxtHKLBZ4UeeUyAnbtFuAmTHLtso9YtsqRDRWpM").unwrap();
// Derive the obligation PDA
let (obligation_pubkey, _) = pda::obligation(
&KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market,
&Pubkey::default(), &Pubkey::default(),
);
// Fetch the obligation account
let obligation_data = rpc_client.get_account(&obligation_pubkey)?;
// Discover which reserves the obligation references
let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?;
// Fetch all reserve accounts in one RPC call
let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?;
// Build the context
let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter()
.zip(reserve_accounts.iter())
.filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice())))
.collect();
let ctx = ObligationContext::from_account_data(
obligation_pubkey, &obligation_data.data, &reserves
)?;프로젝트로 돌아가기