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

# AMM v4 kod örnekleri

> Mevcut bir AMM v4 havuzuna karşı swap işlemi yapma ve likidite sağlama için TypeScript örnekleri. Yeni havuz oluşturma kapsam dışındadır — bunun yerine CPMM kullanın.

<Info>
  **Bu sayfa yapay zekâ tarafından otomatik olarak çevrilmiştir. İngilizce sürüm esas alınır.**

  [İngilizce sürümü görüntüle →](/products/amm-v4/code-demos)
</Info>

<Info>
  **Sürüm notu.** Tüm örnekler `@raydium-io/raydium-sdk-v2@0.2.42-alpha` sürümünü Solana mainnet-beta üzerinde hedefler, 2026-04'te doğrulanmıştır. Program ID: `675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8` (bkz. [`reference/program-addresses`](/tr/reference/program-addresses)).
</Info>

<Info>
  **Yeni havuz oluşturma burada gösterilmemektedir.** Raydium UI artık AMM v4 havuz oluşturmayı sunmamaktadır — yeni çiftler [CPMM](/tr/products/cpmm/code-demos)'ye varsayılan olarak ayarlanır. AMM v4 programı kendisi hâlâ zincir üzerinde `Initialize2` kabul eder; sadece önerilen yol değildir. Aşağıdaki örnekler her entegratörün hâlâ ihtiyaç duyduğu canlı havuz işlemlerini kapsar: swap, deposit, withdraw.
</Info>

## Kurulum

```ts theme={null}
import { Connection, Keypair, clusterApiUrl } from "@solana/web3.js";
import { Raydium, TxVersion } from "@raydium-io/raydium-sdk-v2";
import fs from "node:fs";

const connection = new Connection(process.env.RPC_URL ?? clusterApiUrl("mainnet-beta"));
const owner = Keypair.fromSecretKey(
  new Uint8Array(JSON.parse(fs.readFileSync(process.env.KEYPAIR!, "utf8"))),
);
const raydium = await Raydium.load({ owner, connection, cluster: "mainnet" });
```

## Havuzu ID'ye göre getir

```ts theme={null}
import { PublicKey } from "@solana/web3.js";

const poolId = new PublicKey("<AMM_V4_POOL_ID>");

// SDK tarafından normalleştirilmiş havuz nesnesini çek. AMM v4 için bu, talimat
// oluşturucuların ihtiyaç duyacağı OpenBook hesaplarını içerir.
const data = await raydium.liquidity.getPoolInfoFromRpc({ poolId });
const { poolInfo, poolKeys, poolRpcData } = data;

console.log("Çift:", poolInfo.mintA.symbol, "/", poolInfo.mintB.symbol);
console.log("Sürüm:", poolInfo.version);       // AMM v4 için 4
console.log("Pazar:", poolKeys.marketId.toBase58());
```

`poolKeys`, talimat oluşturucuların tükettiği yapıdır. Programın beklediği sırada her AMM v4 ve OpenBook hesabını taşır.

## Swap (base-in)

```ts theme={null}
import BN from "bn.js";

const amountIn = new BN(1_000_000);            // 1 USDC (6 ondalak quote)
const inputMint = new PublicKey(poolInfo.mintB.address);  // USDC
const slippage  = 0.005;

const computed = raydium.liquidity.computeAmountOut({
  poolInfo,
  amountIn,
  mintIn: inputMint,
  mintOut: new PublicKey(poolInfo.mintA.address),
  slippage,
});

const { execute } = await raydium.liquidity.swap({
  poolInfo,
  poolKeys,
  amountIn,
  amountOut: computed.minAmountOut,
  fixedSide: "in",
  inputMint,
  txVersion: TxVersion.V0,
});

const { txId } = await execute({ sendAndConfirm: true });
console.log("Swap tx:", txId);
```

SDK, AMM v4 swaplarını V2 giriş noktaları aracılığıyla yönlendirir; bu noktalar OpenBook hesaplarını taşımaz. (2026-07 yükseltmesinden sonra, pazar hesapları eski v1 yolunda bile doğrulanmaz.)

## Swap (base-out)

```ts theme={null}
const amountOut = new BN(1_000_000_000);       // 1 SOL (9 ondalak base)
const slippage  = 0.005;

const computed = raydium.liquidity.computeAmountIn({
  poolInfo,
  amountOut,
  mintOut: new PublicKey(poolInfo.mintA.address),
  mintIn: new PublicKey(poolInfo.mintB.address),
  slippage,
});

const { execute } = await raydium.liquidity.swap({
  poolInfo,
  poolKeys,
  amountIn: computed.maxAmountIn,
  amountOut,
  fixedSide: "out",
  inputMint: new PublicKey(poolInfo.mintB.address),
  txVersion: TxVersion.V0,
});

await execute({ sendAndConfirm: true });
```

