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

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Hesap Yönetimi

> Anchor hesaplarını otomatik discriminator işlemesiyle getirme ve deserialize etme

## Anchor Hesap Discriminator'larını Anlama

Anchor programları, tüm hesap verilerinin başına 8 baytlık bir discriminator ekler. Bu
discriminator, hesap türü adının bir hash'idir ve hesap verisinin beklenen türle
eşleştiğini doğrulamak için kullanılır.

```
┌─────────────────────────────────────────────────┐
│ Account Data Layout                             │
├────────────────┬────────────────────────────────┤
│ Discriminator  │ Account Fields                 │
│ (8 bytes)      │ (variable size)                │
└────────────────┴────────────────────────────────┘
```

`anchor-litesvm` hesap yardımcı araçları bu discriminator'ı otomatik olarak işler.

<Warning>
  Bu örnekler, programınızın SBPF v0 derlemesini gerektirir. `anchor-litesvm` 0.4,
  SBPF v3 programlarını yükleyemeyen LiteSVM 0.11'i kullandığı için `build_with_program`,
  `Failed to add program: Instruction(InvalidAccountData)` hatasıyla panic verir.
  Anchor 1.2 ve sonrasında `anchor build --arch v0` ile derleyin ve
  `anchor test --skip-build` komutunu çalıştırın. Anchor 1.1.x için ve testin ile IDL'in
  nereye yerleştirileceği konusunda
  [Hızlı Başlangıç](/developers/docs/tools/litesvm/additional-crates/testing-with-anchor-litesvm#installation) bölümüne bakın.
</Warning>

Hesap türleri, programınızın IDL'inden üreten `declare_program!(your_program)` makrosundan gelir:
hesap struct'ları `your_program::accounts` altında,
enum gibi diğer türler ise `your_program::types` altında yer alır. `#[account]` struct'larını
test dosyasının içinde tanımlamayın: makro, programın `ID` değerini crate kökünde bekler;
bir test crate'inde ise bu bulunmaz.

## Anchor Hesaplarını Getirme

### Temel Hesap Getirme

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Pubkey, Signer};

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

#[test]
fn test_fetch_account() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        your_program::ID,
        include_bytes!("../../../target/deploy/your_program.so"),
    );

    let user = ctx.create_funded_account(10_000_000_000).unwrap();

    // ... initialize the account ...

    let (user_pda, _) = Pubkey::find_program_address(
        &[b"user", user.pubkey().as_ref()],
        &your_program::ID,
    );

    // Fetch and deserialize the account
    let account: UserAccount = ctx.get_account(&user_pda).unwrap();

    assert_eq!(account.name, "Alice");
    assert_eq!(account.authority, user.pubkey());
}
```

<Info>
  `get_account<T>()`, hesap verisinin beklenen türle eşleştiğinden emin olmak için 8 baytlık discriminator'ı otomatik olarak doğrular.
</Info>

### Doğrulamasız Deserialization

Discriminator doğrulamasının başarısız olabileceği PDA'lar veya özel hesap düzenleri için
`get_account_unchecked` kullanın:

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

#[test]
fn test_fetch_unchecked() {
    let ctx = AnchorLiteSVM::build_with_program(
        your_program::ID,
        include_bytes!("../../../target/deploy/your_program.so"),
    );

    // Fetch without discriminator validation
    let account: UserAccount = ctx.get_account_unchecked(&some_pda).unwrap();
}
```

<Warning>
  `get_account_unchecked` işlevini dikkatli kullanın. Discriminator doğrulaması olmadan
  geçersiz verileri deserialize edebilirsiniz. Bunu yalnızca hesap türünden
  emin olduğunuzda kullanın.
</Warning>

## Hesap Modülünü Doğrudan Kullanma

Hesap deserialization işlevlerini doğrudan da kullanabilirsiniz:

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{get_anchor_account, get_anchor_account_unchecked, LiteSVM};

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

#[test]
fn test_direct_account_fetch() {
    let mut svm = LiteSVM::new();
    // ... setup ...

    // Fetch with discriminator check
    let account: UserAccount = get_anchor_account(&svm, &account_pubkey).unwrap();

    // Fetch without discriminator check
    let account: UserAccount = get_anchor_account_unchecked(&svm, &account_pubkey).unwrap();
}
```

## Hesap Hataları

`AccountError` enum'ı ayrıntılı hata bilgisi sağlar:

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{AccountError, AnchorLiteSVM};

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

#[test]
fn test_handle_errors() {
    let ctx = AnchorLiteSVM::build_with_program(
        your_program::ID,
        include_bytes!("../../../target/deploy/your_program.so"),
    );

    let result = ctx.get_account::<UserAccount>(&nonexistent_pubkey);

    match result {
        Ok(account) => println!("Found account: {}", account.name),
        Err(AccountError::AccountNotFound(pubkey)) => {
            println!("Account not found: {}", pubkey);
        }
        Err(AccountError::DiscriminatorMismatch) => {
            println!("Wrong account type!");
        }
        Err(AccountError::DeserializationError(msg)) => {
            println!("Failed to deserialize: {}", msg);
        }
    }
}
```

