bucks-api 0.2.0

White label stablecoin launchpad
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
use solana_program::pubkey::Pubkey;
use spl_associated_token_account::get_associated_token_address;
use steel::*;

use crate::{consts::*, instruction::*, state::*};

// =============================================================================
// Protocol Account Helpers
// =============================================================================

/// Returns the accounts needed for Kamino protocol operations.
pub fn kamino_accounts(vault_address: Pubkey) -> Vec<AccountMeta> {
    let vault_ctoken_address = get_associated_token_address(&vault_address, &CTOKEN_ADDRESS);

    vec![
        AccountMeta::new(vault_address, false),
        AccountMeta::new(OBLIGATION_ADDRESS, false),
        AccountMeta::new(LENDING_MARKET_ADDRESS, false),
        AccountMeta::new(LENDING_MARKET_AUTHORITY_ADDRESS, false),
        AccountMeta::new(RESERVE_ADDRESS, false),
        AccountMeta::new(USDC_ADDRESS, false),
        AccountMeta::new(RESERVE_LIQUIDITY_SUPPLY_ADDRESS, false),
        AccountMeta::new(CTOKEN_ADDRESS, false),
        AccountMeta::new(RESERVE_CTOKEN_ADDRESS, false),
        AccountMeta::new(get_associated_token_address(&vault_address, &USDC_ADDRESS), false),
        AccountMeta::new(vault_ctoken_address, false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(sysvar::instructions::ID, false),
        AccountMeta::new(RESERVE_FARM_USER_STATE_ADDRESS, false),
        AccountMeta::new(RESERVE_FARM_STATE_ADDRESS, false),
        AccountMeta::new_readonly(KFARMS_PROGRAM_ID, false),
        AccountMeta::new_readonly(SCOPE_PRICES_ADDRESS, false),
        AccountMeta::new_readonly(KLEND_PROGRAM_ID, false),
    ]
}

/// Returns the accounts needed for Perena protocol operations.
/// Matches the bankineco IDL structure for mint_w_yielding_gen / burn_for_yielding_gen.
pub fn perena_accounts(vault_address: Pubkey) -> Vec<AccountMeta> {
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);
    let vault_usd_star_address = get_associated_token_address(&vault_address, &USD_STAR_MINT);

    vec![
        // 0. vault_info (signer) - the "user" in Perena terms (our vault PDA)
        AccountMeta::new(vault_address, false),
        // 1. bank_state
        AccountMeta::new(PERENA_BANK_STATE, false),
        // 2. vault_state (Perena's vault state, not our vault)
        AccountMeta::new(PERENA_VAULT_STATE, false),
        // 3. oracle_state
        AccountMeta::new_readonly(PERENA_ORACLE_STATE, false),
        // 4. yielding_mint (USDC)
        AccountMeta::new_readonly(USDC_ADDRESS, false),
        // 5. bank_mint (USD*)
        AccountMeta::new(USD_STAR_MINT, false),
        // 6. vault_usdc_ata (user's USDC ATA - our vault's USDC)
        AccountMeta::new(vault_usdc_address, false),
        // 7. vault_usd_star_ata (user's USD* ATA - our vault's USD*)
        AccountMeta::new(vault_usd_star_address, false),
        // 8. yielding_vault_ata (Perena's USDC vault)
        AccountMeta::new(PERENA_YIELDING_VAULT, false),
        // 9. team_state
        AccountMeta::new(PERENA_TEAM_STATE, false),
        // 10. fee_team_ata
        AccountMeta::new(PERENA_FEE_TEAM_ATA, false),
        // 11. system_program
        AccountMeta::new_readonly(system_program::ID, false),
        // 12. token_program
        AccountMeta::new_readonly(spl_token::ID, false),
        // 13. yielding_mint_program (USDC token program)
        AccountMeta::new_readonly(spl_token::ID, false),
        // 14. associated_token_program
        AccountMeta::new_readonly(spl_associated_token_account::ID, false),
        // 15. perena_program
        AccountMeta::new_readonly(PERENA_PROGRAM_ID, false),
    ]
}

