pump-rust-client 0.1.7

Rust SDK for the pump and pump_amm Solana programs: instruction builders, quoting, PDA helpers, and optional RPC client features.
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//! Fetches the admin-initialized PDAs the SDK needs (`Global`, `FeeConfig`,
//! mayhem `global-params`/`sol-vault`, the pump trade ALT, etc.) from a
//! Solana cluster and dumps them to `artifacts/accounts_to_load.zst` — the
//! file the local validator boots with via
//! `src/bin/local_validator/main.rs`.
//!
//! Network selection (which ALT / fixture layout to use):
//!   - `--network devnet|mainnet` (CLI), or `PUMP_NETWORK` — defaults to devnet.
//!
//! RPC endpoint precedence:
//!   1. `--rpc-url <URL>` or a single positional `<RPC_URL>` (same meaning)
//!   2. `PUMP_CLONE_RPC`
//!   3. Public Solana cluster RPC for the selected network
//!
//! Per-PDA mainnet override: entries in `fixed_pdas` carry a
//! `fetch_from_mainnet` bool. When set, that PDA is fetched from mainnet even
//! on a devnet run via a separate `RpcClient`. The mainnet endpoint comes from
//! `PUMP_CLONE_MAINNET_RPC` (if set) or the public mainnet-beta URL.
//!
//! A `.env` in the current directory is loaded when present (`dotenvy`), so
//! `PUMP_CLONE_RPC` / `PUMP_CLONE_MAINNET_RPC` / `PUMP_NETWORK` can live there.
//!
//! Run once before `cargo run --features local-validator --bin local-validator`:
//!   `cargo run --features local-validator --bin clone_devnet_accounts -- --help`

use std::collections::HashMap;
use std::fs;

use anchor_lang::AccountSerialize;
use anchor_spl::token::spl_token;
use solana_client::rpc_client::RpcClient;
use solana_program::program_pack::Pack;
use solana_sdk::account::Account;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::rent::Rent;
use solana_sdk::system_program;

use pump_rust_client::accounts::pump_amm::decode_pool;
use pump_rust_client::accounts::{decode_bonding_curve, decode_global, decode_sharing_config};
use pump_rust_client::constants;
use pump_rust_client::pda;
use pump_rust_client::state::Global;

#[path = "../../../tests/common/fixtures.rs"]
mod fixtures;
use fixtures::{FixtureMint, FIXTURE_MINTS};

const OUT_PATH: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/artifacts/accounts_to_load.zst"
);

/// Canonical mainnet Raydium AMM v4 SOL/USDC pool and every sibling
/// account the swap CPI may touch.
///
/// The `pump_stables_router` program (see `bonding_curve_v2.rs` /
/// `pump_swap_v2.rs`) CPIs into this pool for the SOL <-> USDC leg of any
/// USDC-quoted trade. We always fetch from mainnet because (a) devnet has
/// no equivalent pool and (b) the router pins the v4 mainnet authority,
/// so a devnet pool would fail on-chain anyway.
///
/// The Raydium V4 `SwapBaseIn` instruction takes 17 accounts (open-orders
/// variant, no target-orders slot) covering the AMM side, the OpenBook
/// market, and the user. To keep the local validator self-contained we
/// clone every one of them so the CPI works whether it falls into the
/// AMM-only or hybrid-orderbook path. Values come from Raydium's public
/// liquidity-pool list for pool `58oQChx4…`.
mod raydium_sol_usdc {
    use super::Pubkey;
    use solana_program::pubkey;

    // AMM side
    pub const POOL: Pubkey = pubkey!("58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2");
    pub const AMM_AUTHORITY: Pubkey = pubkey!("5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1");
    pub const OPEN_ORDERS: Pubkey = pubkey!("HRk9CMrpq7Jn9sh7mzxE8CChHG8dneX9p475QKz4Fsfc");
    pub const TARGET_ORDERS: Pubkey = pubkey!("CZza3Ej4Mc58MnxWA385itCC9jCo3L1D7zc3LKy1bZMR");
    pub const WSOL_VAULT: Pubkey = pubkey!("DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz");
    pub const USDC_VAULT: Pubkey = pubkey!("HLmqeL62xR1QoZ1HKKbXRrdN1p3phKpxRMb2VVopvBBz");

