meteora-dbc-client 0.1.1

Rust SDK for Meteora Dynamic Bonding Curve program
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
use solana_client::rpc_client::RpcClient;
use solana_client::rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig};
use solana_client::rpc_filter::{Memcmp, RpcFilterType};
use solana_pubkey::Pubkey;
use solana_sdk::commitment_config::CommitmentConfig;
use solana_sdk::signature::{Keypair, Signer};
use solana_sdk::transaction::Transaction;
use solana_sdk::system_instruction;
use std::str::FromStr;

use meteora_dbc_client::generated::accounts::{VirtualPool, PoolConfig};
use meteora_dbc_client::generated::types::SwapParameters;
use meteora_dbc_client::generated::instructions::SwapBuilder;
use meteora_dbc_client::DYNAMIC_BONDING_CURVE_ID;


pub const POOL_AUTHORITY: &str = "FhVo3mqL8PW5pH5U2CN4XE33DokiyZnUwuGpH2hmHLuM";
pub const TOKEN_PROGRAM_ID: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
pub const TOKEN_2022_PROGRAM_ID: &str = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
pub const ASSOCIATED_TOKEN_PROGRAM_ID: &str = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
pub const WSOL_MINT: &str = "So11111111111111111111111111111111111111112";

pub const VIRTUAL_POOL_DISCRIMINATOR: [u8; 8] = [213, 224, 5, 209, 98, 69, 119, 92];

pub fn fetch_virtual_pool(
    rpc: &RpcClient,
    pool_address: &Pubkey,
) -> Result<VirtualPool, Box<dyn std::error::Error>> {
    let account_data = rpc.get_account_data(pool_address)?;
    let pool = VirtualPool::from_bytes(&account_data)?;
    Ok(pool)
}

/// Find pool address by searching for base_mint
pub fn find_pool_by_token_mint(
    rpc: &RpcClient,
    token_mint: &Pubkey,
) -> Result<Pubkey, Box<dyn std::error::Error>> {
    // VirtualPool layout:
    // [0..8]     - discriminator
    // [8..72]    - volatility_tracker (64 bytes)
    // [72..104]  - config (32 bytes)
    // [104..136] - creator (32 bytes)
    // [136..168] - base_mint (32 bytes) <-- filter on this
    let base_mint_offset = 8 + 64 + 32 + 32; // = 136

    let filters = vec![
        // Filter by discriminator
        RpcFilterType::Memcmp(Memcmp::new_raw_bytes(
            0,
            VIRTUAL_POOL_DISCRIMINATOR.to_vec(),
        )),
        // Filter by base_mint
        RpcFilterType::Memcmp(Memcmp::new_raw_bytes(
            base_mint_offset,
            token_mint.to_bytes().to_vec(),
        )),
    ];

    let config = RpcProgramAccountsConfig {
        filters: Some(filters),
        account_config: RpcAccountInfoConfig {
            commitment: Some(CommitmentConfig::confirmed()),
            encoding: Some(solana_account_decoder::UiAccountEncoding::Base64),
            ..Default::default()
        },
        ..Default::default()
    };

    let accounts = rpc.get_program_accounts_with_config(
        &DYNAMIC_BONDING_CURVE_ID,
        config,
    )?;

    if accounts.is_empty() {
        return Err("No pool found for this token mint".into());
    }

    Ok(accounts[0].0)
}

pub fn fetch_pool_config(
    rpc: &RpcClient,
    config_address: &Pubkey,
) -> Result<PoolConfig, Box<dyn std::error::Error>> {
    let account_data = rpc.get_account_data(config_address)?;
    let config = PoolConfig::from_bytes(&account_data)?;
    Ok(config)
}


pub fn get_event_authority() -> Pubkey {
    let (pda, _bump) = Pubkey::find_program_address(
        &[b"__event_authority"],
        &DYNAMIC_BONDING_CURVE_ID,
    );
    pda
}

pub fn get_pool_authority() -> Pubkey {
    Pubkey::from_str(POOL_AUTHORITY).unwrap()
}

pub fn get_user_token_account(
    wallet: &Pubkey,
    mint: &Pubkey,
    token_program: &Pubkey,
) -> Pubkey {
    let ata_program = Pubkey::from_str(ASSOCIATED_TOKEN_PROGRAM_ID).unwrap();
    let (ata, _bump) = Pubkey::find_program_address(
        &[
            wallet.as_ref(),
            token_program.as_ref(),
            mint.as_ref(),
        ],
        &ata_program,
    );
    ata
}