/// Returns protocol accounts based on protocol ID.
pub fn protocol_accounts(protocol_id: u8, vault_address: Pubkey) -> Vec<AccountMeta> {
    match protocol_id {
        PROTOCOL_KAMINO => kamino_accounts(vault_address),
        PROTOCOL_PERENA => perena_accounts(vault_address),
        _ => vec![],
    }
}

// =============================================================================
// Log Helpers
// =============================================================================

/// Build a Log instruction (for CPI from within the program).
pub fn log(signer: Pubkey, msg: &[u8]) -> Instruction {
    let mut data = Log {}.to_bytes();
    data.extend_from_slice(msg);
    Instruction {
        program_id: crate::ID,
        accounts: vec![AccountMeta::new(signer, true)],
        data,
    }
}

/// CPI call to emit a log event. The vault PDA signs.
pub fn program_log(accounts: &[AccountInfo], msg: &[u8]) -> Result<(), ProgramError> {
    invoke_signed(
        &log(*accounts[0].key, msg),
        accounts,
        &crate::ID,
        &[VAULT],
    )
}

// =============================================================================
// Admin Instructions
// =============================================================================

/// Initialize the vault with fee parameters and treasury.
pub fn init(signer: Pubkey, platform_fee_bps: u16, treasury: Pubkey) -> Instruction {
    let vault_address = vault_pda().0;
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new_readonly(USDC_ADDRESS, false),
            AccountMeta::new(vault_address, false),
            AccountMeta::new(vault_usdc_address, false),
            AccountMeta::new_readonly(system_program::ID, false),
            AccountMeta::new_readonly(spl_token::ID, false),
            AccountMeta::new_readonly(spl_associated_token_account::ID, false),
        ],
        data: Init {
            platform_fee_bps: platform_fee_bps.to_le_bytes(),
            _padding: [0u8; 6],
            treasury: treasury.to_bytes(),
        }
        .to_bytes(),
    }
}

/// Initialize a protocol registry.
pub fn init_protocol(signer: Pubkey, protocol_id: u8, name: &str, user_lookup_table: Option<Pubkey>) -> Instruction {
    let vault_address = vault_pda().0;
    let protocol_address = protocol_pda(protocol_id).0;

    // Get receipt token mint based on protocol.
    let receipt_token_mint = match protocol_id {
        PROTOCOL_KAMINO => CTOKEN_ADDRESS,
        PROTOCOL_PERENA => USD_STAR_MINT,
        _ => panic!("Unknown protocol"),
    };

    let vault_receipt_token_address = get_associated_token_address(&vault_address, &receipt_token_mint);

    // Convert name to bytes.
    let name_bytes = name.as_bytes();
    let mut name_array = [0u8; 32];
    let len = name_bytes.len().min(32);
    name_array[..len].copy_from_slice(&name_bytes[..len]);

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(protocol_address, false),
        AccountMeta::new_readonly(receipt_token_mint, false),
        AccountMeta::new(vault_receipt_token_address, false),
        AccountMeta::new_readonly(system_program::ID, false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(spl_associated_token_account::ID, false),
    ];

    // Add protocol-specific accounts.
    if protocol_id == PROTOCOL_KAMINO {
        let user_metadata_address = Pubkey::find_program_address(
            &[b"user_meta", vault_address.as_ref()],
            &klend_sdk::programs::KAMINO_LENDING_ID.to_bytes().into(),
        )
        .0;

        accounts.extend(vec![
            AccountMeta::new(OBLIGATION_ADDRESS, false),
            AccountMeta::new(LENDING_MARKET_ADDRESS, false),
            AccountMeta::new_readonly(USDC_ADDRESS, false),
            AccountMeta::new_readonly(USDC_ADDRESS, false),
            AccountMeta::new(user_metadata_address, false),
            AccountMeta::new(user_lookup_table.unwrap_or(signer), false),
            AccountMeta::new(LENDING_MARKET_AUTHORITY_ADDRESS, false),
            AccountMeta::new(RESERVE_ADDRESS, false),
            AccountMeta::new(RESERVE_FARM_USER_STATE_ADDRESS, false),
            AccountMeta::new(RESERVE_FARM_STATE_ADDRESS, false),
            AccountMeta::new_readonly(KFARMS_PROGRAM_ID, false),
            AccountMeta::new_readonly(KLEND_PROGRAM_ID, false),
            AccountMeta::new_readonly(sysvar::rent::ID, false),
            AccountMeta::new_readonly(system_program::ID, false),
        ]);
    }

    Instruction {
        program_id: crate::ID,
        accounts,
        data: InitProtocol {
            protocol_id,
            name: name_array,
        }
        .to_bytes(),
    }
}