    // OpenBook market side. `MARKET_PROGRAM_ID` is the OpenBook DEX program
    // address — it must be loaded as a *program* on the local validator
    // (via `dump-programs`), not snapshotted as an account, so it's not in
    // the fetch list below.
    #[allow(dead_code)]
    pub const MARKET_PROGRAM_ID: Pubkey = pubkey!("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX");
    pub const MARKET: Pubkey = pubkey!("8BnEgHoWFysVcuFFX7QztDmzuH8r5ZFvyP3sYwn1XTh6");
    pub const MARKET_AUTHORITY: Pubkey = pubkey!("CTz5UMLQm2SRWHzQnU62Pi4yJqbNGjgRBHqqp6oDHfF7");
    pub const MARKET_BASE_VAULT: Pubkey = pubkey!("CKxTHwM9fPMRRvZmFnFoqKNd9pQR21c5Aq9bh5h9oghX");
    pub const MARKET_QUOTE_VAULT: Pubkey = pubkey!("6A5NHCj1yF6urc9wZNe6Bcjj4LVszQNj5DwAWG97yzMu");
    pub const MARKET_BIDS: Pubkey = pubkey!("5jWUncPNBMZJ3sTHKmMLszypVkoRK6bfEQMQUHweeQnh");
    pub const MARKET_ASKS: Pubkey = pubkey!("EaXdHx7x3mdGA38j5RSmKYSXMzAFzzUXCLNBEDXDn1d5");
    // `MARKET_EVENT_QUEUE` was previously `8CvwxZ9Dg1LRxpgHsvQwYDqEYFA6jSdNG6N4qbSCC4SD`
    // but that address does not exist on mainnet. Left out of the clone
    // list — fill in once we have a confirmed pubkey.
    // pub const MARKET_EVENT_QUEUE: Pubkey = pubkey!("…");
}

#[derive(Clone, Copy, Debug)]
enum Network {
    Devnet,
    Mainnet,
}

impl Network {
    fn parse(s: &str) -> Result<Self, String> {
        match s.trim().to_ascii_lowercase().as_str() {
            "mainnet" | "mainnet-beta" => Ok(Network::Mainnet),
            "devnet" => Ok(Network::Devnet),
            other => Err(format!(
                "network must be devnet or mainnet (or mainnet-beta), got `{other}`"
            )),
        }
    }

    fn from_env() -> Self {
        let s = std::env::var("PUMP_NETWORK").unwrap_or_else(|_| "devnet".into());
        Self::parse(&s).unwrap_or_else(|e| panic!("{e}"))
    }

    fn default_rpc(self) -> &'static str {
        match self {
            // Public cluster RPCs (rate-limited). For dedicated providers, set `PUMP_CLONE_RPC`.
            Network::Devnet => "https://api.devnet.solana.com",
            Network::Mainnet => "https://api.mainnet-beta.solana.com",
        }
    }

    fn alt(self) -> Pubkey {
        match self {
            Network::Devnet => constants::DEVNET_ALT,
            Network::Mainnet => constants::MAINNET_ALT,
        }
    }

    fn alt_label(self) -> &'static str {
        match self {
            Network::Devnet => "alt:devnet",
            Network::Mainnet => "alt:mainnet",
        }
    }
}

struct Cli {
    network: Option<Network>,
    /// From `-r` / `--rpc-url` or a single positional argument.
    rpc_url: Option<String>,
}

fn print_usage() {
    println!(
        "\
clone_devnet_accounts — snapshot on-chain accounts for the local validator

Usage:
  clone_devnet_accounts [OPTIONS] [RPC_URL]

Options:
  -n, --network <NETWORK>   devnet | mainnet (sets which ALT / fixtures apply).
                              Overrides PUMP_NETWORK.
  -r, --rpc-url <URL>         RPC HTTP endpoint. Overrides PUMP_CLONE_RPC.
  -h, --help                  Print this help.

If RPC_URL is given as the first non-option argument, it is treated like --rpc-url.
Do not pass both --rpc-url and a positional RPC_URL.

RPC resolution: CLI (-r or positional) → PUMP_CLONE_RPC → public cluster RPC.

A .env file in the current directory is loaded when present.

Examples:
  clone_devnet_accounts --network devnet
  clone_devnet_accounts -r https://api.devnet.solana.com
  clone_devnet_accounts https://api.mainnet-beta.solana.com --network mainnet
"
    );
}

fn parse_cli() -> Result<Cli, String> {
    let mut network = None;
    let mut rpc_flag = None;
    let mut positional = None;

    let mut args = std::env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => {
                print_usage();
                std::process::exit(0);
            }
            "-n" | "--network" => {
                let v = args
                    .next()
                    .ok_or_else(|| "--network requires a value (devnet or mainnet)".to_string())?;
                network = Some(Network::parse(&v)?);
            }
            "-r" | "--rpc-url" => {
                let v = args
                    .next()
                    .ok_or_else(|| "--rpc-url requires a URL".to_string())?;
                rpc_flag = Some(v);
            }
            s if s.starts_with('-') => {
                return Err(format!("unknown option `{s}` (try --help)"));
            }
            s => {
                if positional.is_some() {
                    return Err(format!("unexpected extra argument `{s}`"));
                }
                positional = Some(s.to_string());
            }
        }
    }

    if rpc_flag.is_some() && positional.is_some() {
        return Err("use either --rpc-url or one positional RPC URL, not both".into());
    }

    Ok(Cli {
        network,
        rpc_url: rpc_flag.or(positional),
    })
}