| Hata                          | Açıklama                                       |
| ------------------------------ | ------------------------------------------------- |
| `AccountNotFound(Pubkey)`      | Belirtilen adreste hesap yok            |
| `DiscriminatorMismatch`        | Hesap discriminator'ı beklenen türle eşleşmiyor |
| `DeserializationError(String)` | Hesap verisi deserialize edilemedi                |

## Birden Fazla Hesap Türüyle Çalışma

### Farklı Hesap Türlerini Getirme

Burada `your_program`, `Config`, `UserProfile` ve `Order` hesaplarını ve `Order`'ın
tuttuğu `OrderStatus` enum'ını (`Pending`, `Completed`, `Cancelled`) tanımlar:

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;

anchor_lang::declare_program!(your_program);

use your_program::accounts::{Config, Order, UserProfile};
use your_program::types::OrderStatus;

#[test]
fn test_multiple_account_types() {
    let ctx = AnchorLiteSVM::build_with_program(
        your_program::ID,
        include_bytes!("../../../target/deploy/your_program.so"),
    );

    // Each account type is deserialized correctly
    let config: Config = ctx.get_account(&config_pda).unwrap();
    let profile: UserProfile = ctx.get_account(&profile_pda).unwrap();
    let order: Order = ctx.get_account(&order_pda).unwrap();

    assert_eq!(config.fee_bps, 100);
    assert_eq!(profile.username, "alice");
    assert!(matches!(order.status, OrderStatus::Pending));
}
```

### Getirmeden Önce Hesabın Var Olup Olmadığını Kontrol Etme

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Pubkey};

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

#[test]
fn test_check_before_fetch() {
    let ctx = AnchorLiteSVM::build_with_program(
        your_program::ID,
        include_bytes!("../../../target/deploy/your_program.so"),
    );

    let user_pda = Pubkey::new_unique();

    // Check existence first
    if ctx.account_exists(&user_pda) {
        let account: UserAccount = ctx.get_account(&user_pda).unwrap();
        println!("Found: {}", account.name);
    } else {
        println!("Account not initialized yet");
    }
}
```

## Eksiksiz Örnek

İşte bir sayaç programıyla hesap yönetimini gösteren kapsamlı bir örnek.
Programın `initialize` işlevi bir `Counter` PDA'sı (`count`, `authority`,
`bump`) oluşturur, `increment` işlevi ise `count` değerine bir ekler:

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Pubkey, Signer, TestHelpers};

anchor_lang::declare_program!(counter);

#[test]
fn test_counter_workflow() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        counter::ID,
        include_bytes!("../../../target/deploy/counter.so"),
    );

    let authority = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    // Derive the counter PDA
    let (counter_pda, bump) = Pubkey::find_program_address(
        &[b"counter", authority.pubkey().as_ref()],
        &counter::ID,
    );

    // Verify counter doesn't exist yet
    assert!(!ctx.account_exists(&counter_pda));

    // Initialize using generated client types
    let init_ix = ctx.program()
        .accounts(counter::client::accounts::Initialize {
            authority: authority.pubkey(),
            counter: counter_pda,
            system_program: anchor_lang::system_program::ID,
        })
        .args(counter::client::args::Initialize {})
        .instruction()
        .unwrap();

    ctx.execute_instruction(init_ix, &[&authority])
        .unwrap()
        .assert_success();

    // Verify counter exists and has correct initial state
    assert!(ctx.account_exists(&counter_pda));
    let counter: counter::accounts::Counter = ctx.get_account(&counter_pda).unwrap();
    assert_eq!(counter.count, 0);
    assert_eq!(counter.authority, authority.pubkey());
    assert_eq!(counter.bump, bump);

    // Increment using generated client types
    let increment_ix = ctx.program()
        .accounts(counter::client::accounts::Increment {
            authority: authority.pubkey(),
            counter: counter_pda,
        })
        .args(counter::client::args::Increment {})
        .instruction()
        .unwrap();

    ctx.execute_instruction(increment_ix.clone(), &[&authority])
        .unwrap()
        .assert_success();

    // Verify incremented
    let counter: counter::accounts::Counter = ctx.get_account(&counter_pda).unwrap();
    assert_eq!(counter.count, 1);

    // An identical transaction with the same blockhash is rejected as
    // AlreadyProcessed, so move to a new blockhash before repeating it
    ctx.svm.expire_blockhash();

    // Increment again
    ctx.execute_instruction(increment_ix, &[&authority])
        .unwrap()
        .assert_success();

    let counter: counter::accounts::Counter = ctx.get_account(&counter_pda).unwrap();
    assert_eq!(counter.count, 2);

    println!("Counter test passed! Final count: {}", counter.count);
}
```

<Info>
  `execute_instruction(...).unwrap()` yalnızca çağrının kendisini unwrap eder.
  Çalışma zamanının reddettiği bir işlem yine de `Ok` döndürür; bu nedenle işlem başarısız olduğunda
  testin de başarısız olması için `.assert_success()` zincirini ekleyin.
</Info>