/// Checkpoint a protocol's exchange rate.
pub fn checkpoint(signer: Pubkey, protocol_id: u8) -> Instruction {
    let vault_address = vault_pda().0;
    let protocol_address = protocol_pda(protocol_id).0;

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(protocol_address, false),
    ];

    // Add protocol-specific read accounts for getting exchange rate.
    match protocol_id {
        PROTOCOL_KAMINO => {
            accounts.push(AccountMeta::new_readonly(RESERVE_ADDRESS, false));
        }
        PROTOCOL_PERENA => {
            accounts.push(AccountMeta::new_readonly(PERENA_ORACLE_STATE, false));
        }
        _ => {}
    }

    Instruction {
        program_id: crate::ID,
        accounts,
        data: Checkpoint { protocol_id }.to_bytes(),
    }
}

/// Rebalance a single stable's position from one protocol to another.
///
/// This is a per-stable operation. To rebalance the entire pool, call this
/// for each stable that has funds in the source protocol. Can be parallelized
/// via Jito bundles.
pub fn rebalance(
    signer: Pubkey,
    stable_address: Pubkey,
    from_protocol: u8,
    to_protocol: u8,
    amount: u64,
) -> Instruction {
    let vault_address = vault_pda().0;
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);
    let from_protocol_address = protocol_pda(from_protocol).0;
    let to_protocol_address = protocol_pda(to_protocol).0;
    let from_position_address = position_pda(stable_address, from_protocol).0;
    let to_position_address = position_pda(stable_address, to_protocol).0;

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(stable_address, false),
        AccountMeta::new(from_protocol_address, false),
        AccountMeta::new(to_protocol_address, false),
        AccountMeta::new(from_position_address, false),
        AccountMeta::new(to_position_address, false),
        AccountMeta::new(vault_usdc_address, false),
        AccountMeta::new_readonly(system_program::ID, false),
        AccountMeta::new_readonly(spl_token::ID, false),
    ];

    // Add from protocol accounts.
    accounts.extend(protocol_accounts(from_protocol, vault_address));
    // Add to protocol accounts.
    accounts.extend(protocol_accounts(to_protocol, vault_address));

    Instruction {
        program_id: crate::ID,
        accounts,
        data: Rebalance {
            from_protocol,
            to_protocol,
            _padding: [0u8; 6],
            amount: amount.to_le_bytes(),
        }
        .to_bytes(),
    }
}

/// Set the primary protocol for new deposits.
pub fn set_primary_protocol(signer: Pubkey, protocol_id: u8) -> Instruction {
    let vault_address = vault_pda().0;
    let protocol_address = protocol_pda(protocol_id).0;

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(vault_address, false),
            AccountMeta::new_readonly(protocol_address, false),
        ],
        data: SetPrimaryProtocol { protocol_id }.to_bytes(),
    }
}

/// Pause or unpause the vault.
pub fn set_paused(signer: Pubkey, paused: bool) -> Instruction {
    let vault_address = vault_pda().0;

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(vault_address, false),
        ],
        data: SetPaused {
            paused: if paused { 1 } else { 0 },
        }
        .to_bytes(),
    }
}