pub fn get_token_program_from_pool_type(pool_type: u8) -> Pubkey {
    match pool_type {
        0 => Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap(),      // SPL Token
        1 => Pubkey::from_str(TOKEN_2022_PROGRAM_ID).unwrap(), // Token-2022
        _ => Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap(),      // Default to SPL
    }
}

pub fn build_buy_instruction(
    pool_address: &Pubkey,
    pool: &VirtualPool,
    pool_config: &PoolConfig,
    wallet: &Pubkey,
    amount_in: u64,
    minimum_amount_out: u64,
) -> solana_instruction::Instruction {
    let token_base_program = get_token_program_from_pool_type(pool.pool_type);
    let token_quote_program = Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap();

    let user_quote_ata = get_user_token_account(wallet, &pool_config.quote_mint, &token_quote_program);
    let user_base_ata = get_user_token_account(wallet, &pool.base_mint, &token_base_program);

    SwapBuilder::new()
        .pool_authority(get_pool_authority())
        .config(pool.config)
        .pool(*pool_address)
        .input_token_account(user_quote_ata)    
        .output_token_account(user_base_ata)
        .base_vault(pool.base_vault)
        .quote_vault(pool.quote_vault)
        .base_mint(pool.base_mint)
        .quote_mint(pool_config.quote_mint)
        .payer(*wallet)
        .token_base_program(token_base_program)
        .token_quote_program(token_quote_program)
        .referral_token_account(None)
        .event_authority(get_event_authority())
        .program(DYNAMIC_BONDING_CURVE_ID)
        .params(SwapParameters {
            amount_in,
            minimum_amount_out,
        })
        .instruction()
}

pub fn build_sell_instruction(
    pool_address: &Pubkey,
    pool: &VirtualPool,
    pool_config: &PoolConfig,
    wallet: &Pubkey,
    amount_in: u64,
    minimum_amount_out: u64,
) -> solana_instruction::Instruction {
    let token_base_program = get_token_program_from_pool_type(pool.pool_type);
    let token_quote_program = Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap();

    let user_quote_ata = get_user_token_account(wallet, &pool_config.quote_mint, &token_quote_program);
    let user_base_ata = get_user_token_account(wallet, &pool.base_mint, &token_base_program);

    SwapBuilder::new()
        .pool_authority(get_pool_authority())
        .config(pool.config)
        .pool(*pool_address)
        .input_token_account(user_base_ata)
        .output_token_account(user_quote_ata)
        .base_vault(pool.base_vault)
        .quote_vault(pool.quote_vault)
        .base_mint(pool.base_mint)
        .quote_mint(pool_config.quote_mint)
        .payer(*wallet)
        .token_base_program(token_base_program)
        .token_quote_program(token_quote_program)
        .referral_token_account(None)
        .event_authority(get_event_authority())
        .program(DYNAMIC_BONDING_CURVE_ID)
        .params(SwapParameters {
            amount_in,
            minimum_amount_out,
        })
        .instruction()
}

// =============================================================================
// WSOL Wrapping Functions
// =============================================================================

/// Create Associated Token Account instruction (idempotent - won't fail if exists)
pub fn create_ata_instruction(
    payer: &Pubkey,
    owner: &Pubkey,
    mint: &Pubkey,
    token_program: &Pubkey,
) -> solana_instruction::Instruction {
    let ata_program = Pubkey::from_str(ASSOCIATED_TOKEN_PROGRAM_ID).unwrap();
    let ata = get_user_token_account(owner, mint, token_program);
    
    solana_instruction::Instruction {
        program_id: ata_program,
        accounts: vec![
            solana_instruction::AccountMeta::new(*payer, true),
            solana_instruction::AccountMeta::new(ata, false),
            solana_instruction::AccountMeta::new_readonly(*owner, false),
            solana_instruction::AccountMeta::new_readonly(*mint, false),
            solana_instruction::AccountMeta::new_readonly(solana_sdk::system_program::ID, false),
            solana_instruction::AccountMeta::new_readonly(*token_program, false),
        ],
        data: vec![1], // CreateIdempotent instruction
    }
}

