Skip to main content

noviscia_asset_engine_sdk/
lib.rs

1//! # Noviscia Asset Engine SDK
2//!
3//! Instruction builders + PDA derivation for the **noviscia-asset-engine**
4//! on-chain program — the multi-asset token register & pool layout.
5//!
6//! Three standardized SPL profiles share one engine: SOL arrives as **wSOL**
7//! (Same decimals as native SOL, handled identically to any SPL asset), USDC,
8//! and the NVSC project token. Each asset owns a segregated `AssetPool` with
9//! its own capacity ceiling, premium baseline, and vault pair.
10//!
11//! Flagship builders:
12//! - `build_allocate_asset_capacity_ix` — single-slot JIT allocation that
13//!   verifies Merkle KYC, opens/rolls the 24h floating window, and atomically
14//!   CPIs the **principal** (the micro-premium is accrued, taxi-meter style).
15//! - `build_settle_daily_ix` — daily Clearing House settlement: the desk
16//!   treasury returns the exact native asset and the ledger resets.
17//! - `build_recredit_asset_capacity_ix` — releases unused slot capital back
18//!   into the pool.
19//! - `build_register_asset_ix` — onboards a mint into the token register.
20
21use solana_program::instruction::{AccountMeta, Instruction};
22use solana_program::pubkey::Pubkey;
23use solana_sdk::sysvar::rent::ID as RENT_ID;
24
25use noviscia_types::{
26    ASSET_AUTHORITY_SEED, ASSET_CREDIT_LINE_SEED, ASSET_ENGINE_PROGRAM_ID, ASSET_FEE_VAULT_SEED,
27    ASSET_LP_MINT_SEED, ASSET_LP_POSITION_SEED, ASSET_POOL_SEED, ASSET_REGISTRY_SEED,
28    ASSET_VAULT_SEED, BPS, DESK_POSITION_SEED, GRACE_SLOTS, LATE_FEE_BASE, LATE_FEE_RATE_BPS,
29    WINDOW_SLOTS,
30};
31
32pub use noviscia_types::{AssetEngineRegistry, AssetPool, DeskPosition, InstitutionalCreditLine};
33
34pub mod economics;
35pub mod velocity;
36
37// ── Anchor Discriminator ───────────────────────────────────────────────────
38
39/// First 8 bytes of `sha256("global:<name>")` — Solana's built-in SHA-256.
40pub fn anchor_discriminator(name: &str) -> [u8; 8] {
41    let preimage = format!("global:{name}");
42    let hash = solana_program::hash::hash(preimage.as_bytes());
43    let mut disc = [0u8; 8];
44    disc.copy_from_slice(&hash.to_bytes()[..8]);
45    disc
46}
47
48// ── PDA Derivation ─────────────────────────────────────────────────────────
49
50pub fn registry_pda(program_id: &Pubkey) -> Pubkey {
51    let (pda, _bump) = Pubkey::find_program_address(&[ASSET_REGISTRY_SEED], program_id);
52    pda
53}
54
55pub fn asset_pool_pda(program_id: &Pubkey, mint: &Pubkey) -> Pubkey {
56    let (pda, _bump) =
57        Pubkey::find_program_address(&[ASSET_POOL_SEED, mint.as_ref()], program_id);
58    pda
59}
60
61pub fn asset_vault_pda(program_id: &Pubkey, mint: &Pubkey) -> Pubkey {
62    let (pda, _bump) =
63        Pubkey::find_program_address(&[ASSET_VAULT_SEED, mint.as_ref()], program_id);
64    pda
65}
66
67pub fn asset_fee_vault_pda(program_id: &Pubkey, mint: &Pubkey) -> Pubkey {
68    let (pda, _bump) =
69        Pubkey::find_program_address(&[ASSET_FEE_VAULT_SEED, mint.as_ref()], program_id);
70    pda
71}
72
73pub fn asset_authority_pda(program_id: &Pubkey, mint: &Pubkey) -> Pubkey {
74    let (pda, _bump) =
75        Pubkey::find_program_address(&[ASSET_AUTHORITY_SEED, mint.as_ref()], program_id);
76    pda
77}
78
79pub fn credit_line_pda(program_id: &Pubkey, institution: &Pubkey) -> Pubkey {
80    let (pda, _bump) = Pubkey::find_program_address(
81        &[ASSET_CREDIT_LINE_SEED, institution.as_ref()],
82        program_id,
83    );
84    pda
85}
86
87/// Per-mint desk borrow mirror: `[desk-position, institution, mint]`.
88pub fn desk_position_pda(program_id: &Pubkey, institution: &Pubkey, mint: &Pubkey) -> Pubkey {
89    let (pda, _bump) = Pubkey::find_program_address(
90        &[DESK_POSITION_SEED, institution.as_ref(), mint.as_ref()],
91        program_id,
92    );
93    pda
94}
95
96/// ERC-4626 share-mint per pool: `[asset-lp-mint, mint]` (nUSDC / nSOL / nNVSC).
97pub fn asset_lp_mint_pda(program_id: &Pubkey, mint: &Pubkey) -> Pubkey {
98    let (pda, _bump) =
99        Pubkey::find_program_address(&[ASSET_LP_MINT_SEED, mint.as_ref()], program_id);
100    pda
101}
102
103/// Per-(pool, LP) share-position ledger: `[asset-lp-position, mint, lp]`.
104pub fn asset_lp_position_pda(
105    program_id: &Pubkey,
106    mint: &Pubkey,
107    lp: &Pubkey,
108) -> Pubkey {
109    let (pda, _bump) = Pubkey::find_program_address(
110        &[ASSET_LP_POSITION_SEED, mint.as_ref(), lp.as_ref()],
111        program_id,
112    );
113    pda
114}
115
116/// Per-asset plan used by `asset_register`.
117#[derive(Clone, Copy, Debug)]
118pub struct AssetParams {
119    pub decimals: u8,
120    pub base_premium_rate_bps: u16,
121    pub premium_cap_bps: u16,
122    pub max_capacity: u64,
123    pub min_premium_lamports: u64,
124    /// Basis points of paid premium credited to LPs (compounds their share value).
125    pub lp_yield_split_bps: u16,
126}
127
128/// Standard NVSC project-token profile (9 decimals, VAULT-scale tokens, no min premium).
129pub const NVSC_PROFILE: AssetParams = AssetParams {
130    decimals: 9,
131    base_premium_rate_bps: 30,
132    premium_cap_bps: 500,
133    max_capacity: 100_000_000_000_000,
134    min_premium_lamports: 0,
135    lp_yield_split_bps: 9_000,
136};
137
138/// Standard USDC profile (6 decimals, fast-cash pool, tighter ceiling).
139pub const USDC_PROFILE: AssetParams = AssetParams {
140    decimals: 6,
141    base_premium_rate_bps: 8,
142    premium_cap_bps: 250,
143    max_capacity: 5_000_000_000_000,
144    min_premium_lamports: 0,
145    lp_yield_split_bps: 9_000,
146};
147
148/// Standard wSOL profile (9 decimals, native-interop).
149pub const WSOL_PROFILE: AssetParams = AssetParams {
150    decimals: 9,
151    base_premium_rate_bps: 12,
152    premium_cap_bps: 300,
153    max_capacity: 100_000_000_000,
154    min_premium_lamports: 0,
155    lp_yield_split_bps: 9_000,
156};
157
158// ── Instruction Builders ───────────────────────────────────────────────────
159
160/// Build `initialize` — pins the platform mints + guard authority.
161#[allow(clippy::too_many_arguments)]
162pub fn build_initialize_ix(
163    program_id: Pubkey,
164    upgrade_authority: Pubkey,
165    breaker_authority: Pubkey,
166    risk_committee_authority: Pubkey,
167    wsol_mint: Pubkey,
168    usdc_mint: Pubkey,
169    nvsc_mint: Pubkey,
170) -> Instruction {
171    let accounts = vec![
172        AccountMeta::new(upgrade_authority, true),
173        AccountMeta::new(registry_pda(&program_id), false),
174        AccountMeta::new_readonly(solana_program::system_program::ID, false),
175    ];
176    let mut data = anchor_discriminator("initialize").to_vec();
177    data.extend_from_slice(breaker_authority.as_ref());
178    data.extend_from_slice(risk_committee_authority.as_ref());
179    data.extend_from_slice(upgrade_authority.as_ref());
180    data.extend_from_slice(wsol_mint.as_ref());
181    data.extend_from_slice(usdc_mint.as_ref());
182    data.extend_from_slice(nvsc_mint.as_ref());
183    Instruction { program_id, accounts, data }
184}
185
186/// Build `asset_register` — onboards a mint (Tier 3: Core Ecosystem Council,
187/// 5-of-7 Squads, 72h timelock).
188#[allow(clippy::too_many_arguments)]
189pub fn build_register_asset_ix(
190    program_id: Pubkey,
191    upgrade_authority: Pubkey,
192    mint: Pubkey,
193    params: AssetParams,
194) -> Instruction {
195    let accounts = vec![
196        AccountMeta::new(registry_pda(&program_id), false),
197        AccountMeta::new(upgrade_authority, true),
198        AccountMeta::new_readonly(mint, false),
199        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
200        AccountMeta::new(asset_vault_pda(&program_id, &mint), false),
201        AccountMeta::new(asset_fee_vault_pda(&program_id, &mint), false),
202        AccountMeta::new_readonly(asset_authority_pda(&program_id, &mint), false),
203        AccountMeta::new(asset_lp_mint_pda(&program_id, &mint), false),
204        AccountMeta::new_readonly(solana_program::system_program::ID, false),
205        AccountMeta::new_readonly(spl_token::ID, false),
206        AccountMeta::new_readonly(RENT_ID, false),
207    ];
208    let mut data = anchor_discriminator("asset_register").to_vec();
209    data.push(params.decimals);
210    data.extend_from_slice(&params.base_premium_rate_bps.to_le_bytes());
211    data.extend_from_slice(&params.premium_cap_bps.to_le_bytes());
212    data.extend_from_slice(&params.max_capacity.to_le_bytes());
213    data.extend_from_slice(&params.min_premium_lamports.to_le_bytes());
214    data.extend_from_slice(&params.lp_yield_split_bps.to_le_bytes());
215    Instruction { program_id, accounts, data }
216}
217
218/// Build `asset_update_params` — adjusts a registered asset's parameters
219/// (Tier 2: Risk Committee, 3-of-5 Squads).
220pub fn build_update_asset_params_ix(
221    program_id: Pubkey,
222    risk_committee_authority: Pubkey,
223    mint: Pubkey,
224    params: AssetParams,
225) -> Instruction {
226    let accounts = vec![
227        AccountMeta::new_readonly(registry_pda(&program_id), false),
228        AccountMeta::new(risk_committee_authority, true),
229        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
230        AccountMeta::new_readonly(mint, false),
231    ];
232    let mut data = anchor_discriminator("asset_update_params").to_vec();
233    data.extend_from_slice(&params.base_premium_rate_bps.to_le_bytes());
234    data.extend_from_slice(&params.premium_cap_bps.to_le_bytes());
235    data.extend_from_slice(&params.max_capacity.to_le_bytes());
236    data.extend_from_slice(&params.min_premium_lamports.to_le_bytes());
237    data.extend_from_slice(&params.lp_yield_split_bps.to_le_bytes());
238    Instruction { program_id, accounts, data }
239}
240
241/// Build `asset_set_support` — toggles an asset's registration latch
242/// (Tier 2: Risk Committee, 3-of-5 Squads).
243pub fn build_set_asset_support_ix(
244    program_id: Pubkey,
245    risk_committee_authority: Pubkey,
246    mint: Pubkey,
247    supported: bool,
248) -> Instruction {
249    let accounts = vec![
250        AccountMeta::new_readonly(registry_pda(&program_id), false),
251        AccountMeta::new(risk_committee_authority, true),
252        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
253        AccountMeta::new_readonly(mint, false),
254    ];
255    let mut data = anchor_discriminator("asset_set_support").to_vec();
256    data.push(supported as u8);
257    Instruction { program_id, accounts, data }
258}
259
260/// Build `asset_initialize_credit_line` — registers an institution's aggregate
261/// multi-asset credit ceiling (Tier 2: Risk Committee, 3-of-5, post-KYB).
262pub fn build_initialize_credit_line_ix(
263    program_id: Pubkey,
264    institution: Pubkey,
265    risk_committee_authority: Pubkey,
266    total_credit_limit: u64,
267) -> Instruction {
268    let accounts = vec![
269        AccountMeta::new(registry_pda(&program_id), false),
270        AccountMeta::new(institution, true),
271        AccountMeta::new(risk_committee_authority, true),
272        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
273        AccountMeta::new_readonly(solana_program::system_program::ID, false),
274    ];
275    let mut data = anchor_discriminator("asset_initialize_credit_line").to_vec();
276    data.extend_from_slice(&total_credit_limit.to_le_bytes());
277    Instruction { program_id, accounts, data }
278}
279
280/// Build `asset_update_credit_limit` — adjusts the aggregate ceiling
281/// (Tier 2: Risk Committee, 3-of-5 Squads).
282pub fn build_update_credit_limit_ix(
283    program_id: Pubkey,
284    risk_committee_authority: Pubkey,
285    institution: Pubkey,
286    new_limit: u64,
287) -> Instruction {
288    let accounts = vec![
289        AccountMeta::new_readonly(registry_pda(&program_id), false),
290        AccountMeta::new(risk_committee_authority, true),
291        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
292        AccountMeta::new_readonly(institution, false),
293    ];
294    let mut data = anchor_discriminator("asset_update_credit_limit").to_vec();
295    data.extend_from_slice(&new_limit.to_le_bytes());
296    Instruction { program_id, accounts, data }
297}
298
299/// Build `asset_set_credit_frozen` — freezes an institution's credit line
300/// (Tier 1: Emergency Risk Guard "The Breaker", 1-of-3 Squads).
301pub fn build_set_credit_frozen_ix(
302    program_id: Pubkey,
303    breaker_authority: Pubkey,
304    institution: Pubkey,
305    frozen: bool,
306) -> Instruction {
307    let accounts = vec![
308        AccountMeta::new_readonly(registry_pda(&program_id), false),
309        AccountMeta::new(breaker_authority, true),
310        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
311        AccountMeta::new_readonly(institution, false),
312    ];
313    let mut data = anchor_discriminator("asset_set_credit_frozen").to_vec();
314    data.push(frozen as u8);
315    Instruction { program_id, accounts, data }
316}
317
318/// Build `asset_set_paused` — engine-level allocation pause
319/// (Tier 1: Emergency Risk Guard "The Breaker", 1-of-3 Squads).
320pub fn build_set_paused_ix(
321    program_id: Pubkey,
322    breaker_authority: Pubkey,
323    paused: bool,
324) -> Instruction {
325    let accounts = vec![
326        AccountMeta::new(breaker_authority, true),
327        AccountMeta::new(registry_pda(&program_id), false),
328    ];
329    let mut data = anchor_discriminator("asset_set_paused").to_vec();
330    data.push(paused as u8);
331    Instruction { program_id, accounts, data }
332}
333
334/// Build `asset_allocate_capacity` — the Multi-Asset JIT Allocation core.
335///
336/// Account order mirrors the on-chain `AllocateAssetCapacity` context:
337/// 0. pool (mut)
338/// 1. pool_vault (mut)
339/// 2. vault_authority
340/// 3. credit_line (mut)
341/// 4. desk_position (mut, init_if_needed)
342/// 5. trader (signer)
343/// 6. trader_token_account (mut)
344/// 7. fee_vault (mut)
345/// 8. token_program
346/// 9. system_program
347///
348/// `requested_amount` raw lamports (not human decimals). The expected premium
349/// is `principal × base_premium_rate_bps / 10_000`, floored at the pool's
350/// minimum premium. `expiry` is the KYC leaf timestamp (unix seconds); when the
351/// desk has a root set, `merkle_proof` must validate
352/// `keccak256(institution || expiry_be)` up to that root.
353pub fn build_allocate_asset_capacity_ix(
354    program_id: Pubkey,
355    mint: Pubkey,
356    institution: Pubkey,
357    trader: Pubkey,
358    trader_token_account: Pubkey,
359    requested_amount: u64,
360    target_slot: u64,
361    expected_premium: u64,
362    expiry: i64,
363    merkle_proof: Vec<[u8; 32]>,
364) -> Instruction {
365    let accounts = vec![
366        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
367        AccountMeta::new(asset_vault_pda(&program_id, &mint), false),
368        AccountMeta::new_readonly(asset_authority_pda(&program_id, &mint), false),
369        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
370        AccountMeta::new(desk_position_pda(&program_id, &institution, &mint), false),
371        AccountMeta::new(trader, true),
372        AccountMeta::new(trader_token_account, false),
373        AccountMeta::new(asset_fee_vault_pda(&program_id, &mint), false),
374        AccountMeta::new_readonly(spl_token::ID, false),
375        AccountMeta::new_readonly(solana_program::system_program::ID, false),
376    ];
377    let mut data = anchor_discriminator("asset_allocate_capacity").to_vec();
378    data.extend_from_slice(&requested_amount.to_le_bytes());
379    data.extend_from_slice(&target_slot.to_le_bytes());
380    data.extend_from_slice(&expected_premium.to_le_bytes());
381    data.extend_from_slice(&expiry.to_le_bytes());
382    data.extend_from_slice(&(merkle_proof.len() as u32).to_le_bytes());
383    for node in merkle_proof {
384        data.extend_from_slice(&node);
385    }
386    Instruction { program_id, accounts, data }
387}
388
389/// Build `asset_recredit_capacity` — releases unused slot capital.
390pub fn build_recredit_asset_capacity_ix(
391    program_id: Pubkey,
392    mint: Pubkey,
393    institution: Pubkey,
394    trader: Pubkey,
395    trader_token_account: Pubkey,
396    amount: u64,
397) -> Instruction {
398    let accounts = vec![
399        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
400        AccountMeta::new(asset_vault_pda(&program_id, &mint), false),
401        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
402        AccountMeta::new(desk_position_pda(&program_id, &institution, &mint), false),
403        AccountMeta::new(trader, true),
404        AccountMeta::new(trader_token_account, false),
405        AccountMeta::new_readonly(spl_token::ID, false),
406    ];
407    let mut data = anchor_discriminator("asset_recredit_capacity").to_vec();
408    data.extend_from_slice(&amount.to_le_bytes());
409    Instruction { program_id, accounts, data }
410}
411
412/// Build `asset_set_kyc_root` — posts a desk's provider-agnostic Merkle root.
413/// Build `asset_set_kyc_root` — provider-agnostic Merkle KYC root for a desk
414/// (Tier 2: Risk Committee, 3-of-5 Squads).
415pub fn build_set_kyc_root_ix(
416    program_id: Pubkey,
417    risk_committee_authority: Pubkey,
418    institution: Pubkey,
419    kyc_merkle_root: [u8; 32],
420) -> Instruction {
421    let accounts = vec![
422        AccountMeta::new_readonly(registry_pda(&program_id), false),
423        AccountMeta::new(risk_committee_authority, true),
424        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
425        AccountMeta::new_readonly(institution, false),
426    ];
427    let mut data = anchor_discriminator("asset_set_kyc_root").to_vec();
428    data.extend_from_slice(&kyc_merkle_root);
429    Instruction { program_id, accounts, data }
430}
431
432/// Build `asset_settle_daily` — Phase 3 daily clearing house settlement.
433///
434/// The desk treasury returns the exact native asset. `late_fee_payment` is the
435/// deterministic per-block default interest during the 2h grace phase
436/// (`compute_late_fee(desk_position.active_principal, overdue_blocks)`); pass
437/// `0` while the 24h window is still open. After the grace window the program
438/// refuses settlement (status "Breached" → off-chain Master Loan Agreement).
439///
440/// Account order mirrors the on-chain `SettleDaily` context:
441/// 0. pool (mut)
442/// 1. pool_vault (mut)
443/// 2. fee_vault (mut)
444/// 3. credit_line (mut)
445/// 4. desk_position (mut)
446/// 5. treasury (signer)
447/// 6. treasury_token_account (mut)
448/// 7. token_program
449pub fn build_settle_daily_ix(
450    program_id: Pubkey,
451    mint: Pubkey,
452    institution: Pubkey,
453    treasury: Pubkey,
454    treasury_token_account: Pubkey,
455    principal_payment: u64,
456    premium_payment: u64,
457    late_fee_payment: u64,
458) -> Instruction {
459    let accounts = vec![
460        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
461        AccountMeta::new(asset_vault_pda(&program_id, &mint), false),
462        AccountMeta::new(asset_fee_vault_pda(&program_id, &mint), false),
463        AccountMeta::new(credit_line_pda(&program_id, &institution), false),
464        AccountMeta::new(desk_position_pda(&program_id, &institution, &mint), false),
465        AccountMeta::new(treasury, true),
466        AccountMeta::new(treasury_token_account, false),
467        AccountMeta::new_readonly(spl_token::ID, false),
468    ];
469    let mut data = anchor_discriminator("asset_settle_daily").to_vec();
470    data.extend_from_slice(&principal_payment.to_le_bytes());
471    data.extend_from_slice(&premium_payment.to_le_bytes());
472    data.extend_from_slice(&late_fee_payment.to_le_bytes());
473    Instruction { program_id, accounts, data }
474}
475
476/// Build `asset_deposit_liquidity` — LP seeds a pool vault in native asset and
477/// receives freshly minted ERC-4626 share tokens (nUSDC / nSOL / nNVSC).
478#[allow(clippy::too_many_arguments)]
479pub fn build_deposit_asset_liquidity_ix(
480    program_id: Pubkey,
481    mint: Pubkey,
482    provider: Pubkey,
483    provider_token_account: Pubkey,
484    provider_lp_token_account: Pubkey,
485    amount: u64,
486) -> Instruction {
487    let accounts = vec![
488        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
489        AccountMeta::new(asset_vault_pda(&program_id, &mint), false),
490        AccountMeta::new(asset_lp_mint_pda(&program_id, &mint), false),
491        AccountMeta::new(asset_lp_position_pda(&program_id, &mint, &provider), false),
492        AccountMeta::new_readonly(asset_authority_pda(&program_id, &mint), false),
493        AccountMeta::new(provider, true),
494        AccountMeta::new(provider_token_account, false),
495        AccountMeta::new(provider_lp_token_account, false),
496        AccountMeta::new_readonly(spl_token::ID, false),
497        AccountMeta::new_readonly(solana_program::system_program::ID, false),
498    ];
499    let mut data = anchor_discriminator("asset_deposit_liquidity").to_vec();
500    data.extend_from_slice(&amount.to_le_bytes());
501    Instruction { program_id, accounts, data }
502}
503
504/// Build `asset_withdraw_liquidity` — an LP burns share tokens and redeems a
505/// proportional slice of the pool vault, subject to the desk-solvency floor
506/// (`idle − shares_value ≥ active credit utilization`).
507#[allow(clippy::too_many_arguments)]
508pub fn build_withdraw_asset_liquidity_ix(
509    program_id: Pubkey,
510    mint: Pubkey,
511    lp: Pubkey,
512    lp_token_account: Pubkey,
513    destination: Pubkey,
514    shares: u64,
515) -> Instruction {
516    let accounts = vec![
517        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
518        AccountMeta::new(asset_vault_pda(&program_id, &mint), false),
519        AccountMeta::new_readonly(asset_lp_mint_pda(&program_id, &mint), false),
520        AccountMeta::new(asset_lp_position_pda(&program_id, &mint, &lp), false),
521        AccountMeta::new_readonly(asset_authority_pda(&program_id, &mint), false),
522        AccountMeta::new(lp, true),
523        AccountMeta::new(lp_token_account, false),
524        AccountMeta::new(destination, false),
525        AccountMeta::new_readonly(spl_token::ID, false),
526    ];
527    let mut data = anchor_discriminator("asset_withdraw_liquidity").to_vec();
528    data.extend_from_slice(&shares.to_le_bytes());
529    Instruction { program_id, accounts, data }
530}
531
532/// Build `asset_withdraw_fees` — sweeps a per-asset fee vault.
533/// Build `asset_withdraw_fees` — sweeps a per-asset fee vault (Tier 3:
534/// Core Ecosystem Council, 5-of-7 Squads, 72h timelock — treasury allocation).
535pub fn build_withdraw_asset_fees_ix(
536    program_id: Pubkey,
537    upgrade_authority: Pubkey,
538    mint: Pubkey,
539    destination: Pubkey,
540    amount: u64,
541) -> Instruction {
542    let accounts = vec![
543        AccountMeta::new(asset_pool_pda(&program_id, &mint), false),
544        AccountMeta::new_readonly(registry_pda(&program_id), false),
545        AccountMeta::new(upgrade_authority, true),
546        AccountMeta::new(asset_fee_vault_pda(&program_id, &mint), false),
547        AccountMeta::new_readonly(asset_authority_pda(&program_id, &mint), false),
548        AccountMeta::new(destination, false),
549        AccountMeta::new_readonly(spl_token::ID, false),
550    ];
551    let mut data = anchor_discriminator("asset_withdraw_fees").to_vec();
552    data.extend_from_slice(&amount.to_le_bytes());
553    Instruction { program_id, accounts, data }
554}
555
556// ── Default program convenience ────────────────────────────────────────────
557
558pub fn asset_register_default(authority: Pubkey, mint: Pubkey, profile: AssetParams) -> Instruction {
559    build_register_asset_ix(ASSET_ENGINE_PROGRAM_ID, authority, mint, profile)
560}
561
562/// One-shot pointer to the wSOL-mint profile (native-interop).
563pub fn register_wsol_default(authority: Pubkey, wsol_mint: Pubkey) -> Instruction {
564    build_register_asset_ix(ASSET_ENGINE_PROGRAM_ID, authority, wsol_mint, WSOL_PROFILE)
565}
566
567/// Compute the on-chain micro-premium for an allocation.
568pub fn compute_premium(principal: u64, base_premium_rate_bps: u16, min_premium_lamports: u64) -> u64 {
569    let bps_premium =
570        (principal as u128) * (base_premium_rate_bps as u128) / 10_000u128;
571    (bps_premium as u64).max(min_premium_lamports)
572}
573
574/// Per-block default-interest meter for the 2h grace phase (mirrors the
575/// on-chain formula exactly). `overdue_blocks` counts slots past the 24h
576/// maturity; zero once the window is still open.
577pub fn compute_late_fee(principal: u64, overdue_blocks: u64) -> u64 {
578    if overdue_blocks == 0 {
579        return 0;
580    }
581    let accrued = (principal as u128)
582        .checked_mul(LATE_FEE_RATE_BPS as u128)
583        .and_then(|x| x.checked_mul(overdue_blocks as u128))
584        .unwrap_or(0)
585        / (BPS as u128 * LATE_FEE_BASE as u128);
586    accrued as u64
587}
588
589/// Deterministic posture of the desk's 24h floating window at `current_slot`.
590#[derive(Debug, Clone, Copy, PartialEq, Eq)]
591pub enum WindowPosture {
592    NoWindow,
593    Open,
594    Overdue,
595    Breached,
596}
597
598pub fn window_posture(window_start_slot: u64, current_slot: u64) -> WindowPosture {
599    if window_start_slot == 0 {
600        return WindowPosture::NoWindow;
601    }
602    let mature = window_start_slot.saturating_add(WINDOW_SLOTS);
603    if current_slot < mature {
604        return WindowPosture::Open;
605    }
606    if current_slot < mature.saturating_add(GRACE_SLOTS) {
607        WindowPosture::Overdue
608    } else {
609        WindowPosture::Breached
610    }
611}
612
613/// ERC-4626 deposit: shares minted for `deposit` at the current share price.
614/// Mirrors `AssetPool::compute_deposit_shares` on-chain; 1:1 on first deposit.
615pub fn compute_deposit_shares(deposit: u64, total_shares: u64, total_assets: u64) -> u64 {
616    if deposit == 0 {
617        return 0;
618    }
619    if total_shares == 0 || total_assets == 0 {
620        return deposit;
621    }
622    let shares_ratio = (deposit as u128)
623        .checked_mul(total_shares as u128)
624        .unwrap_or(0)
625        / total_assets as u128;
626    shares_ratio as u64
627}
628
629/// ERC-4626 redeem: native assets returned for `shares` at the current price.
630/// Mirrors `AssetPool::compute_lp_withdraw_value` on-chain (caps at assets).
631pub fn compute_lp_withdraw_value(shares: u64, total_shares: u64, total_assets: u64) -> u64 {
632    if shares == 0 || total_shares == 0 {
633        return 0;
634    }
635    let value = (shares as u128)
636        .checked_mul(total_assets as u128)
637        .unwrap_or(0)
638        / total_shares as u128;
639    value.min(total_assets as u128) as u64
640}
641
642/// Scaled per-share price (×1_000_000) — the auto-compounding readout.
643pub fn compute_lp_share_price(total_shares: u64, total_assets: u64) -> u128 {
644    if total_shares == 0 {
645        return 1_000_000;
646    }
647    (total_assets as u128)
648        .checked_mul(1_000_000u128)
649        .unwrap_or(0)
650        / total_shares as u128
651}
652
653// ── Tests ──────────────────────────────────────────────────────────────────
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    #[test]
660    fn premium_matches_onchain_formula() {
661        assert_eq!(compute_premium(1_000_000, 8, 0), 800);
662        assert_eq!(compute_premium(1_000_000, 30, 0), 3_000);
663        assert_eq!(compute_premium(1_000_000, 12, 0), 1_200);
664        assert_eq!(compute_premium(1_000, 12, 500), 500); // min premium floor
665    }
666
667    #[test]
668    fn late_fee_and_window_posture_mirror_onchain_safeguards() {
669        // 0 overdue blocks => no penalty.
670        assert_eq!(compute_late_fee(1_000_000_000, 0), 0);
671        // 50 micro-bps per slot => 5 lamports per slot per 1e9 borrowed bucket.
672        assert_eq!(compute_late_fee(1_000_000_000, 200), 100_000);
673        assert_eq!(compute_late_fee(1_000_000_000, 18_000), 9_000_000);
674
675        let start = 1_000;
676        assert_eq!(window_posture(start, 999), WindowPosture::Open);
677        let mature = start + WINDOW_SLOTS;
678        assert_eq!(window_posture(start, mature - 1), WindowPosture::Open);
679        assert_eq!(window_posture(start, mature), WindowPosture::Overdue);
680        assert_eq!(window_posture(start, mature + GRACE_SLOTS - 1), WindowPosture::Overdue);
681        assert_eq!(window_posture(start, mature + GRACE_SLOTS), WindowPosture::Breached);
682        // No window open yet.
683        assert_eq!(window_posture(0, 5), WindowPosture::NoWindow);
684    }
685
686    #[test]
687    fn standardized_profiles_carry_distinct_limits() {
688        assert_eq!(USDC_PROFILE.decimals, 6);
689        assert_eq!(WSOL_PROFILE.decimals, 9);
690        assert_eq!(NVSC_PROFILE.decimals, 9);
691        assert!(USDC_PROFILE.base_premium_rate_bps < NVSC_PROFILE.base_premium_rate_bps);
692        assert!(NVSC_PROFILE.max_capacity > USDC_PROFILE.max_capacity);
693    }
694
695    #[test]
696    fn allocate_ix_encodes_account_order_and_args() {
697        let mint = Pubkey::new_unique();
698        let institution = Pubkey::new_unique();
699        let trader = Pubkey::new_unique();
700        let ata = Pubkey::new_unique();
701        let proof = vec![[7u8; 32], [9u8; 32]];
702        let ix = build_allocate_asset_capacity_ix(
703            ASSET_ENGINE_PROGRAM_ID, mint, institution, trader, ata, 500_000_000, 123, 600_000, 1_758_000_000,
704            proof.clone(),
705        );
706        assert_eq!(ix.program_id, ASSET_ENGINE_PROGRAM_ID);
707        assert_eq!(ix.accounts.len(), 10);
708        // 0 = pool, 4 = desk_position, 5 = trader (signer), 8 = token program, 9 = system
709        assert_eq!(ix.accounts[0].pubkey, asset_pool_pda(&ASSET_ENGINE_PROGRAM_ID, &mint));
710        assert_eq!(
711            ix.accounts[4].pubkey,
712            desk_position_pda(&ASSET_ENGINE_PROGRAM_ID, &institution, &mint)
713        );
714        assert_eq!(ix.accounts[5].pubkey, trader);
715        assert!(ix.accounts[5].is_signer);
716        assert_eq!(ix.accounts[8].pubkey, spl_token::ID);
717        assert_eq!(ix.accounts[9].pubkey, solana_program::system_program::ID);
718        // requested_amount + target_slot + expected_premium + expiry (LE),
719        // then u32 proof length + two proof nodes.
720        assert_eq!(&ix.data[8..16], &500_000_000u64.to_le_bytes());
721        assert_eq!(&ix.data[16..24], &123u64.to_le_bytes());
722        assert_eq!(&ix.data[24..32], &600_000u64.to_le_bytes());
723        assert_eq!(&ix.data[32..40], &1_758_000_000i64.to_le_bytes());
724        assert_eq!(&ix.data[40..44], &2u32.to_le_bytes());
725        assert_eq!(&ix.data[44..76], &proof[0]);
726        assert_eq!(&ix.data[76..108], &proof[1]);
727    }
728
729    #[test]
730    fn lifecycle_builders_cover_the_daily_clearing_flow() {
731        let mint = Pubkey::new_unique();
732        let institution = Pubkey::new_unique();
733
734        // Desk position PDA is institution × mint scoped.
735        assert_ne!(
736            desk_position_pda(&ASSET_ENGINE_PROGRAM_ID, &institution, &mint),
737            asset_pool_pda(&ASSET_ENGINE_PROGRAM_ID, &mint)
738        );
739
740        // settle_daily lays out pool → vaults → line → position → treasury.
741        let treasury = Pubkey::new_unique();
742        let tta = Pubkey::new_unique();
743        let settle = build_settle_daily_ix(
744            ASSET_ENGINE_PROGRAM_ID, mint, institution, treasury, tta, 1_000_000_000, 50_000,
745            777,
746        );
747        assert_eq!(&settle.data[..8], &anchor_discriminator("asset_settle_daily"));
748        assert_eq!(settle.accounts.len(), 8);
749        assert_eq!(settle.accounts[0].pubkey, asset_pool_pda(&ASSET_ENGINE_PROGRAM_ID, &mint));
750        assert_eq!(settle.accounts[4].pubkey, desk_position_pda(&ASSET_ENGINE_PROGRAM_ID, &institution, &mint));
751        assert_eq!(settle.accounts[5].pubkey, treasury);
752        assert!(settle.accounts[5].is_signer);
753        // principal, premium, then late-fee lamports appended in order.
754        assert_eq!(&settle.data[8..16], &1_000_000_000u64.to_le_bytes());
755        assert_eq!(&settle.data[16..24], &50_000u64.to_le_bytes());
756        assert_eq!(&settle.data[24..32], &777u64.to_le_bytes());
757
758        // set_kyc_root carries the 32-byte root + references the credit line
759        // (Tier 2 committee signs after the registry proof).
760        let root = [42u8; 32];
761        let kyc = build_set_kyc_root_ix(ASSET_ENGINE_PROGRAM_ID, Pubkey::new_unique(), institution, root);
762        assert_eq!(&kyc.data[..8], &anchor_discriminator("asset_set_kyc_root"));
763        assert_eq!(&kyc.data[8..40], &root);
764        assert_eq!(
765            kyc.accounts[2].pubkey,
766            credit_line_pda(&ASSET_ENGINE_PROGRAM_ID, &institution)
767        );
768
769        // Liquidity builders route LP deposits through the share-mint + position.
770        let depositor = Pubkey::new_unique();
771        let deposit_ata = Pubkey::new_unique();
772        let deposit_lp_ata = Pubkey::new_unique();
773        let dep = build_deposit_asset_liquidity_ix(
774            ASSET_ENGINE_PROGRAM_ID, mint, depositor, deposit_ata, deposit_lp_ata, 2_000_000_000,
775        );
776        assert_eq!(dep.accounts[1].pubkey, asset_vault_pda(&ASSET_ENGINE_PROGRAM_ID, &mint));
777        assert_eq!(dep.accounts[2].pubkey, asset_lp_mint_pda(&ASSET_ENGINE_PROGRAM_ID, &mint));
778        assert_eq!(
779            dep.accounts[3].pubkey,
780            asset_lp_position_pda(&ASSET_ENGINE_PROGRAM_ID, &mint, &depositor)
781        );
782        assert_eq!(dep.accounts[5].pubkey, depositor);
783        assert!(dep.accounts[5].is_signer);
784        assert_eq!(dep.accounts.len(), 10);
785        assert_eq!(&dep.data[8..16], &2_000_000_000u64.to_le_bytes());
786
787        // LP redemption burns shares and honors the desk-solvency floor.
788        let title_lp = Pubkey::new_unique();
789        let burn_ata = Pubkey::new_unique();
790        let wd_dest = Pubkey::new_unique();
791        let wd = build_withdraw_asset_liquidity_ix(
792            ASSET_ENGINE_PROGRAM_ID, mint, title_lp, burn_ata, wd_dest, 500,
793        );
794        assert_eq!(wd.accounts[0].pubkey, asset_pool_pda(&ASSET_ENGINE_PROGRAM_ID, &mint));
795        assert_eq!(wd.accounts[3].pubkey, asset_lp_position_pda(&ASSET_ENGINE_PROGRAM_ID, &mint, &title_lp));
796        assert_eq!(wd.accounts[5].pubkey, title_lp);
797        assert!(wd.accounts[5].is_signer);
798        assert_eq!(wd.accounts[7].pubkey, wd_dest);
799        assert_eq!(wd.accounts.len(), 9);
800        assert_eq!(&wd.data[8..16], &500u64.to_le_bytes());
801    }
802
803    #[test]
804    fn register_ix_lays_out_the_five_asset_pdas() {
805        let mint = Pubkey::new_unique();
806        let authority = Pubkey::new_unique();
807        let ix = build_register_asset_ix(ASSET_ENGINE_PROGRAM_ID, authority, mint, USDC_PROFILE);
808        assert_eq!(ix.accounts.len(), 11);
809        let pool = asset_pool_pda(&ASSET_ENGINE_PROGRAM_ID, &mint);
810        let vault = asset_vault_pda(&ASSET_ENGINE_PROGRAM_ID, &mint);
811        let fee_vault = asset_fee_vault_pda(&ASSET_ENGINE_PROGRAM_ID, &mint);
812        assert_eq!(ix.accounts[3].pubkey, pool);
813        assert_eq!(ix.accounts[4].pubkey, vault);
814        assert_eq!(ix.accounts[5].pubkey, fee_vault);
815        assert_eq!(ix.accounts[7].pubkey, asset_lp_mint_pda(&ASSET_ENGINE_PROGRAM_ID, &mint));
816        assert_ne!(pool, vault);
817        assert_ne!(vault, fee_vault);
818        // decimals byte then bps/capacity args, LP yield split appended last.
819        assert_eq!(ix.data[8], USDC_PROFILE.decimals);
820        assert_eq!(&ix.data[29..31], &USDC_PROFILE.lp_yield_split_bps.to_le_bytes());
821    }
822
823    #[test]
824    fn governance_builders_bind_each_tier_to_its_scope() {
825        let breaker = Pubkey::new_unique();
826        let committee = Pubkey::new_unique();
827        let council = Pubkey::new_unique();
828        let wsol = Pubkey::new_unique();
829        let usdc = Pubkey::new_unique();
830        let nvsc = Pubkey::new_unique();
831
832        // initialize: Tier-3 council signs; data carries breaker + committee + upgrade keys.
833        let init = build_initialize_ix(ASSET_ENGINE_PROGRAM_ID, council, breaker, committee, wsol, usdc, nvsc);
834        assert!(init.accounts[0].is_signer);
835        assert_eq!(init.accounts[0].pubkey, council);
836        assert_eq!(&init.data[..8], &anchor_discriminator("initialize"));
837        assert_eq!(&init.data[8..40], breaker.as_ref());
838        assert_eq!(&init.data[40..72], committee.as_ref());
839        assert_eq!(&init.data[72..104], council.as_ref());
840        assert_eq!(&init.data[104..136], wsol.as_ref());
841        assert_eq!(&init.data[136..168], usdc.as_ref());
842        assert_eq!(&init.data[168..200], nvsc.as_ref());
843        assert_eq!(init.data.len(), 200);
844
845        // Breaker scope is strictly emergency: pause + freeze carry no other meta.
846        let brk = Pubkey::new_unique();
847        let pause = build_set_paused_ix(ASSET_ENGINE_PROGRAM_ID, brk, false);
848        assert_eq!(pause.accounts[0].pubkey, brk);
849        assert!(pause.accounts[0].is_signer);
850        let freeze = build_set_credit_frozen_ix(ASSET_ENGINE_PROGRAM_ID, brk, Pubkey::new_unique(), true);
851        assert_eq!(freeze.accounts[1].pubkey, brk);
852        assert!(freeze.accounts[1].is_signer);
853
854        // Committee scope is parameter / limit surfaces.
855        let cmt = Pubkey::new_unique();
856        let limit = build_update_credit_limit_ix(ASSET_ENGINE_PROGRAM_ID, cmt, Pubkey::new_unique(), 1_000);
857        assert_eq!(limit.accounts[1].pubkey, cmt);
858        assert!(limit.accounts[1].is_signer);
859        let params = build_update_asset_params_ix(ASSET_ENGINE_PROGRAM_ID, cmt, Pubkey::new_unique(), USDC_PROFILE);
860        assert_eq!(params.accounts[1].pubkey, cmt);
861        assert!(params.accounts[1].is_signer);
862
863        // Upgrade scope is structural: asset registration + fee treasury.
864        let council = Pubkey::new_unique();
865        let fees = build_withdraw_asset_fees_ix(ASSET_ENGINE_PROGRAM_ID, council, Pubkey::new_unique(), Pubkey::new_unique(), 500);
866        assert_eq!(fees.accounts[2].pubkey, council);
867        assert!(fees.accounts[2].is_signer);
868    }
869
870    #[test]
871    fn pda_derivations_are_stable_and_distinct_per_mint() {
872        let a = Pubkey::new_unique();
873        let b = Pubkey::new_unique();
874        let program = ASSET_ENGINE_PROGRAM_ID;
875        assert_ne!(asset_pool_pda(&program, &a), asset_pool_pda(&program, &b));
876        assert_ne!(asset_vault_pda(&program, &a), asset_vault_pda(&program, &b));
877        assert_ne!(asset_fee_vault_pda(&program, &a), asset_fee_vault_pda(&program, &b));
878        assert_ne!(asset_pool_pda(&program, &a), asset_vault_pda(&program, &a));
879        assert_ne!(asset_vault_pda(&program, &a), asset_fee_vault_pda(&program, &a));
880    }
881
882    #[test]
883    fn credit_line_pda_is_institution_scoped() {
884        let program = ASSET_ENGINE_PROGRAM_ID;
885        let inst_a = Pubkey::new_unique();
886        let inst_b = Pubkey::new_unique();
887        assert_ne!(
888            credit_line_pda(&program, &inst_a),
889            credit_line_pda(&program, &inst_b)
890        );
891    }
892
893    #[test]
894    fn every_builder_uses_the_anchor_discriminator_prefix() {
895        // spot-check three builders land a 32-byte body past the prefix
896        let ix = build_set_paused_ix(ASSET_ENGINE_PROGRAM_ID, Pubkey::new_unique(), true);
897        assert_eq!(&ix.data[..8], &anchor_discriminator("asset_set_paused"));
898        assert_eq!(ix.data.len(), 9);
899        assert_eq!(
900            noviscia_types::WSOL_MINT.to_string().starts_with("So111"),
901            true
902        );
903    }
904
905    #[test]
906    fn lp_share_math_mirrors_the_4626_onchain_ledger() {
907        // First deposit is 1:1.
908        assert_eq!(compute_deposit_shares(1_000, 0, 0), 1_000);
909        // After compounding 1_000 → 1_200 at constant shares, price is 1.2.
910        assert_eq!(compute_lp_share_price(1_000, 1_200), 1_200_000);
911        assert_eq!(compute_lp_withdraw_value(1_000, 1_000, 1_200), 1_200);
912        // Bob deposits 600 at 1.2/share → 500 shares.
913        assert_eq!(compute_deposit_shares(600, 1_000, 1_200), 500);
914        assert_eq!(compute_lp_withdraw_value(500, 1_500, 1_800), 600);
915        // Redeems cap at total assets.
916        assert_eq!(compute_lp_withdraw_value(1_000, 1_000, 0), 0);
917        assert_eq!(compute_lp_withdraw_value(1_000, 1_000, 500), 500);
918    }
919}