/// Collect platform fees from a position.
/// Admin can call this to collect the protocol's share of yield from any position.
pub fn collect_platform_fee(
    signer: Pubkey,
    treasury: Pubkey,
    stable_address: Pubkey,
    protocol_id: u8,
) -> Instruction {
    let vault_address = vault_pda().0;
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);
    let protocol_address = protocol_pda(protocol_id).0;
    let position_address = position_pda(stable_address, protocol_id).0;

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(treasury, false),
        AccountMeta::new(vault_usdc_address, false),
        AccountMeta::new_readonly(stable_address, false),
        AccountMeta::new(protocol_address, false),
        AccountMeta::new(position_address, false),
        AccountMeta::new_readonly(spl_token::ID, false),
    ];

    // Add protocol-specific accounts for withdrawal.
    accounts.extend(protocol_accounts(protocol_id, vault_address));

    Instruction {
        program_id: crate::ID,
        accounts,
        data: CollectPlatformFee { protocol_id }.to_bytes(),
    }
}

/// Set the treasury address for platform fee collection.
pub fn set_treasury(signer: Pubkey, treasury: Pubkey) -> Instruction {
    let vault_address = vault_pda().0;

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(vault_address, false),
            AccountMeta::new_readonly(treasury, false),
        ],
        data: SetTreasury {
            treasury: treasury.to_bytes(),
        }
        .to_bytes(),
    }
}

/// Delete the vault account (for re-initialization after schema changes).
/// WARNING: This is destructive and should only be used during development/testing.
pub fn delete_vault(signer: Pubkey) -> Instruction {
    let vault_address = vault_pda().0;

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(vault_address, false),
        ],
        data: DeleteVault {}.to_bytes(),
    }
}

// =============================================================================
// Creator Instructions
// =============================================================================

/// Create a new stablecoin.
pub fn create(
    signer: Pubkey,
    payer: Pubkey,
    id: String,
    name: String,
    symbol: String,
    noise: [u8; 32],
) -> Instruction {
    // Convert `id` into [u8; 32].
    let id_bytes = id.as_bytes();
    if id_bytes.len() > 32 {
        panic!("Id must be at most 32 bytes");
    }
    let mut id_array = [0u8; 32];
    id_array[..id_bytes.len()].copy_from_slice(id_bytes);

    // Convert `symbol` into [u8; 32].
    let symbol_bytes = symbol.as_bytes();
    if symbol_bytes.len() > 32 {
        panic!("Symbol must be at most 32 bytes");
    }
    let mut symbol_array = [0u8; 32];
    symbol_array[..symbol_bytes.len()].copy_from_slice(symbol_bytes);

    // Convert `name` into [u8; 32].
    let name_bytes = name.as_bytes();
    if name_bytes.len() > 32 {
        panic!("Name must be at most 32 bytes");
    }
    let mut name_array = [0u8; 32];
    name_array[..name_bytes.len()].copy_from_slice(name_bytes);

    let mint_pda =
        Pubkey::find_program_address(&[MINT, noise.as_ref()], &crate::ID.to_bytes().into());

    let metadata_address = mpl_token_metadata::accounts::Metadata::find_pda(&mint_pda.0).0;
    let stable_address = stable_pda(mint_pda.0).0;

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(payer, true),
            AccountMeta::new(metadata_address, false),
            AccountMeta::new(stable_address, false),
            AccountMeta::new(mint_pda.0, false),
            AccountMeta::new_readonly(system_program::ID, false),
            AccountMeta::new_readonly(spl_token::ID, false),
            AccountMeta::new_readonly(spl_associated_token_account::ID, false),
            AccountMeta::new_readonly(mpl_token_metadata::ID, false),
            AccountMeta::new_readonly(sysvar::rent::ID, false),
        ],
        data: Create {
            id: id_array,
            name: name_array,
            symbol: symbol_array,
            noise,
            bump: mint_pda.1,
        }
        .to_bytes(),
    }
}