/// Wrap native SOL by transferring to ATA and syncing
pub fn wrap_sol_instructions(
    wallet: &Pubkey,
    amount: u64,
) -> Vec<solana_instruction::Instruction> {
    let wsol_mint = Pubkey::from_str(WSOL_MINT).unwrap();
    let token_program = Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap();
    let wsol_ata = get_user_token_account(wallet, &wsol_mint, &token_program);
    
    vec![
        // 1. Create WSOL ATA if it doesn't exist
        create_ata_instruction(wallet, wallet, &wsol_mint, &token_program),
        
        // 2. Transfer SOL to the ATA (this funds it with native lamports)
        system_instruction::transfer(wallet, &wsol_ata, amount),
        
        // 3. Sync native - updates the token balance to match lamport balance
        sync_native_instruction(&wsol_ata),
    ]
}

/// SyncNative instruction for WSOL
pub fn sync_native_instruction(token_account: &Pubkey) -> solana_instruction::Instruction {
    let token_program = Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap();
    
    solana_instruction::Instruction {
        program_id: token_program,
        accounts: vec![
            solana_instruction::AccountMeta::new(*token_account, false),
        ],
        data: vec![17], // SyncNative instruction discriminator
    }
}

/// Close WSOL account and get remaining SOL back
pub fn close_wsol_instruction(
    wallet: &Pubkey,
) -> solana_instruction::Instruction {
    let wsol_mint = Pubkey::from_str(WSOL_MINT).unwrap();
    let token_program = Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap();
    let wsol_ata = get_user_token_account(wallet, &wsol_mint, &token_program);
    
    solana_instruction::Instruction {
        program_id: token_program,
        accounts: vec![
            solana_instruction::AccountMeta::new(wsol_ata, false),
            solana_instruction::AccountMeta::new(*wallet, false),
            solana_instruction::AccountMeta::new_readonly(*wallet, true),
        ],
        data: vec![9], // CloseAccount instruction discriminator
    }
}

// =============================================================================
// Meteora DBC Price Calculation Functions
// =============================================================================
// 
// Meteora DBC uses a multi-segment concentrated liquidity curve.
// Each segment has: sqrt_price (price boundary) and liquidity (L)
// 
// Core Formulas (from Meteora source code):
// - Delta Base (tokens): Δbase = L × (√P_upper - √P_lower) / (√P_upper × √P_lower)
// - Delta Quote (SOL):   Δquote = L × (√P_upper - √P_lower) / 2^128
// - New price after buy:  √P' = √P + (Δquote × 2^128) / L
// - New price after sell: √P' = √P × L / (L + Δbase × √P)
// =============================================================================

const Q64: u128 = 1u128 << 64;   // 2^64 for sqrt_price scaling
const Q128: u128 = 1u128 << 64;  // We use Q64.64 format, so effective Q128 in denominator

/// Calculate expected tokens out for a BUY (SOL → Tokens)
/// Uses the actual Meteora DBC formula with sqrt_price and liquidity
/// 
/// Formula:
/// 1. new_sqrt_price = sqrt_price + (sol_in × 2^128) / liquidity
/// 2. tokens_out = L × (new_sqrt_price - sqrt_price) / (sqrt_price × new_sqrt_price)
pub fn calculate_tokens_out_dbc(
    sol_in: u64,
    sqrt_price: u128,
    liquidity: u128,
    fee_bps: u64,  // Fee in basis points (e.g., 100 = 1%)
) -> u64 {
    if liquidity == 0 || sqrt_price == 0 {
        return 0;
    }
    
    // Use f64 for calculation to handle very large liquidity values
    let sol_in_f = sol_in as f64;
    let sqrt_price_f = sqrt_price as f64;
    let liquidity_f = liquidity as f64;
    let q128: f64 = (1u128 << 64) as f64 * (1u128 << 64) as f64;  // 2^128
    
    // Calculate new sqrt_price after adding SOL
    // √P' = √P + (Δquote × 2^128) / L
    let delta_sqrt = (sol_in_f * q128) / liquidity_f;
    let new_sqrt_price_f = sqrt_price_f + delta_sqrt;
    
    // Calculate tokens out: L × (√P' - √P) / (√P × √P')
    let sqrt_diff = new_sqrt_price_f - sqrt_price_f;
    let denom = sqrt_price_f * new_sqrt_price_f;
    
    if denom == 0.0 {
        return 0;
    }
    
    let tokens_raw = liquidity_f * sqrt_diff / denom;
    
    // Apply fee reduction
    let tokens_after_fee = tokens_raw * (10000.0 - fee_bps as f64) / 10000.0;
    
    if tokens_after_fee < 0.0 {
        return 0;
    }
    
    tokens_after_fee as u64
}