## Likidite ekle

```ts theme={null}
const amountA = new BN(100_000_000);           // 0.1 SOL

const { anotherAmount, maxAnotherAmount } = raydium.liquidity.computePairAmount({
  poolInfo,
  amount: amountA,
  baseIn: true,
  slippage: 0.01,
});

const { execute } = await raydium.liquidity.addLiquidity({
  poolInfo,
  poolKeys,
  amountInA: amountA,
  amountInB: maxAnotherAmount,
  fixedSide: "a",
  txVersion: TxVersion.V0,
});

await execute({ sendAndConfirm: true });
```

`fixedSide: "a"` SDK'ya tam `amountInA` sağladığınızı ve `amountInB`'nin en fazla `maxAnotherAmount` olması gerektiğini söyler. Havuzun zincir üzerindeki likidite, oran-orantılı matematik öncesinde kapatılır, böylece yatırım oranı en yeni rezervleri eşleştirir.

## Likiditeyi kaldır

```ts theme={null}
const lpAmount = new BN(50_000);               // Yakılacak LP

const { execute } = await raydium.liquidity.removeLiquidity({
  poolInfo,
  poolKeys,
  lpAmount,
  baseAmountMin: new BN(0),
  quoteAmountMin: new BN(0),
  txVersion: TxVersion.V0,
});

await execute({ sendAndConfirm: true });
```

Slippage minimumları, havuzun durumunun ön-teklif ile iniş zamanı arasında değişmesine karşı koruma sağlar.

## Compute-unit / priority fee ayarlaması

AMM v4 swapları, her talimat tam OpenBook durumunu doğruladığı için compute açısından ağırdır. Tipik bir swap, kapalı emirlerin kaç tanesinin yol boyunca kapatılması gerektiğine bağlı olarak 180k–250k CU kullanır. Her zaman bir compute-unit limiti geçin:

```ts theme={null}
import { ComputeBudgetProgram } from "@solana/web3.js";

const { execute, innerTransactions } = await raydium.liquidity.swap({
  /* ...params... */
  computeBudgetConfig: {
    units: 400_000,
    microLamports: 50_000,       // priority fee
  },
});
```

`computeBudgetConfig` atlamazsanız, SDK yine de kendi varsayılanını kullanabilir; doğrulamak için `innerTransactions`'ı inceleyin. Bkz. [`integration-guides/priority-fee-tuning`](/tr/integration-guides/priority-fee-tuning).

## Doğrudan Rust CPI

Kendi Anchor programınızdan AMM v4'e CPI yapmanız gerekiyorsa, `SwapBaseIn`'in hesap listesini tam olarak modellemeniz gerekecektir. Minimal bir taslak:

```rust theme={null}
use anchor_lang::prelude::*;
use anchor_lang::solana_program::program::invoke_signed;
use anchor_lang::solana_program::instruction::Instruction;

const AMM_V4_PROGRAM_ID: Pubkey = pubkey!("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8");

#[derive(Accounts)]
pub struct ProxyAmmV4Swap<'info> {
    /// CHECK:
    pub token_program: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub amm:          UncheckedAccount<'info>,
    /// CHECK:
    pub amm_authority: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub amm_open_orders: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub amm_target_orders: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub pool_coin_token_account: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub pool_pc_token_account: UncheckedAccount<'info>,
    /// CHECK:
    pub market_program: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub market: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub market_bids: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub market_asks: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub market_event_queue: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub market_coin_vault: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub market_pc_vault: UncheckedAccount<'info>,
    /// CHECK:
    pub market_vault_signer: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub user_source: UncheckedAccount<'info>,
    #[account(mut)] /// CHECK:
    pub user_dest: UncheckedAccount<'info>,
    pub user_owner: Signer<'info>,
}

pub fn proxy_swap(
    ctx: Context<ProxyAmmV4Swap>,
    amount_in: u64,
    minimum_amount_out: u64,
) -> Result<()> {
    // SwapBaseIn için talimat ayırıcı AMM v4'te 9'dur.
    let mut data = vec![9u8];
    data.extend_from_slice(&amount_in.to_le_bytes());
    data.extend_from_slice(&minimum_amount_out.to_le_bytes());

    let ix = Instruction {
        program_id: AMM_V4_PROGRAM_ID,
        accounts: vec![
            AccountMeta::new_readonly(ctx.accounts.token_program.key(), false),
            AccountMeta::new(ctx.accounts.amm.key(), false),
            AccountMeta::new_readonly(ctx.accounts.amm_authority.key(), false),
            AccountMeta::new(ctx.accounts.amm_open_orders.key(), false),
            AccountMeta::new(ctx.accounts.amm_target_orders.key(), false),
            AccountMeta::new(ctx.accounts.pool_coin_token_account.key(), false),
            AccountMeta::new(ctx.accounts.pool_pc_token_account.key(), false),
            AccountMeta::new_readonly(ctx.accounts.market_program.key(), false),
            AccountMeta::new(ctx.accounts.market.key(), false),
            AccountMeta::new(ctx.accounts.market_bids.key(), false),
            AccountMeta::new(ctx.accounts.market_asks.key(), false),
            AccountMeta::new(ctx.accounts.market_event_queue.key(), false),
            AccountMeta::new(ctx.accounts.market_coin_vault.key(), false),
            AccountMeta::new(ctx.accounts.market_pc_vault.key(), false),
            AccountMeta::new_readonly(ctx.accounts.market_vault_signer.key(), false),
            AccountMeta::new(ctx.accounts.user_source.key(), false),
            AccountMeta::new(ctx.accounts.user_dest.key(), false),
            AccountMeta::new_readonly(ctx.accounts.user_owner.key(), true),
        ],
        data,
    };
    invoke_signed(&ix, &ctx.accounts.to_account_infos(), &[])?;
    Ok(())
}
```