/// Update stablecoin authority.
pub fn update_authority(signer: Pubkey, mint_stable: Pubkey, new_authority: Pubkey) -> Instruction {
    let stable_address = stable_pda(mint_stable).0;

    Instruction {
        program_id: crate::ID,
        accounts: vec![
            AccountMeta::new(signer, true),
            AccountMeta::new(stable_address, false),
        ],
        data: UpdateAuthority {
            new_authority: new_authority.to_bytes(),
        }
        .to_bytes(),
    }
}

/// Claim yield from a stablecoin's position in a specific protocol.
pub fn claim(signer: Pubkey, mint_stable: Pubkey, protocol_id: u8, amount: u64, min_usdc_out: u64) -> Instruction {
    let stable_address = stable_pda(mint_stable).0;
    let signer_stable_address = get_associated_token_address(&signer, &mint_stable);
    let signer_usdc_address = get_associated_token_address(&signer, &USDC_ADDRESS);
    let vault_address = vault_pda().0;
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);
    let protocol_address = protocol_pda(protocol_id).0;
    let position_address = position_pda(stable_address, protocol_id).0;

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(signer, true),
        AccountMeta::new(signer_stable_address, false),
        AccountMeta::new(signer_usdc_address, false),
        AccountMeta::new_readonly(USDC_ADDRESS, false),
        AccountMeta::new(mint_stable, false),
        AccountMeta::new(stable_address, false),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(vault_usdc_address, false),
        AccountMeta::new(protocol_address, false),
        AccountMeta::new(position_address, false),
        AccountMeta::new_readonly(system_program::ID, false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(spl_associated_token_account::ID, false),
        AccountMeta::new_readonly(sysvar::instructions::ID, false),
        AccountMeta::new_readonly(crate::ID, false),
    ];

    // Add protocol-specific accounts.
    accounts.extend(protocol_accounts(protocol_id, vault_address));

    Instruction {
        program_id: crate::ID,
        accounts,
        data: Claim {
            amount: amount.to_le_bytes(),
            min_usdc_out: min_usdc_out.to_le_bytes(),
        }
        .to_bytes(),
    }
}

// =============================================================================
// User Instructions
// =============================================================================

/// Wrap USDC into stablecoin.
/// Creates the position account if it doesn't exist.
pub fn wrap(signer: Pubkey, mint_stable: Pubkey, protocol_id: u8, amount: u64) -> Instruction {
    let stable_address = stable_pda(mint_stable).0;
    let signer_stable_address = get_associated_token_address(&signer, &mint_stable);
    let signer_usdc_address = get_associated_token_address(&signer, &USDC_ADDRESS);
    let vault_address = vault_pda().0;
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);
    let protocol_address = protocol_pda(protocol_id).0;
    let position_address = position_pda(stable_address, protocol_id).0;

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(signer, true),
        AccountMeta::new(signer_stable_address, false),
        AccountMeta::new(signer_usdc_address, false),
        AccountMeta::new_readonly(USDC_ADDRESS, false),
        AccountMeta::new(mint_stable, false),
        AccountMeta::new(stable_address, false),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(vault_usdc_address, false),
        AccountMeta::new(protocol_address, false),
        AccountMeta::new(position_address, false),
        AccountMeta::new_readonly(system_program::ID, false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(spl_associated_token_account::ID, false),
        AccountMeta::new_readonly(sysvar::instructions::ID, false),
        AccountMeta::new_readonly(crate::ID, false),
    ];

    // Add protocol-specific accounts.
    accounts.extend(protocol_accounts(protocol_id, vault_address));

    Instruction {
        program_id: crate::ID,
        accounts,
        data: Wrap {
            amount: amount.to_le_bytes(),
        }
        .to_bytes(),
    }
}

