etch 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, 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>
### Borrow and Multiply SDK Methods
<div>
| Method | Operation | When to Use |
| - | - | - |
| `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position |
| `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet |
| `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid |
| `getWithdrawWithLeverageIxs` | Deleverage and withdraw | Sell collateral to repay debt and receive remaining value in wallet |
| `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) |
<Note>
**Multiply operations** use `MultiplyObligation`. **Standard borrow operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position.
</Note>
</div>
# Borrow with the API
Source: https://kamino.com/docs/build/borrow/recipes/borrow-via-api
The API generates the unsigned transaction, and the client signs it securely
Borrow assets from a Kamino reserve using the API. The API builds the transaction, and you sign it locally keeping your keys secure.
## Borrow via the API
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities.
```typescript theme={null}
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
getTransactionDecoder,
getCompiledTransactionMessageDecoder,
decompileTransactionMessageFetchingLookupTables,
pipe,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
addSignersToTransactionMessage,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
} from '@solana/kit';
import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer';
```
</Step>
<Step>
### Configure and Initialize
Set up the configuration and initialize RPC connections.
```typescript theme={null}
const KEYPAIR_FILE = '/path/to/your/keypair.json';
const API_BASE_URL = 'https://api.kamino.finance';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const WS_ENDPOINT = 'wss://api.mainnet-beta.solana.com';
const MAIN_MARKET = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF';
const SOL_RESERVE = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q';
const signer = await parseKeypairFile(KEYPAIR_FILE);
const rpc = createSolanaRpc(RPC_ENDPOINT);
const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT);
```
</Step>
<Step>
### Call the Kamino API
Make a POST request to the Kamino API to build the borrow transaction.
```typescript theme={null}
const res = await fetch(`${API_BASE_URL}/ktx/klend/borrow`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
wallet: signer.address,
market: MAIN_MARKET,
reserve: SOL_RESERVE,
amount: '0.02',
}),
});
const data = await res.json();
if (!res.ok) {
console.error('Response error:', data);
}
const encodedTransaction = data.transaction;
```
<Info>
The API returns a pre-built transaction encoded in base64 format ready for signing.
</Info>
</Step>
<Step>
### Decode Transaction
Decode the base64-encoded transaction and extract the message bytes.
```typescript theme={null}
const txBuffer = Buffer.from(encodedTransaction, 'base64');
const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes;
const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes);
```
</Step>
<Step>
### Resolve Address Lookup Tables and Sign
Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign.
```typescript theme={null}
const { value: latestBlockhash } = await rpc.getLatestBlockhash({
commitment: 'finalized'
}).send();
const signedTransaction = await pipe(
await decompileTransactionMessageFetchingLookupTables(compiledMessage, rpc),
tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
tx => setTransactionMessageFeePayerSigner(signer, tx),
tx => addSignersToTransactionMessage([signer], tx),
tx => signTransactionMessageWithSigners(tx)
);
const signature = getSignatureFromTransaction(signedTransaction);
```
<Info>
`decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs.
</Info>
</Step>
<Step>
### Send and Confirm Transaction
Submit the signed transaction to the Solana network.
```typescript theme={null}
const sendAndConfirm = sendAndConfirmTransactionFactory({
rpc,
rpcSubscriptions,
});
await sendAndConfirm(signedTransaction, {
commitment: 'confirmed',
skipPreflight: false,
});
console.log('Borrow successful! Signature:', signature);
```
<Check>
Your borrow is complete! The API built the transaction, you signed it locally (keeping your keys secure), and it was successfully submitted to the network.
</Check>
</Step>
</Steps>
# Deposit with the API
Source: https://kamino.com/docs/build/borrow/recipes/deposit-via-api
The API generates the unsigned transaction, and the client signs it securely
Deposit collateral into a Kamino reserve using the API. The API builds the transaction, and you sign it locally keeping your keys secure.
## Deposit via the API
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities.
```typescript theme={null}
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
getTransactionDecoder,
getCompiledTransactionMessageDecoder,
decompileTransactionMessageFetchingLookupTables,
pipe,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
addSignersToTransactionMessage,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
} from '@solana/kit';
import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer';
```
</Step>
<Step>
### Configure and Initialize
Set up the configuration and initialize RPC connections.
```typescript theme={null}
const KEYPAIR_FILE = '/path/to/your/keypair.json';
const API_BASE_URL = 'https://api.kamino.finance';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const WS_ENDPOINT = 'wss://api.mainnet-beta.solana.com';
const MAIN_MARKET = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF';
const CASH_RESERVE = 'ApQkX32ULJUzszZDe986aobLDLMNDoGQK8tRm6oD6SsA';
const signer = await parseKeypairFile(KEYPAIR_FILE);
const rpc = createSolanaRpc(RPC_ENDPOINT);
const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT);
```
</Step>
<Step>
### Call the Kamino API
Make a POST request to the Kamino API to build the deposit transaction.
```typescript theme={null}
const res = await fetch(`${API_BASE_URL}/ktx/klend/deposit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
wallet: signer.address,
market: MAIN_MARKET,
reserve: CASH_RESERVE,
amount: '2.0',
}),
});
const data = await res.json();
if (!res.ok) {
console.error('Response error:', data);
}
const encodedTransaction = data.transaction;
```
<Info>
The API returns a pre-built transaction encoded in base64 format ready for signing.
</Info>
</Step>
<Step>
### Decode Transaction
Decode the base64-encoded transaction and extract the message bytes.
```typescript theme={null}
const txBuffer = Buffer.from(encodedTransaction, 'base64');
const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes;
const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes);
```
</Step>
<Step>
### Resolve Address Lookup Tables and Sign
Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign.
```typescript theme={null}
const { value: latestBlockhash } = await rpc.getLatestBlockhash({
commitment: 'finalized'
}).send();
const signedTransaction = await pipe(
await decompileTransactionMessageFetchingLookupTables(compiledMessage, rpc),
tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
tx => setTransactionMessageFeePayerSigner(signer, tx),
tx => addSignersToTransactionMessage([signer], tx),
tx => signTransactionMessageWithSigners(tx)
);
const signature = getSignatureFromTransaction(signedTransaction);
```
<Info>
`decompileTransactionM프로젝트로 돌아가기