> ## Documentation Index
> Fetch the complete documentation index at: https://kamino.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Repay and Withdraw

> Repay borrowed assets and withdraw your collateral

## Repay Debt

Repay borrowed assets to improve your position health.

<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, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk';
    import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js';
    import BN from 'bn.js';
    ```
  </Step>

  <Step>
    ### Load Signer and Initialize Market

    Load your keypair from a file and initialize RPC connections and 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);
    ```

    <Note>
      Replace `/path/to/your/keypair.json` with the actual path to your keypair file. The `KaminoMarket.load()` method fetches the current market state including all reserve data.
    </Note>
  </Step>

  <Step>
    ### Fetch Obligation and Build Repay Instructions

    Fetch the existing obligation and generate repay instructions for the specified token and amount.

    ```typescript theme={null}
    const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB');
    const repayAmount = new BN(1_000_000); // 1.00 USDT (6 decimals)

    const currentSlot = await rpc.getSlot().send();

    const obligation = await market!.getObligationByWallet(address(signer.address), new VanillaObligation(PROGRAM_ID));

    if (!obligation) {
      throw new Error('No obligation found for this wallet. You must have an active borrow to repay.');
    }

    const repayAction = await KaminoAction.buildRepayTxns(
      market!,
      repayAmount,
      usdtMint,
      signer,
      new VanillaObligation(PROGRAM_ID),
      true,
      undefined,
      currentSlot,
      signer,
      1_000_000,
      true,
      false
    );

    const allInstructions = [
      ...(repayAction.setupIxs || []),
      ...(repayAction.lendingIxs || []),
      ...(repayAction.cleanupIxs || []),
    ];
    ```

    <Info>
      The `buildRepayTxns` method creates instructions to repay your borrowed assets. Repaying reduces your debt and improves your loan-to-value ratio.
    </Info>
  </Step>

  <Step>
    ### Build and Sign Transaction

    Use Kit's functional pipe pattern to build and sign the transaction with a fresh blockhash.

    ```typescript theme={null}
    const { value: latestBlockhash } = await rpc
      .getLatestBlockhash({
        commitment: 'finalized',
      })
      .send();

    const transactionMessage = pipe(
      createTransactionMessage({ version: 0 }),
      (tx) => setTransactionMessageFeePayerSigner(signer, tx),
      (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
      (tx) => appendTransactionMessageInstructions(allInstructions, tx)
    );

    const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
    ```
  </Step>

  <Step>
    ### Send and Confirm Transaction

    Send the repay transaction and wait for confirmation.

    ```typescript theme={null}
    const signature = getSignatureFromTransaction(signedTransaction);

    await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, {
      commitment: 'confirmed',
      skipPreflight: true,
    });

    console.log('Repay successful! Signature:', signature);
    ```

    <Check>
      Once the repay transaction is confirmed, your debt is reduced and your loan-to-value ratio improves. You stop paying interest on the repaid amount.
    </Check>
  </Step>
</Steps>

## Withdraw Collateral

Withdraw collateral from your obligation.

<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, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk';
    import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js';
    import BN from 'bn.js';
    ```
  </Step>

  <Step>
    ### Load Signer and Initialize Market

    Load your keypair from a file and initialize RPC connections and 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);
    ```

    <Note>
      Replace `/path/to/your/keypair.json` with the actual path to your keypair file. The `KaminoMarket.load()` method fetches the current market state including all reserve data.
    </Note>
  </Step>

  <Step>
    ### Build Withdraw Collateral Instructions

    Generate withdraw instructions for the specified collateral token and amount.

    ```typescript theme={null}
    const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
    const withdrawAmount = new BN(1_000_000); // 1 USDC (6 decimals)

    const withdrawAction = await KaminoAction.buildWithdrawTxns(
      market!,
      withdrawAmount,
      usdcMint,
      signer,
      new VanillaObligation(PROGRAM_ID),
      true,
      undefined,
      1_000_000,
      true,
      false
    );

    const allInstructions = [
      ...(withdrawAction.setupIxs || []),
      ...(withdrawAction.lendingIxs || []),
      ...(withdrawAction.cleanupIxs || []),
    ];
    ```

    <Info>
      The `buildWithdrawTxns` method creates instructions to withdraw your collateral. You can only withdraw collateral if your position remains healthy after the withdrawal.
    </Info>
  </Step>

  <Step>
    ### Build and Sign Transaction

    Use Kit's functional pipe pattern to build and sign the transaction with a fresh blockhash.

    ```typescript theme={null}
    const { value: latestBlockhash } = await rpc
      .getLatestBlockhash({
        commitment: 'finalized',
      })
      .send();

    const transactionMessage = pipe(
      createTransactionMessage({ version: 0 }),
      (tx) => setTransactionMessageFeePayerSigner(signer, tx),
      (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
      (tx) => appendTransactionMessageInstructions(allInstructions, tx)
    );

    const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
    ```
  </Step>

  <Step>
    ### Send and Confirm Transaction

    Send the withdraw transaction and wait for confirmation.

    ```typescript theme={null}
    const signature = getSignatureFromTransaction(signedTransaction);

    await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, {
      commitment: 'confirmed',
      skipPreflight: true,
    });

    console.log('Withdrawal successful! Signature:', signature);
    ```

    <Check>
      Once the withdraw transaction is confirmed, your collateral is returned to your wallet. Your borrowing capacity decreases and your loan-to-value ratio may increase.
    </Check>
  </Step>
</Steps>