/// Unwrap stablecoin to USDC from a single protocol.
/// For large withdrawals spanning multiple protocols, use `build_unwrap_bundle`.
/// Position must exist (created during wrap).
pub fn unwrap(signer: Pubkey, mint_stable: Pubkey, protocol_id: u8, amount: u64, min_usdc_out: u64) -> Instruction {
    let stable_address = stable_pda(mint_stable).0;
    let signer_stable_address = get_associated_token_address(&signer, &mint_stable);
    let signer_usdc_address = get_associated_token_address(&signer, &USDC_ADDRESS);
    let vault_address = vault_pda().0;
    let vault_usdc_address = get_associated_token_address(&vault_address, &USDC_ADDRESS);
    let protocol_address = protocol_pda(protocol_id).0;
    let position_address = position_pda(stable_address, protocol_id).0;

    let mut accounts = vec![
        AccountMeta::new(signer, true),
        AccountMeta::new(signer, true),
        AccountMeta::new(signer_stable_address, false),
        AccountMeta::new(signer_usdc_address, false),
        AccountMeta::new_readonly(USDC_ADDRESS, false),
        AccountMeta::new(mint_stable, false),
        AccountMeta::new(stable_address, false),
        AccountMeta::new(vault_address, false),
        AccountMeta::new(vault_usdc_address, false),
        AccountMeta::new(protocol_address, false),
        AccountMeta::new(position_address, false),
        AccountMeta::new_readonly(system_program::ID, false),
        AccountMeta::new_readonly(spl_token::ID, false),
        AccountMeta::new_readonly(spl_associated_token_account::ID, false),
        AccountMeta::new_readonly(sysvar::instructions::ID, false),
        AccountMeta::new_readonly(crate::ID, false),
    ];

    // Add protocol-specific accounts.
    accounts.extend(protocol_accounts(protocol_id, vault_address));

    Instruction {
        program_id: crate::ID,
        accounts,
        data: Unwrap {
            amount: amount.to_le_bytes(),
            min_usdc_out: min_usdc_out.to_le_bytes(),
        }
        .to_bytes(),
    }
}

// =============================================================================
// Bundle Helpers
// =============================================================================

/// Protocol allocation info for building unwrap bundles.
pub struct ProtocolAllocation {
    /// Protocol ID.
    pub protocol_id: u8,
    /// Amount of USDC available in this protocol.
    pub usdc_available: u64,
}

/// Builds a bundle of unwrap instructions for withdrawing across multiple protocols.
///
/// For large withdrawals that span multiple protocols, this function calculates
/// the optimal split and returns multiple instructions that should be submitted
/// as a Jito bundle for atomic execution.
///
/// # Arguments
/// * `signer` - The user's wallet address
/// * `mint_stable` - The stablecoin mint address
/// * `amount` - Total amount of stablecoins to unwrap
/// * `protocols` - List of protocols with their available USDC balances
///
/// # Returns
/// A vector of instructions, one per protocol that needs to be withdrawn from.
/// Submit these as a Jito bundle for atomic execution.
///
/// # Example
/// ```ignore
/// let protocols = vec![
///     ProtocolAllocation { protocol_id: PROTOCOL_KAMINO, usdc_available: 1000_000000 },
///     ProtocolAllocation { protocol_id: PROTOCOL_PERENA, usdc_available: 500_000000 },
/// ];
/// let bundle = build_unwrap_bundle(signer, mint, 1200_000000, &protocols);
/// // bundle[0] = unwrap 1000 USDC from Kamino
/// // bundle[1] = unwrap 200 USDC from Perena
/// ```
pub fn build_unwrap_bundle(
    _signer: Pubkey,
    _mint_stable: Pubkey,
    _amount: u64,
    _protocols: &[ProtocolAllocation],
) -> Vec<Instruction> {
    // TODO: Implement bundle building logic
    //
    // 1. Sort protocols by available USDC (descending) for optimal withdrawal
    // 2. Calculate how much to withdraw from each protocol:
    //    - Start with the protocol with most funds
    //    - Take min(remaining_amount, protocol.usdc_available)
    //    - Move to next protocol if more needed
    // 3. Build one unwrap instruction per protocol
    // 4. Return the vector of instructions
    //
    // The caller should submit these instructions as a Jito bundle
    // to ensure atomic execution across all protocols.
    todo!("Implement multi-protocol unwrap bundle builder")
}