/// Calculate expected SOL out for a SELL (Tokens → SOL)
/// Uses the actual Meteora DBC formula with sqrt_price and liquidity
/// 
/// Formula:
/// 1. new_sqrt_price = sqrt_price × L / (L + tokens_in × sqrt_price)
/// 2. sol_out = L × (sqrt_price - new_sqrt_price) / 2^128
pub fn calculate_sol_out_dbc(
    tokens_in: u64,
    sqrt_price: u128,
    liquidity: u128,
    fee_bps: u64,  // Fee in basis points (e.g., 100 = 1%)
) -> u64 {
    if liquidity == 0 || sqrt_price == 0 {
        return 0;
    }
    
    // Use f64 for calculation to handle very large liquidity values
    let tokens_in_f = tokens_in as f64;
    let sqrt_price_f = sqrt_price as f64;
    let liquidity_f = liquidity as f64;
    let q128: f64 = (1u128 << 64) as f64 * (1u128 << 64) as f64;  // 2^128
    
    // Calculate new sqrt_price after adding tokens
    // √P' = √P × L / (L + Δbase × √P)
    let product = tokens_in_f * sqrt_price_f;
    let denominator = liquidity_f + product;
    
    if denominator == 0.0 {
        return 0;
    }
    
    let new_sqrt_price_f = (liquidity_f * sqrt_price_f) / denominator;
    
    // Calculate SOL out: L × (√P - √P') / 2^128
    let sqrt_diff = sqrt_price_f - new_sqrt_price_f;
    
    if sqrt_diff <= 0.0 {
        return 0;
    }
    
    let sol_raw = (liquidity_f * sqrt_diff) / q128;
    
    // Apply fee reduction
    let sol_after_fee = sol_raw * (10000.0 - fee_bps as f64) / 10000.0;
    
    if sol_after_fee < 0.0 {
        return 0;
    }
    
    sol_after_fee as u64
}

/// Get current price from sqrt_price
/// price = (sqrt_price / 2^64)^2 = sqrt_price^2 / 2^128
/// Returns price in quote per base (SOL per token)
pub fn get_price_from_sqrt_price(sqrt_price: u128) -> f64 {
    let sqrt_price_f = sqrt_price as f64 / (Q64 as f64);
    sqrt_price_f * sqrt_price_f
}

/// Simplified calculation using reserves (for backwards compatibility)
/// Less accurate than DBC formula but works without liquidity parameter
pub fn calculate_expected_tokens_out(
    sol_in: u64,
    base_reserve: u64,
    quote_reserve: u64,
) -> u64 {
    // Simple approximation: tokens = sol_in × base_reserve / quote_reserve
    // This is a rough estimate - actual DBC uses sqrt_price curve segments
    if quote_reserve == 0 {
        return 0;
    }
    let numerator = (sol_in as u128) * (base_reserve as u128);
    let denominator = quote_reserve as u128;
    (numerator / denominator) as u64
}

/// Simplified calculation using reserves (for backwards compatibility)
pub fn calculate_expected_sol_out(
    tokens_in: u64,
    base_reserve: u64,
    quote_reserve: u64,
) -> u64 {
    // Simple approximation: sol = tokens_in × quote_reserve / base_reserve
    // This is a rough estimate - actual DBC uses sqrt_price curve segments
    if base_reserve == 0 {
        return 0;
    }
    let numerator = (tokens_in as u128) * (quote_reserve as u128);
    let denominator = base_reserve as u128;
    (numerator / denominator) as u64
}

// =============================================================================
// Complete Transaction Builders (with proper slippage)
// =============================================================================