/// `(label, address, required, fetch_from_mainnet)`. Required entries panic
/// if absent on the chosen cluster; optional entries are skipped when not
/// initialized (e.g. signer-only PDAs or program-state that's lazily
/// created). When `fetch_from_mainnet` is `true` the entry is fetched from
/// mainnet regardless of `--network`; flip back to `false` to revert that
/// PDA to the selected-network fetch.
fn fixed_pdas(network: Network) -> Vec<(&'static str, Pubkey, bool, bool)> {
    vec![
        ("pump:global", pda::pump::global().0, true, false),
        (
            "pump:event_authority",
            pda::pump::event_authority().0,
            false,
            false,
        ),
        (
            "pump:mint_authority",
            pda::pump::mint_authority().0,
            false,
            false,
        ),
        (
            "pump:global_volume_accumulator",
            pda::pump::global_volume_accumulator().0,
            true,
            false,
        ),
        ("pump:fee_config", pda::pump::fee_config().0, true, false),
        (
            "pump_amm:global_config",
            pda::pump_amm::global_config().0,
            false,
            false,
        ),
        (
            "pump_amm:event_authority",
            pda::pump_amm::event_authority().0,
            false,
            false,
        ),
        (
            "pump_amm:global_volume_accumulator",
            pda::pump_amm::global_volume_accumulator().0,
            false,
            false,
        ),
        (
            "pump_amm:fee_config",
            pda::pump_amm::fee_config().0,
            true,
            false,
        ),
        (
            "pump_agent_payments:global_config",
            pda::pump_agent_payments::global_config().0,
            false,
            false,
        ),
        (
            "mayhem:global_params",
            pda::mayhem::global_params().0,
            true,
            false,
        ),
        ("mayhem:sol_vault", pda::mayhem::sol_vault().0, true, false),
        // ALT for the cluster — required so the test's full create_coin
        // versioned tx can compress shared accounts under the 1232-byte limit.
        (network.alt_label(), network.alt(), true, false),
        // Raydium AMM v4 SOL/USDC pool — every sibling account the swap CPI
        // may touch, always fetched from mainnet (see `raydium_sol_usdc`
        // doc-comment for why). All entries are marked `required` because a
        // partial clone will fail the swap unpredictably at runtime; if any
        // mainnet fetch returns `None`, we'd rather hear about it now.
        (
            "raydium_amm_v4:sol_usdc:pool",
            raydium_sol_usdc::POOL,
            true,
            true,
        ),
        (
            "raydium_amm_v4:sol_usdc:amm_authority",
            raydium_sol_usdc::AMM_AUTHORITY,
            false,
            true,
        ),
        (
            "raydium_amm_v4:sol_usdc:open_orders",
            raydium_sol_usdc::OPEN_ORDERS,
            true,
            true,
        ),
        (
            "raydium_amm_v4:sol_usdc:target_orders",
            raydium_sol_usdc::TARGET_ORDERS,
            true,
            true,
        ),
        (
            "raydium_amm_v4:sol_usdc:wsol_vault",
            raydium_sol_usdc::WSOL_VAULT,
            true,
            true,
        ),
        (
            "raydium_amm_v4:sol_usdc:usdc_vault",
            raydium_sol_usdc::USDC_VAULT,
            true,
            true,
        ),
        (
            "openbook:sol_usdc:market",
            raydium_sol_usdc::MARKET,
            true,
            true,
        ),
        (
            "openbook:sol_usdc:market_authority",
            raydium_sol_usdc::MARKET_AUTHORITY,
            false,
            true,
        ),
        (
            "openbook:sol_usdc:market_base_vault",
            raydium_sol_usdc::MARKET_BASE_VAULT,
            true,
            true,
        ),
        (
            "openbook:sol_usdc:market_quote_vault",
            raydium_sol_usdc::MARKET_QUOTE_VAULT,
            true,
            true,
        ),
        (
            "openbook:sol_usdc:market_bids",
            raydium_sol_usdc::MARKET_BIDS,
            true,
            true,
        ),
        (
            "openbook:sol_usdc:market_asks",
            raydium_sol_usdc::MARKET_ASKS,
            true,
            true,
        ),
        // openbook:sol_usdc:market_event_queue — the address we had
        // (8CvwxZ9Dg…) does not exist on mainnet; left commented until we
        // confirm a real one. Raydium can swap without it via the AMM-only
        // path since the router passes a placeholder for this slot anyway.
        // (
        //     "openbook:sol_usdc:market_event_queue",
        //     raydium_sol_usdc::MARKET_EVENT_QUEUE,
        //     true,
        //     true,
        // ),
        // OpenBook fee-discount mints. Not strictly part of the SOL/USDC
        // pool, but OpenBook references them in fee accounting paths; clone
        // them from mainnet so the local validator sees real mint state.
        // Optional — markets without fee-discount logic don't need them.
        (
            "openbook:srm_mint",
            solana_program::pubkey!("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),
            false,
            true,
        ),
        (
            "openbook:msrm_mint",
            solana_program::pubkey!("MSRMcoVyrFxnSgo5uXwone5SKcGhT1KEJMFEkMEWf9L"),
            false,
            true,
        ),
    ]
}

fn print_account(label: &str, key: &Pubkey, acct: &Account) {
    println!(
        "  {:<40} {} lamports={} owner={} data={}B",
        label,
        key,
        acct.lamports,
        acct.owner,
        acct.data.len()
    );
}

/// Pull `key` and stash it under `label`. Required entries panic when
/// missing (the test depending on the fixture would fail more
/// confusingly downstream); optional entries log a skip line.
fn clone_one(
    rpc: &RpcClient,
    out: &mut HashMap<Pubkey, Account>,
    label: &str,
    key: Pubkey,
    required: bool,
) -> Result<Option<Account>, Box<dyn std::error::Error>> {
    if let Some(existing) = out.get(&key) {
        print_account(label, &key, existing);
        return Ok(Some(existing.clone()));
    }
    let acct = rpc
        .get_account_with_commitment(&key, rpc.commitment())?
        .value;
    match acct {
        Some(acct) => {
            print_account(label, &key, &acct);
            out.insert(key, acct.clone());
            Ok(Some(acct))
        }
        None if required => {
            panic!("required fixture account `{label}` missing on cluster at {key}")
        }
        None => {
            println!("  {:<40} {} (not on cluster — skipped)", label, key);
            Ok(None)
        }
    }
}

/// Snapshot every PDA the SDK touches for `fixture.mint`. For graduated
/// mints, also snapshots the post-migration `pump_amm` `Pool` and its
/// base/quote/lp/creator-vault accounts so AMM tests have a working pool
/// on the local validator without needing to run a migration.
///
/// Pool derivation matches canonical pump AMM `pool` PDA layout (see
/// `pump-swap-sdk` / `PumpSdk::buy_quote_amm_*` with live vault balances):
///   `pool_creator = pda::pump::pool_authority(mint)` and `index = 0` —
/// the pump migration always uses index 0 against the deterministic
/// pool-authority PDA.
fn clone_fixture_mint(
    rpc: &RpcClient,
    out: &mut HashMap<Pubkey, Account>,
    fixture: &FixtureMint,
) -> Result<(), Box<dyn std::error::Error>> {
    let mint = fixture.mint;
    println!("📥 Fixture {} ({}):", fixture.label, mint);

    // The mint account itself (Token-2022 program owner for v2 coins).
    clone_one(rpc, out, "  mint", mint, true)?;

    // Bonding curve always exists; everything else hangs off its `creator`.
    let bonding_curve_key = pda::pump::bonding_curve(&mint).0;
    let bc_account = clone_one(rpc, out, "  bonding_curve", bonding_curve_key, true)?
        .expect("bonding_curve required entry returned None");
    let mut bc = decode_bonding_curve(&bc_account.data)?;
    // Remember the quote mint as it lives on-chain before any local patch:
    // the AMM pool and its quote-reserve ATA exist on the cluster at addresses
    // derived from THIS mint, regardless of any patch we apply below.
    let original_bc_quote_mint = bc.quote_mint;

    // Devnet curves are SOL-quoted; rewrite their `quote_mint` to
    // [`USDC_QUOTE_MINT`] so the local validator can exercise the
    // non-SOL-quote (USDC) trade path end-to-end. The Global has already been
    // patched in `whitelist_USDC_QUOTE_MINT_in_global` so the on-chain
    // `is_quote_mint_supported` check accepts this mint.
    if fixture.patch_quote_mint_to_test && bc.quote_mint != fixtures::USDC_QUOTE_MINT {
        let original_quote_mint = bc.quote_mint;
        bc.quote_mint = fixtures::USDC_QUOTE_MINT;
        let mut new_data = Vec::new();
        bc.try_serialize(&mut new_data)?;
        let entry = out
            .get_mut(&bonding_curve_key)
            .expect("bonding_curve must be present in `out` before patching");
        if new_data.len() < entry.data.len() {
            new_data.resize(entry.data.len(), 0);
        }
        entry.data = new_data;
        println!(
            "🛠  Patched bonding_curve.quote_mint -> {} for {}",
            fixtures::USDC_QUOTE_MINT,
            fixture.label
        );

        // The bonding curve's quote-reserve ATA lives at the address derived
        // from the *original* quote mint; the program will now look it up at
        // the address derived from `USDC_QUOTE_MINT`. Fetch the original
        // ATA, rewrite its Token-account `mint` field, and re-insert it
        // under the new address so the reserves carry over.
        let original_quote_ata_key = pda::associated_token(
            &bonding_curve_key,
            &constants::SPL_TOKEN_PROGRAM_ID,
            &original_quote_mint,
        )
        .0;
        let new_quote_ata_key = pda::associated_token(
            &bonding_curve_key,
            &constants::SPL_TOKEN_PROGRAM_ID,
            &fixtures::USDC_QUOTE_MINT,
        )
        .0;
        let source = clone_one(
            rpc,
            out,
            "  bonding_curve_quote_ata (source)",
            original_quote_ata_key,
            false,
        )?;
        match source {
            Some(mut acct) => {
                let mut token = spl_token::state::Account::unpack(&acct.data)?;
                token.mint = fixtures::USDC_QUOTE_MINT;
                let mut new_data = vec![0u8; spl_token::state::Account::LEN];
                spl_token::state::Account::pack(token, &mut new_data)?;
                acct.data = new_data;
                out.insert(new_quote_ata_key, acct);
                // The original-mint ATA is no longer addressable correctly;
                // drop it so it doesn't ship in the snapshot.
                out.remove(&original_quote_ata_key);
                println!(
                    "🛠  Re-keyed bonding curve quote ATA {} -> {} (Token.mint -> {})",
                    original_quote_ata_key,
                    new_quote_ata_key,
                    fixtures::USDC_QUOTE_MINT
                );
            }
            None => {
                println!(
                    "ℹ️  No quote ATA on cluster at {} — skipping re-key (mint-to from USDC_QUOTE_MINT_AUTHORITY in tests to seed reserves)",
                    original_quote_ata_key
                );
            }
        }
    }

    // Per-mint PDAs the program does NOT lazy-init.
    let creator_vault = pda::pump::creator_vault(&bc.creator).0;
    clone_one(rpc, out, "  creator_vault", creator_vault, false)?;

    // creator_vault's quote-mint ATA — where v2 creator fees accumulate.
    // distribute_creator_fees_v2 / transfer_creator_fees_to_pump_v2 read
    // from this account, so it must be present and non-empty in the
    // snapshot. Clone from the on-chain (pre-patch) quote-mint derived
    // address, then re-key under the USDC_QUOTE_MINT derived address with
    // `Token.mint` rewritten, matching the bonding-curve quote ATA logic.
    {
        let on_chain_quote_mint = if original_bc_quote_mint == Pubkey::default() {
            constants::NATIVE_MINT
        } else {
            original_bc_quote_mint
        };
        let patched_quote_mint = if bc.quote_mint == Pubkey::default() {
            constants::NATIVE_MINT
        } else {
            bc.quote_mint
        };
        let original_cv_quote_ata = pda::associated_token(
            &creator_vault,
            &constants::SPL_TOKEN_PROGRAM_ID,
            &on_chain_quote_mint,
        )
        .0;
        let new_cv_quote_ata = pda::associated_token(
            &creator_vault,
            &constants::SPL_TOKEN_PROGRAM_ID,
            &patched_quote_mint,
        )
        .0;
        let source = clone_one(
            rpc,
            out,
            "  creator_vault_quote_ata (source)",
            original_cv_quote_ata,
            false,
        )?;
        if patched_quote_mint != on_chain_quote_mint {
            if let Some(mut acct) = source {
                let mut token = spl_token::state::Account::unpack(&acct.data)?;
                token.mint = patched_quote_mint;
                let mut new_data = vec![0u8; spl_token::state::Account::LEN];
                spl_token::state::Account::pack(token, &mut new_data)?;
                acct.data = new_data;
                out.insert(new_cv_quote_ata, acct);
                out.remove(&original_cv_quote_ata);
                println!(
                    "🛠  Re-keyed creator_vault_quote_ata {} -> {} (Token.mint -> {})",
                    original_cv_quote_ata, new_cv_quote_ata, patched_quote_mint
                );
            } else {
                println!(
                    "ℹ️  creator_vault_quote_ata not on cluster at {} — skipped re-key",
                    original_cv_quote_ata
                );
            }
        }
    }

    // sharing_config + shareholders (when present): each shareholder's
    // wallet plus their quote ATA so distribute_creator_fees_v2 can pay them.
    let sharing_config_key = pda::pump::sharing_config(&mint).0;
    if let Some(sharing_acct) = clone_one(rpc, out, "  sharing_config", sharing_config_key, false)?
    {
        let quote_mint = if bc.quote_mint == Pubkey::default() {
            constants::NATIVE_MINT
        } else {
            bc.quote_mint
        };
        let quote_token_program = out
            .get(&quote_mint)
            .map(|a| a.owner)
            .unwrap_or(constants::SPL_TOKEN_PROGRAM_ID);
        match decode_sharing_config(&sharing_acct.data) {
            Ok(sc) => {
                println!("    {} shareholder(s)", sc.shareholders.len());
                for (i, sh) in sc.shareholders.iter().enumerate() {
                    clone_one(
                        rpc,
                        out,
                        &format!("    shareholder[{i}]"),
                        sh.address,
                        false,
                    )?;
                    clone_one(
                        rpc,
                        out,
                        &format!("    shareholder[{i}]_quote_ata"),
                        pda::associated_token(&sh.address, &quote_token_program, &quote_mint).0,
                        false,
                    )?;
                }
            }
            Err(e) => println!("    sharing_config decode failed: {e}"),
        }
    }
    clone_one(
        rpc,
        out,
        "  bonding_curve_v2",
        pda::pump::bonding_curve_v2(&mint).0,
        false,
    )?;
    // Bonding curve's base + quote ATAs (Token-2022 base, classic-SPL wSOL quote).
    clone_one(
        rpc,
        out,
        "  bonding_curve_base_ata",
        pda::associated_token(
            &bonding_curve_key,
            &constants::SPL_TOKEN_2022_PROGRAM_ID,
            &mint,
        )
        .0,
        false,
    )?;
    clone_one(
        rpc,
        out,
        "  bonding_curve_wsol_ata",
        pda::associated_token(
            &bonding_curve_key,
            &constants::SPL_TOKEN_PROGRAM_ID,
            &constants::NATIVE_MINT,
        )
        .0,
        false,
    )?;

    // Post-migration AMM pool, only when the curve has graduated. The
    // pool_authority + index=0 derivation matches what the program emits
    // on migration; if the snapshot pre-dates migration, the pool will
    // simply be missing and the AMM tests will be skipped at runtime.
    if bc.complete {
        let pool_creator = pda::pump::pool_authority(&mint).0;
        let on_chain_quote_mint = if original_bc_quote_mint == Pubkey::default() {
            constants::NATIVE_MINT
        } else {
            original_bc_quote_mint
        };
        let patched_quote_mint = if bc.quote_mint == Pubkey::default() {
            constants::NATIVE_MINT
        } else {
            bc.quote_mint
        };
        let original_pool_key =
            pda::pump_amm::pool(0, &pool_creator, &mint, &on_chain_quote_mint).0;
        let new_pool_key = pda::pump_amm::pool(0, &pool_creator, &mint, &patched_quote_mint).0;
        let pool_account = clone_one(rpc, out, "  pool (source)", original_pool_key, false)?;
        if let Some(mut pool_account) = pool_account {
            let mut pool = decode_pool(&pool_account.data)?;
            let original_pool_quote_ata = pool.pool_quote_token_account;
            clone_one(rpc, out, "    lp_mint", pool.lp_mint, true)?;
            clone_one(
                rpc,
                out,
                "    pool_base_token_account",
                pool.pool_base_token_account,
                true,
            )?;
            clone_one(
                rpc,
                out,
                "    pool_quote_token_account",
                pool.pool_quote_token_account,
                true,
            )?;
            // Coin-creator vault authority + its quote ATA (where AMM
            // creator fees accrue). ATA may not exist yet if no fees have
            // ever been claimed against this pool.
            let cc_vault_authority =
                pda::pump_amm::coin_creator_vault_authority(&pool.coin_creator).0;
            clone_one(
                rpc,
                out,
                "    coin_creator_vault_authority",
                cc_vault_authority,
                false,
            )?;
            clone_one(
                rpc,
                out,
                "    coin_creator_vault_quote_ata",
                pda::associated_token(
                    &cc_vault_authority,
                    &constants::SPL_TOKEN_PROGRAM_ID,
                    &constants::NATIVE_MINT,
                )
                .0,
                false,
            )?;

            // If the bonding curve's quote_mint was patched, the example /
            // test code derives the AMM pool from the patched quote mint and
            // expects to find the pool (and its quote-reserve token account)
            // at the new derived addresses. Re-key the snapshot accordingly:
            // patch the pool's `quote_mint` + `pool_quote_token_account`
            // fields, re-insert at the new pool key, and re-key the
            // quote-reserve token account (rewriting its Token-account `mint`
            // field) under its new derived ATA.
            if patched_quote_mint != on_chain_quote_mint {
                let new_pool_quote_ata = pda::associated_token(
                    &new_pool_key,
                    &constants::SPL_TOKEN_PROGRAM_ID,
                    &patched_quote_mint,
                )
                .0;
                pool.quote_mint = patched_quote_mint;
                pool.pool_quote_token_account = new_pool_quote_ata;
                let mut new_pool_data = Vec::new();
                pool.try_serialize(&mut new_pool_data)?;
                if new_pool_data.len() < pool_account.data.len() {
                    new_pool_data.resize(pool_account.data.len(), 0);
                }
                pool_account.data = new_pool_data;
                out.insert(new_pool_key, pool_account);
                out.remove(&original_pool_key);
                println!(
                    "🛠  Re-keyed pool {} -> {} (quote_mint -> {})",
                    original_pool_key, new_pool_key, patched_quote_mint
                );

                if let Some(mut quote_ata_acct) = out.remove(&original_pool_quote_ata) {
                    let mut token = spl_token::state::Account::unpack(&quote_ata_acct.data)?;
                    token.mint = patched_quote_mint;
                    // Owner of pool_quote_token_account stays the pool
                    // authority pubkey baked in at on-chain init; leave it.
                    let mut new_data = vec![0u8; spl_token::state::Account::LEN];
                    spl_token::state::Account::pack(token, &mut new_data)?;
                    quote_ata_acct.data = new_data;
                    out.insert(new_pool_quote_ata, quote_ata_acct);
                    println!(
                        "🛠  Re-keyed pool_quote_token_account {} -> {} (Token.mint -> {})",
                        original_pool_quote_ata, new_pool_quote_ata, patched_quote_mint
                    );
                } else {
                    println!(
                        "ℹ️  pool_quote_token_account {} missing from snapshot — skipped re-key",
                        original_pool_quote_ata
                    );
                }
            }
        }
    }

    Ok(())
}

/// Whitelist [`fixtures::USDC_QUOTE_MINT`] inside the cloned `Global` so the
/// program's `is_quote_mint_supported` check accepts it during local-validator
/// `create_v2` / `buy_v2` / `sell_v2` flows. Idempotent: no-op if the mint is
/// already in the array. The re-serialized bytes must be the same length as
/// the original because `whitelisted_quote_mints` is fixed-size; the
/// `assert_eq!` is a tripwire if the IDL ever drifts.
fn whitelist_test_quote_mint_in_global(
    out: &mut HashMap<Pubkey, Account>,
    global: &Global,
) -> Result<(), Box<dyn std::error::Error>> {
    if global
        .whitelisted_quote_mints
        .contains(&fixtures::USDC_QUOTE_MINT)
    {
        println!(
            "🛠  Quote mint {} already whitelisted in Global — skipping",
            fixtures::USDC_QUOTE_MINT
        );
        return Ok(());
    }
    let mut patched = global.clone();
    patched.whitelisted_quote_mints[0] = fixtures::USDC_QUOTE_MINT;
    let mut new_data = Vec::new();
    patched.try_serialize(&mut new_data)?;
    let key = pda::pump::global().0;
    let entry = out
        .get_mut(&key)
        .expect("pump:global must be present in `out` before patching");
    assert_eq!(
        entry.data.len(),
        new_data.len(),
        "Global re-serialization changed data length ({} -> {}); IDL drift?",
        entry.data.len(),
        new_data.len()
    );
    entry.data = new_data;
    println!(
        "🛠  Whitelisted quote mint {} in Global",
        fixtures::USDC_QUOTE_MINT
    );
    Ok(())
}

/// Insert a synthetic legacy SPL Token mint at [`fixtures::USDC_QUOTE_MINT`]
/// owned by [`fixtures::USDC_QUOTE_MINT_AUTHORITY`] so tests can
/// `mint_to` arbitrary balances on the local validator. Always overwrites:
/// re-running the clone script regenerates a fresh mint with supply=0.
fn synthesize_quote_mint(out: &mut HashMap<Pubkey, Account>) {
    let mint = spl_token::state::Mint {
        mint_authority: solana_program::program_option::COption::Some(
            fixtures::USDC_QUOTE_MINT_AUTHORITY,
        ),
        supply: 0,
        decimals: 6,
        is_initialized: true,
        freeze_authority: solana_program::program_option::COption::None,
    };
    let mut data = vec![0u8; spl_token::state::Mint::LEN];
    spl_token::state::Mint::pack(mint, &mut data).expect("pack test quote Mint");
    let acct = Account {
        lamports: Rent::default().minimum_balance(spl_token::state::Mint::LEN),
        data,
        owner: spl_token::ID,
        executable: false,
        rent_epoch: 0,
    };
    out.insert(fixtures::USDC_QUOTE_MINT, acct);
    println!(
        "🛠  Synthesized test quote mint at {} (authority {})",
        fixtures::USDC_QUOTE_MINT,
        fixtures::USDC_QUOTE_MINT_AUTHORITY
    );
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _ = dotenvy::dotenv();
    let cli =
        parse_cli().map_err(|msg| std::io::Error::new(std::io::ErrorKind::InvalidInput, msg))?;

    let network = cli.network.unwrap_or_else(Network::from_env);
    let rpc_url = cli
        .rpc_url
        .or_else(|| std::env::var("PUMP_CLONE_RPC").ok())
        .unwrap_or_else(|| network.default_rpc().to_string());
    let rpc = RpcClient::new(rpc_url.clone());
    println!("🌐 Cloning {network:?} from: {rpc_url}");

    let labeled = fixed_pdas(network);

    let needs_mainnet = labeled.iter().any(|(_, _, _, from_mainnet)| *from_mainnet);
    let mainnet_rpc: Option<RpcClient> = if needs_mainnet && !matches!(network, Network::Mainnet) {
        let mainnet_url = std::env::var("PUMP_CLONE_MAINNET_RPC")
            .unwrap_or_else(|_| Network::Mainnet.default_rpc().to_string());
        println!("🌐 Mainnet override RPC: {mainnet_url}");
        Some(RpcClient::new(mainnet_url))
    } else {
        None
    };

    let default_keys: Vec<Pubkey> = labeled
        .iter()
        .filter(|(_, _, _, from_mainnet)| !*from_mainnet)
        .map(|(_, k, _, _)| *k)
        .collect();
    let mainnet_keys: Vec<Pubkey> = labeled
        .iter()
        .filter(|(_, _, _, from_mainnet)| *from_mainnet)
        .map(|(_, k, _, _)| *k)
        .collect();

    let mut by_key: HashMap<Pubkey, Option<Account>> = HashMap::new();
    if !default_keys.is_empty() {
        println!(
            "📡 Fetching {} key(s) from {network:?} ({rpc_url})",
            default_keys.len()
        );
        for (k, a) in default_keys
            .iter()
            .copied()
            .zip(rpc.get_multiple_accounts(&default_keys)?.into_iter())
        {
            by_key.insert(k, a);
        }
    }
    if !mainnet_keys.is_empty() {
        let client = mainnet_rpc.as_ref().unwrap_or(&rpc);
        println!(
            "📡 Fetching {} key(s) from mainnet override",
            mainnet_keys.len()
        );
        for (k, a) in mainnet_keys
            .iter()
            .copied()
            .zip(client.get_multiple_accounts(&mainnet_keys)?.into_iter())
        {
            by_key.insert(k, a);
        }
    }

    let mut out: HashMap<Pubkey, Account> = HashMap::new();
    let mut global_account: Option<Account> = None;
    println!("📥 Fixed PDAs:");
    for (label, key, required, from_mainnet) in labeled.iter() {
        let suffix = if *from_mainnet { " (mainnet)" } else { "" };
        match by_key.remove(key).flatten() {
            Some(acct) => {
                print_account(&format!("{label}{suffix}"), key, &acct);
                if *label == "pump:global" {
                    global_account = Some(acct.clone());
                }
                out.insert(*key, acct);
            }
            None if *required => {
                let source = if *from_mainnet {
                    "mainnet".to_string()
                } else {
                    format!("{network:?}")
                };
                panic!("required account `{label}` missing on {source} at {key}");
            }
            None => {
                println!(
                    "  {:<40} {} (not on cluster — skipped)",
                    format!("{label}{suffix}"),
                    key
                );
            }
        }
    }

    let global = decode_global(&global_account.expect("pump:global must be set above").data)?;
    whitelist_test_quote_mint_in_global(&mut out, &global)?;
    let mut recipients: Vec<Pubkey> = Vec::new();
    recipients.push(global.fee_recipient);
    recipients.extend(global.fee_recipients.iter().copied());
    recipients.push(global.reserved_fee_recipient);
    recipients.extend(global.reserved_fee_recipients.iter().copied());
    recipients.extend(global.buyback_fee_recipients.iter().copied());
    recipients.retain(|p| *p != Pubkey::default());
    recipients.sort();
    recipients.dedup();
    println!(
        "🔎 Global yielded {} distinct fee/buyback recipient(s)",
        recipients.len()
    );

    if !recipients.is_empty() {
        let recipient_accounts = rpc.get_multiple_accounts(&recipients)?;
        println!("📥 Recipients:");
        for (key, maybe_acct) in recipients.iter().zip(recipient_accounts.into_iter()) {
            let acct = maybe_acct.unwrap_or_else(|| Account {
                lamports: 0,
                data: vec![],
                owner: system_program::ID,
                executable: false,
                rent_epoch: 0,
            });
            print_account("recipient", key, &acct);
            out.entry(*key).or_insert(acct);
        }
    }
    for fixture in FIXTURE_MINTS {
        clone_fixture_mint(&rpc, &mut out, fixture)?;
    }

    synthesize_quote_mint(&mut out);

    let bytes = bincode::serialize(&out)?;
    let compressed = zstd::stream::encode_all(&bytes[..], 3)?;
    if let Some(parent) = std::path::Path::new(OUT_PATH).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(OUT_PATH, &compressed)?;
    println!(
        "✅ Wrote {} accounts to {} ({} bytes raw, {} bytes zstd)",
        out.len(),
        OUT_PATH,
        bytes.len(),
        compressed.len()
    );
    Ok(())
}