AMM v4, CPI için bir Anchor crate'i göndermiyor. Yukarıdaki taslak, manuel olarak oluşturulmuş bir `Instruction` kullanır.

<Note>
  Yukarıdaki CPI taslağı **eski v1 `SwapBaseIn` düzeni** (etiket 9, 17 hesap) kullanır; mevcut işlemleri okuma/yeniden üretme için. 2026-07 yükseltmesinden bu yana pazar hesapları kabul edilir ancak yoksayılır. **Yeni kod için `SwapBaseInV2` / `SwapBaseOutV2`** (etiketler 16 / 17) tercih edin; bunlar pazar hesaplarını (ve `amm_open_orders`'ı) tamamen bırakır — sadece 8 hesap geçin: `token_program`, `amm`, `amm_authority`, iki havuz kasası, iki kullanıcı token hesabı ve `user_owner`.
</Note>

## Tuzaklar

* **v1 swaplarında yanlış hesap sayısı.** Eski `SwapBaseIn` / `SwapBaseOut` hâlâ tam 17 hesap (veya 18 hesap) listesi gerektirir — uyumsuz bir *sayı* `WrongAccountsNumber` ile geri döner. Pazar hesaplarının *içeriği* artık doğrulanmaz, ancak yine de yuvaları doldurmanız gerekir. Bu sorunu önlemek için V2 giriş noktalarını tercih edin.
* **Ham kasa bakiyelerini okuma.** Rezervler artık yalnızca kasa; tahakkuk eden PnL'yi çıkarın (`need_take_pnl_*`). SDK teklifi veya `api-v3.raydium.io/pools/info/ids` bunu sizin için işler.
* **Kaldırılan talimatları çağırma.** `MonitorStep`, `MigrateToOpenBook`, `WithdrawSrm`, `SimulateInfo`, `AdminCancelOrders` ve eski `Initialize` / `PreInitialize` artık geri döner. Havuz oluşturma için `Initialize2` kullanın; çağrılacak bir crank yoktur.
* **Token-2022 mintleri.** Desteklenmez. AMM v4 havuzu Token-2022 mintine karşı oluşturulamaz; herhangi bir Token-2022 çifti CPMM veya CLMM'de olmalıdır.

## Sonraki adımlar

* [`products/amm-v4/instructions`](/tr/products/amm-v4/instructions) — bu örneklerin arkasındaki talimat düzeyi yüzeyi.
* [`user-flows/migrate-amm-v4-to-cpmm`](/tr/user-flows/migrate-amm-v4-to-cpmm) — eğer bir LP olarak göç düşünüyorsanız.
* [`integration-guides/priority-fee-tuning`](/tr/integration-guides/priority-fee-tuning) — ağır AMM v4 swapları için priority-fee boyutlandırması.

Kaynaklar:

* [Raydium SDK v2](https://github.com/raydium-io/raydium-sdk-V2)
* [Raydium AMM programı](https://github.com/raydium-io/raydium-amm)