/// Build complete BUY transaction with WSOL wrapping
pub fn build_buy_with_wrap(
    pool_address: &Pubkey,
    pool: &VirtualPool,
    pool_config: &PoolConfig,
    wallet: &Pubkey,
    sol_amount: u64,
    slippage_bps: u64,
) -> Vec<solana_instruction::Instruction> {
    // Get liquidity from the current curve segment (first active segment)
    // Find the segment that contains current sqrt_price
    println!("POOL config decimal: {}", pool_config.token_decimal);
    
    let mut liquidity = 0u128;
    for i in 0..pool_config.curve.len() {
        if pool_config.curve[i].liquidity > 0 {
            if pool.sqrt_price < pool_config.curve[i].sqrt_price {
                liquidity = pool_config.curve[i].liquidity;
                break;
            }
        }
    }
    // Fallback to first segment if not found
    if liquidity == 0 {
        liquidity = pool_config.curve[0].liquidity;
    }
    
    // Calculate expected tokens using DBC formula
    let expected_tokens = calculate_tokens_out_dbc(
        sol_amount,
        pool.sqrt_price,
        liquidity,
        100,  // 1% fee estimate
    );
    
    // Apply slippage for minimum output
    let minimum_amount_out = ((expected_tokens as u128) * (10000 - slippage_bps) as u128 / 10000) as u64;
    
    // Calculate current price for display
    let price_per_token = get_price_from_sqrt_price(pool.sqrt_price);
    
    println!("   📊 DBC Price Calculation:");
    println!("      - SOL in: {} lamports ({} SOL)", sol_amount, sol_amount as f64 / 1e9);
    println!("      - Current sqrt_price: {}", pool.sqrt_price);
    println!("      - Liquidity: {:.2e} (raw: {})", liquidity as f64, liquidity);
    println!("      - Price per token: {:.12} SOL", price_per_token);
    let token_divisor = 10u64.pow(pool_config.token_decimal as u32);
    println!("      - Expected tokens: {}", expected_tokens as f64 / token_divisor as f64);
    println!("      - Min tokens ({}% slippage): {}", slippage_bps as f64 / 100.0, minimum_amount_out);
    
    let mut instructions = Vec::new();
    
    // 1. Wrap SOL to WSOL
    instructions.extend(wrap_sol_instructions(wallet, sol_amount));
    
    // 2. Create output token ATA if needed
    let token_base_program = get_token_program_from_pool_type(pool.pool_type);
    instructions.push(create_ata_instruction(
        wallet,
        wallet,
        &pool.base_mint,
        &token_base_program,
    ));

    
    // 3. Swap (buy token)
    instructions.push(build_buy_instruction(
        pool_address,
        pool,
        pool_config,
        wallet,
        sol_amount,
        minimum_amount_out,
    ));
    
    // 4. Close WSOL account to recover any leftover SOL
    // instructions.push(close_wsol_instruction(wallet));
    
    instructions
}

/// Build complete SELL transaction with WSOL unwrapping
pub fn build_sell_with_unwrap(
    pool_address: &Pubkey,
    pool: &VirtualPool,
    pool_config: &PoolConfig,
    wallet: &Pubkey,
    token_amount: u64,
    slippage_bps: u64,
) -> Vec<solana_instruction::Instruction> {
    // Get liquidity from the current curve segment
    // For sell, we iterate backwards from current price
    let mut liquidity = 0u128;
    for i in (0..pool_config.curve.len()).rev() {
        if pool_config.curve[i].liquidity > 0 && pool_config.curve[i].sqrt_price > 0 {
            if pool.sqrt_price >= pool_config.curve[i].sqrt_price {
                // Use the next segment's liquidity (i+1 if exists)
                if i + 1 < pool_config.curve.len() && pool_config.curve[i + 1].liquidity > 0 {
                    liquidity = pool_config.curve[i + 1].liquidity;
                } else {
                    liquidity = pool_config.curve[i].liquidity;
                }
                break;
            }
        }
    }
    // Fallback to first segment if not found
    if liquidity == 0 {
        liquidity = pool_config.curve[0].liquidity;
    }
    
    // Calculate expected SOL using DBC formula
    let expected_sol = calculate_sol_out_dbc(
        token_amount,
        pool.sqrt_price,
        liquidity,
        100,  // 1% fee estimate
    );
    
    // Apply slippage to expected SOL
    let minimum_amount_out = ((expected_sol as u128) * (10000 - slippage_bps) as u128 / 10000) as u64;
    
    // Calculate current price for display
    let price_per_token = get_price_from_sqrt_price(pool.sqrt_price);
    
    println!("   📊 DBC Price Calculation (SELL):");
    println!("      - Tokens in: {}", token_amount);
    println!("      - Current sqrt_price: {}", pool.sqrt_price);
    println!("      - Liquidity: {:.2e} (raw: {})", liquidity as f64, liquidity);
    println!("      - Price per token: {:.12} SOL", price_per_token);
    println!("      - Expected SOL: {} lamports ({} SOL)", expected_sol, expected_sol as f64 / 1e9);
    println!("      - Min SOL ({}% slippage): {} lamports", slippage_bps as f64 / 100.0, minimum_amount_out);
    
    let mut instructions = Vec::new();
    
    // 1. Create WSOL ATA if needed (to receive SOL from sale)
    let wsol_mint = Pubkey::from_str(WSOL_MINT).unwrap();
    let token_program = Pubkey::from_str(TOKEN_PROGRAM_ID).unwrap();
    instructions.push(create_ata_instruction(wallet, wallet, &wsol_mint, &token_program));
    
    // 2. Swap (sell token for WSOL)
    instructions.push(build_sell_instruction(
        pool_address,
        pool,
        pool_config,
        wallet,
        token_amount,
        minimum_amount_out,
    ));
    
    // 3. Close WSOL account to convert back to native SOL
    instructions.push(close_wsol_instruction(wallet));
    
    instructions
}


fn main() {
    println!("===========================================");
    println!("Meteora DBC Buy/Sell Test Simulation");
    println!("===========================================\n");

    let rpc_url = "https://api.mainnet-beta.solana.com";
    let rpc = RpcClient::new_with_commitment(rpc_url.to_string(), CommitmentConfig::confirmed());

    println!("✅ Connected to: {}", rpc_url);

    let test_token_mint = "2aQg364xm5EMjWVYqEKAWTbtLT2J5cS2i2xQRu2gPphG"; 
    
    // Test wallet (for simulation only)
    let PRIVATE_KEY="";
    let test_wallet = Keypair::from_base58_string(PRIVATE_KEY);
    let wallet_pubkey = test_wallet.pubkey();

    println!("📍 Test wallet: {}", wallet_pubkey);
    println!("🪙 Token mint: {}\n", test_token_mint);

    // Check if placeholder
    if test_token_mint == "YOUR_TOKEN_MINT_ADDRESS_HERE" {
        println!("⚠️  Please replace YOUR_TOKEN_MINT_ADDRESS_HERE with a real DBC token mint.");
        println!("   You can find DBC pools on: https://app.meteora.ag/pools\n");
        
        println!("📋 Derived Addresses (constants):");
        println!("   Pool Authority: {}", get_pool_authority());
        println!("   Event Authority: {}", get_event_authority());
        println!("   Token Program: {}", TOKEN_PROGRAM_ID);
        
        return;
    }

    let token_mint = Pubkey::from_str(test_token_mint).expect("Invalid token mint");

    // Test 1: Find Pool
    println!(" Test 1: Finding pool for token...");
    
    match find_pool_by_token_mint(&rpc, &token_mint) {
        Ok(pool_address) => {
            println!(" Pool found: {}", pool_address);
            
            // Test 2: Fetch Pool Data
            println!("\n Test 2: Fetching pool data...");
            
            match fetch_virtual_pool(&rpc, &pool_address) {
                Ok(pool) => {
                    println!(" Pool fetched!");
                    println!("   - Base Mint: {}", pool.base_mint);
                    println!("   - Base Vault: {}", pool.base_vault);
                    println!("   - Quote Vault: {}", pool.quote_vault);
                    println!("   - Config: {}", pool.config);
                    println!("   - Pool Type: {} (0=SPL, 1=Token2022)", pool.pool_type);
                    println!("   - Is Migrated: {} (0=No/Active, 1=Yes/Completed)", pool.is_migrated);
                    println!("   - Base Reserve: {}", pool.base_reserve);
                    println!("   - Quote Reserve: {} ({} SOL)", pool.quote_reserve, pool.quote_reserve as f64 / 1e9);
                    
                    // Check if pool is still active
                    if pool.is_migrated != 0 {
                        println!("\n   ⚠️  WARNING: This pool has MIGRATED (completed). Cannot swap on bonding curve!");
                        println!("   The token may now be tradeable on a regular AMM (Raydium, Meteora DLMM, etc.)");
                    } else {
                        println!("\n   ✅ Pool is ACTIVE - bonding curve trades allowed!");
                    }
                    
                    // Test 3: Fetch PoolConfig
                    println!("\n Test 3: Fetching pool config...");
                    
                    match fetch_pool_config(&rpc, &pool.config) {
                        Ok(pool_config) => {
                            println!(" PoolConfig fetched!");
                            println!("   - Quote Mint: {}", pool_config.quote_mint);
                            println!("   - Fee Claimer: {}", pool_config.fee_claimer);
                            println!("   - Token Decimal: {}", pool_config.token_decimal);
                            
                            // Test 4: Build Buy Instruction WITH WSOL wrapping
                            println!("\n Test 4: Building BUY with WSOL wrapping...");
                            
                            let buy_amount = 2_000_0000;
                            let slippage_bps = 400; // 1%
                            
                            let buy_instructions = build_buy_with_wrap(
                                &pool_address,
                                &pool,
                                &pool_config,
                                &wallet_pubkey,
                                buy_amount,
                                slippage_bps,
                            );
                            
                            println!("   Buy transaction built with {} instructions:", buy_instructions.len());
                            println!("   1. Create WSOL ATA");
                            println!("   2. Transfer SOL to WSOL ATA");
                            println!("   3. SyncNative (wrap)");
                            println!("   4. Create output token ATA");
                            println!("   5. Swap (buy)");
                            println!("   6. Close WSOL account");
                            
                            // Test 5: Build Sell Instruction WITH unwrapping
                            println!("\nTest 5: Building SELL with WSOL unwrapping...");
                            // 5251116 tokens * 10^decimals = raw amount
                            let sell_amount: u64 = 5251116 * 10u64.pow(pool_config.token_decimal as u32);

                            
                            let sell_instructions = build_sell_with_unwrap(
                                &pool_address,
                                &pool,
                                &pool_config,
                                &wallet_pubkey,
                                sell_amount,
                                slippage_bps,
                            );
                            
                            println!("   Sell transaction built with {} instructions:", sell_instructions.len());
                            println!("   1. Create WSOL ATA (to receive)");
                            println!("   2. Swap (sell)");
                            println!("   3. Close WSOL account (unwrap to SOL)");
                            
                            // Test 6: Send the BUY transaction
                            println!("\n Test 6: Sending BUY transaction...");
                            
                            // Get recent blockhash
                            let blockhash = rpc.get_latest_blockhash().unwrap();
                            
                            // Create and SIGN the transaction
                            let mut transaction = Transaction::new_with_payer(&buy_instructions, Some(&wallet_pubkey));
                            transaction.sign(&[&test_wallet], blockhash);
                            
                            match rpc.send_and_confirm_transaction(&transaction) {
                                Ok(signature) => {
                                    println!("   ✅ BUY Transaction successful!");
                                    println!("   Signature: {}", signature);
                                    println!("   View on Solscan: https://solscan.io/tx/{}", signature);
                                    
                                    // Test 7: Send the SELL transaction
                                    println!("\n Test 7: Sending SELL transaction...");
                                    
                                    // Get fresh blockhash for sell
                                    let blockhash_sell = rpc.get_latest_blockhash().unwrap();
                                    
                                    // Create and SIGN the sell transaction
                                    let mut sell_tx = Transaction::new_with_payer(&sell_instructions, Some(&wallet_pubkey));
                                    sell_tx.sign(&[&test_wallet], blockhash_sell);
                                    
                                    match rpc.send_and_confirm_transaction(&sell_tx) {
                                        Ok(sig) => {
                                            println!("   ✅ SELL Transaction successful!");
                                            println!("   Signature: {}", sig);
                                            println!("   View on Solscan: https://solscan.io/tx/{}", sig);
                                        }
                                        Err(e) => println!("   ❌ SELL Transaction error: {}", e),
                                    }
                                }
                                Err(e) => println!("   ❌ BUY Transaction error: {}", e),
                            }
                        }
                        Err(e) => println!("   Failed to fetch pool config: {}", e),
                    }
                }
                Err(e) => println!("   Failed to fetch pool: {}", e),
            }
        }
        Err(e) => println!("    Pool not found: {}", e),
    }

    println!("\n===========================================");
    println!("Test Complete!");
    println!("===========================================");
}