Skip to main content

noviscia_types/
lib.rs

1//! # Noviscia Types
2//!
3//! Shared types, PDA seed constants, and program IDs used across all Noviscia
4//! SDK crates. Mirrors the on-chain account layouts from the active programs.
5
6use anchor_lang::prelude::*;
7
8// ── PDA Seed Constants ──────────────────────────────────────────────────────
9
10/// Pool config PDA seed (`noviscia-permissioned-pool`).
11pub const POOL_SEED: &[u8] = b"pool";
12/// Pool vault PDA seed (token custody).
13pub const POOL_VAULT_SEED: &[u8] = b"pool-vault";
14/// LP entry PDA seed.
15pub const LP_ENTRY_SEED: &[u8] = b"lp-entry";
16/// LP mint PDA seed.
17pub const LP_MINT_SEED: &[u8] = b"lp-mint";
18/// Insurance reserve PDA seed.
19pub const INSURANCE_SEED: &[u8] = b"insurance";
20
21/// Credit line ledger PDA seed (`noviscia-credit-line`).
22pub const CREDIT_LINE_SEED: &[u8] = b"credit-line";
23/// Alpha-sleeve USDC vault PDA seed.
24pub const CREDIT_VAULT_SEED: &[u8] = b"credit-vault";
25/// Toll staging vault PDA seed (90% before omni-pool sweep).
26pub const TOLL_VAULT_SEED: &[u8] = b"toll-vault";
27/// Per-borrower registry PDA seed.
28pub const BORROWER_SEED: &[u8] = b"borrower";
29
30/// Position PDA seed (`position-tracker`).
31pub const POSITION_SEED: &[u8] = b"position";
32/// Collateral vault PDA seed.
33pub const COLLATERAL_VAULT_SEED: &[u8] = b"collateral-vault";
34/// Pt-config PDA seed.
35pub const PT_CONFIG_SEED: &[u8] = b"pt-config";
36
37// ── Program IDs (Devnet) ───────────────────────────────────────────────────
38
39/// Position tracker program (devnet).
40pub const POSITION_TRACKER_PROGRAM_ID: Pubkey =
41    solana_program::pubkey!("6uvr2JcP2iMQooG76RjpCtJLoJ4NuptGyRCiMKuDR1ws");
42/// Escrow program (devnet).
43pub const ESCROW_PROGRAM_ID: Pubkey =
44    solana_program::pubkey!("2WPb3wsyp4G6zFPx8sTYf3bTDyySxwpo1Ja8H6RCHXCZ");
45/// Credit line program (devnet) — now aliases the consolidated `netting-engine`
46/// host (19→4 consolidation: the standalone `noviscia-credit-line` was absorbed
47/// at Stage 3; see `docs/FROZEN.md` + `docs/CONSOLIDATION.md` §7). PDAs derive
48/// under the host ID.
49pub const CREDIT_LINE_PROGRAM_ID: Pubkey =
50    solana_program::pubkey!("68s4vuWUXAaEFF1EM1RUQpw7SFdYZSV3opvtDqoBCs56");
51/// nv-usdc-vault omni-pool program (devnet).
52pub const NV_USDC_VAULT_PROGRAM_ID: Pubkey =
53    solana_program::pubkey!("CN92hAtnZxbMxPdho8tugi9GDK86UpGwmnbEvk5yzAWC");
54/// Burn engine program (devnet).
55pub const BURN_ENGINE_PROGRAM_ID: Pubkey =
56    solana_program::pubkey!("nFgJEQSrKEi7FdAKC6vz5HsQ6f9QjQLBuQcQqQy45id");
57/// Staking manager program (devnet).
58pub const STAKING_MANAGER_PROGRAM_ID: Pubkey =
59    solana_program::pubkey!("HjxcKV51A7jxE2iqMCDY7EvWFL9XsheuM43DamWGabqb");
60/// Netting engine program (devnet).
61pub const NETTING_ENGINE_PROGRAM_ID: Pubkey =
62    solana_program::pubkey!("68s4vuWUXAaEFF1EM1RUQpw7SFdYZSV3opvtDqoBCs56");
63/// Liquidation vault program (devnet).
64pub const LIQUIDATION_VAULT_PROGRAM_ID: Pubkey =
65    solana_program::pubkey!("Cwma3FfMKhoLkgfrGYgErVPoFWEtHpx7DNc4wArpRHBz");
66/// JIT risk marketplace program (devnet) — now aliases the consolidated
67/// `noviscia-capacity` host (19→4 consolidation: the standalone `jit-risk` was
68/// absorbed at Stage 2; see `docs/FROZEN.md` + `docs/CONSOLIDATION.md` §7).
69/// PDAs derive under the host ID.
70pub const JIT_RISK_PROGRAM_ID: Pubkey =
71    solana_program::pubkey!("JDsM18uSZ1UJEP49XdKSjumdftpuZ8cJbpb8CkBaBiMc");
72/// Gateway auction program (devnet).
73pub const GATEWAY_AUCTION_PROGRAM_ID: Pubkey =
74    solana_program::pubkey!("HQ26VTfoBVmGFY1JsFp5HmMT3rjLNoLJH6zurm8TL9xR");
75/// Sovereign netting program (devnet) — now aliases the consolidated
76/// `netting-engine` host (19→4 consolidation: the standalone `sovereign-netting`
77/// was absorbed at Stage 3; see `docs/FROZEN.md` + `docs/CONSOLIDATION.md` §7).
78/// PDAs derive under the host ID.
79pub const SOVEREIGN_NETTING_PROGRAM_ID: Pubkey =
80    solana_program::pubkey!("68s4vuWUXAaEFF1EM1RUQpw7SFdYZSV3opvtDqoBCs56");
81
82/// USDC devnet mint.
83pub const USDC_MINT: Pubkey =
84    solana_program::pubkey!("Cx2bfKM7hcpnreSZxiDaN8q4Ca9i5ViCLxqRTs12JhS5");
85/// NVSC devnet governance token mint.
86pub const NVSC_MINT: Pubkey =
87    solana_program::pubkey!("4BXiDT5o9J6aQdJNd36QE1L2YvQqedEKSP1wuQdSgJkg");
88/// nvscUSDC devnet yield-bearing share token mint.
89pub const NVSCUSDC_MINT: Pubkey =
90    solana_program::pubkey!("2TmaUey4Hh2om1kFR77Vw1RDh8H69qcW6UAACVidJeVk");
91
92// ── Numeric Constants ──────────────────────────────────────────────────────
93
94/// BPS denominator (10_000 = 100%).
95pub const BPS: u64 = 10_000;
96/// BPS denominator as u128 for intermediate math.
97pub const BPS_U128: u128 = 10_000;
98/// WAD (1e12) — per-slot premium rate for jit-risk.
99pub const WAD: u128 = 1_000_000_000_000;
100/// Share of each credit-line toll routed to the omni-pool (LP NAV). 9000 = 90%.
101pub const LP_NAV_SPLIT_BPS: u64 = 9_000;
102/// Share of each credit-line toll routed to the system treasury. 1000 = 10%.
103pub const TREASURY_SPLIT_BPS: u64 = 1_000;
104
105// ── Enums ──────────────────────────────────────────────────────────────────
106
107/// KYC tier for an LP in the permissioned pool.
108#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
109#[repr(u8)]
110pub enum LpTier {
111    /// Standard retail (limited allocation, 5% of pool).
112    #[default]
113    Retail = 0,
114    /// Accredited investor (higher allocation, 20% of pool).
115    Accredited = 1,
116    /// Full institutional (unlimited allocation, 100% of pool).
117    Institutional = 2,
118}
119
120impl LpTier {
121    /// Maximum deposit allocation in bps of total pool shares.
122    pub fn max_deposit_bps(self) -> u64 {
123        match self {
124            LpTier::Retail => 500,
125            LpTier::Accredited => 2_000,
126            LpTier::Institutional => 10_000,
127        }
128    }
129}
130
131/// Position side — long or short.
132#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
133#[repr(u8)]
134pub enum Side {
135    #[default]
136    Long = 0,
137    Short = 1,
138}
139
140// ── On-Chain Account Layouts ───────────────────────────────────────────────
141
142/// The credit line ledger. One per program — the shared alpha sleeve.
143///
144/// Mirrors `noviscia-credit-line` `CreditLine` account layout.
145#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
146pub struct CreditLine {
147    pub authority: Pubkey,
148    pub toll_recipient: Pubkey,
149    pub usdc_mint: Pubkey,
150    /// Dynamic toll floor (bps). Applied at zero utilization.
151    pub base_toll_bps: u64,
152    /// Dynamic toll ceiling (bps). Applied at 100% utilization.
153    pub max_toll_bps: u64,
154    /// Upper bound on a single borrower's outstanding draw (USDC base-6).
155    pub borrower_cap: u64,
156    /// Upper bound on the whole line's total outstanding (USDC base-6).
157    pub global_outstanding_cap: u64,
158    /// Protocol-wide amount currently drawn but not yet settled.
159    pub total_outstanding: u64,
160    pub bump: u8,
161    pub credit_vault_bump: u8,
162    pub toll_vault_bump: u8,
163}
164
165impl CreditLine {
166    pub const SPACE: usize = 8 + 32 + 32 + 32 + 8 + 8 + 8 + 8 + 8 + 1 + 1 + 1;
167}
168
169/// A whitelisted borrower's registry entry.
170///
171/// Mirrors `noviscia-credit-line` `Borrower` account layout.
172#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
173pub struct Borrower {
174    pub owner: Pubkey,
175    /// Whether the desk is permitted to draw credit.
176    pub authorized: bool,
177    /// Per-borrower hard ceiling (USDC base-6).
178    pub credit_limit: u64,
179    /// Amount currently drawn but not yet settled (USDC base-6).
180    pub outstanding: u64,
181    pub bump: u8,
182}
183
184impl Borrower {
185    pub const SPACE: usize = 8 + 32 + 1 + 8 + 8 + 1;
186}
187
188/// Permissioned pool configuration.
189///
190/// Mirrors `noviscia-permissioned-pool` `PoolConfig` account layout.
191#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
192pub struct PoolConfig {
193    pub authority: Pubkey,
194    /// Human-readable pool label (e.g. "SOL-USDC Institutional").
195    pub label: [u8; 32],
196    pub base_mint: Pubkey,
197    pub quote_mint: Pubkey,
198    /// When true, only KYC-verified LPs can deposit/withdraw.
199    pub kyc_required: bool,
200    /// keccak256 merkle root of the LP whitelist.
201    pub kyc_merkle_root: [u8; 32],
202    /// Trading fee in bps (0-100).
203    pub fee_bps: u64,
204    /// Portion of fees routed to insurance reserve (bps of fee).
205    pub insurance_cut_bps: u64,
206    /// Total LP shares outstanding.
207    pub total_shares: u64,
208    /// Total base token reserves.
209    pub base_reserve: u64,
210    /// Total quote token reserves.
211    pub quote_reserve: u64,
212    /// Number of active LPs.
213    pub lp_count: u64,
214    /// When true, deposits are paused.
215    pub is_paused: bool,
216    pub bump: u8,
217    pub vault_bump: u8,
218    pub lp_mint_bump: u8,
219    pub insurance_bump: u8,
220}
221
222impl PoolConfig {
223    pub const SPACE: usize = 8
224        + 32   // authority
225        + 32   // label
226        + 32   // base_mint
227        + 32   // quote_mint
228        + 1    // kyc_required
229        + 32   // kyc_merkle_root
230        + 8    // fee_bps
231        + 8    // insurance_cut_bps
232        + 8    // total_shares
233        + 8    // base_reserve
234        + 8    // quote_reserve
235        + 8    // lp_count
236        + 1    // is_paused
237        + 1    // bump
238        + 1    // vault_bump
239        + 1    // lp_mint_bump
240        + 1;   // insurance_bump
241}
242
243/// Per-LP entry in a permissioned pool.
244///
245/// Mirrors `noviscia-permissioned-pool` `LpEntry` account layout.
246#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
247pub struct LpEntry {
248    pub wallet: Pubkey,
249    /// keccak256(wallet || tier || expiry) — verified against pool's merkle root.
250    pub kyc_hash: [u8; 32],
251    /// When this KYC verification was completed (unix timestamp).
252    pub verified_at: i64,
253    /// When this KYC verification expires (unix timestamp). 0 = never.
254    pub expires_at: i64,
255    /// KYC tier determining allocation limits.
256    pub tier: LpTier,
257    /// Number of LP shares this wallet holds.
258    pub shares: u64,
259    /// Whether this LP is currently active.
260    pub is_active: bool,
261    pub bump: u8,
262}
263
264impl LpEntry {
265    pub const SPACE: usize = 8
266        + 32   // wallet
267        + 32   // kyc_hash
268        + 8    // verified_at
269        + 8    // expires_at
270        + 1    // tier
271        + 8    // shares
272        + 1    // is_active
273        + 1;   // bump
274}
275
276/// Dynamic toll result mirroring the TypeScript `TollResult` and on-chain
277/// `toll_and_utilization` output.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub struct TollResult {
280    /// The computed toll amount (USDC base-6).
281    pub toll_amount: u64,
282    /// Effective toll rate in bps.
283    pub rate_bps: u64,
284    /// Current utilization in bps (0..=10_000).
285    pub utilization_bps: u64,
286    /// 90% share routed to the omni-pool (LP NAV).
287    pub lp_share: u64,
288    /// 10% share routed to the system treasury.
289    pub treasury_share: u64,
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    #[test]
297    fn lp_tier_max_deposit_bps() {
298        assert_eq!(LpTier::Retail.max_deposit_bps(), 500);
299        assert_eq!(LpTier::Accredited.max_deposit_bps(), 2_000);
300        assert_eq!(LpTier::Institutional.max_deposit_bps(), 10_000);
301    }
302
303    #[test]
304    fn credit_line_space_matches_constant() {
305        assert_eq!(
306            CreditLine::SPACE,
307            8 + 32 + 32 + 32 + 8 + 8 + 8 + 8 + 8 + 1 + 1 + 1
308        );
309    }
310
311    #[test]
312    fn borrower_space_matches_constant() {
313        assert_eq!(Borrower::SPACE, 8 + 32 + 1 + 8 + 8 + 1);
314    }
315
316        #[test]
317    fn pool_config_space_matches_constant() {
318        assert_eq!(
319            PoolConfig::SPACE,
320            8 + 32 + 32 + 32 + 32 + 1 + 32 + 8 + 8 + 8 + 8 + 8 + 8 + 1 + 1 + 1 + 1 + 1
321        );
322    }
323
324    #[test]
325    fn lp_entry_space_matches_constant() {
326        assert_eq!(LpEntry::SPACE, 8 + 32 + 32 + 8 + 8 + 1 + 8 + 1 + 1);
327    }
328
329    #[test]
330    fn actual_serialized_sizes_sans_discriminator() {
331        assert_eq!(PoolConfig::default().try_to_vec().unwrap().len(), 214);
332        assert_eq!(LpEntry::default().try_to_vec().unwrap().len(), 91);
333        assert_eq!(CreditLine::default().try_to_vec().unwrap().len(), 139);
334        assert_eq!(Borrower::default().try_to_vec().unwrap().len(), 50);
335    }
336}
337
338// ── Capacity Engine (noviscia-capacity) ────────────────────────────────────
339
340/// Capacity engine config PDA seed.
341pub const CAPACITY_SEED: &[u8] = b"capacity";
342/// Congestion oracle PDA seed.
343pub const CONGESTION_SEED: &[u8] = b"congestion";
344/// Client account PDA seed.
345pub const CLIENT_SEED: &[u8] = b"client";
346/// Per-slot ledger PDA seed.
347pub const SLOT_LEDGER_SEED: &[u8] = b"slot-ledger";
348/// Treasury token account PDA seed.
349pub const TREASURY_SEED: &[u8] = b"treasury";
350/// Treasury authority PDA seed (owner of the token account).
351pub const TREASURY_AUTH_SEED: &[u8] = b"treasury-auth";
352
353/// On-chain program ID for `noviscia-capacity` (devnet).
354pub const CAPACITY_PROGRAM_ID: Pubkey =
355    anchor_lang::solana_program::pubkey!("JDsM18uSZ1UJEP49XdKSjumdftpuZ8cJbpb8CkBaBiMc");
356
357/// Institutional client tier.
358#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
359#[repr(u8)]
360pub enum ClientTier {
361    #[default]
362    TierOne = 0,
363    TierTwo = 1,
364}
365
366/// Global capacity engine configuration.
367#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
368pub struct CapacityConfig {
369    pub authority: Pubkey,
370    pub guard_authority: Pubkey,
371    pub usdc_mint: Pubkey,
372    pub kyc_merkle_root: [u8; 32],
373    pub base_premium_bps: u64,
374    pub premium_cap_bps: u64,
375    pub congestion_multiplier_bps: u64,
376    pub min_premium_lamports: u64,
377    pub paused: bool,
378    pub bump: u8,
379}
380
381impl CapacityConfig {
382    pub const SPACE: usize = 8 + 32 + 32 + 32 + 32 + 8 + 8 + 8 + 8 + 1 + 1;
383}
384
385/// Network congestion oracle feeding the dynamic premium model.
386#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
387pub struct CongestionOracle {
388    pub load_ratio_bps: u64,
389    pub cu_consumed: u64,
390    pub cu_capacity: u64,
391    pub updated_slot: u64,
392    pub bump: u8,
393}
394
395impl CongestionOracle {
396    pub const SPACE: usize = 8 + 8 + 8 + 8 + 8 + 1;
397}
398
399/// Registered institutional client.
400#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
401pub struct ClientAccount {
402    pub operator: Pubkey,
403    pub authority: Pubkey,
404    pub tier: ClientTier,
405    pub premium_multiplier_bps: u64,
406    pub credit_limit: u64,
407    pub active_utilization: u64,
408    pub available_balance: u64,
409    pub margin_posted: u64,
410    pub frozen: bool,
411    pub bump: u8,
412}
413
414impl ClientAccount {
415    pub const SPACE: usize = 8 + 32 + 32 + 1 + 8 + 8 + 8 + 8 + 8 + 1 + 1;
416
417    pub fn capacity_budget(&self) -> u64 {
418        self.credit_limit
419            .saturating_add(self.margin_posted)
420            .saturating_sub(self.active_utilization)
421    }
422}
423
424/// Per-slot capacity ledger.
425#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
426pub struct SlotLedger {
427    pub client: Pubkey,
428    pub slot: u64,
429    pub capacity_granted: u64,
430    pub utilized: u64,
431    pub premium_paid: u64,
432    pub settled: bool,
433    pub bump: u8,
434}
435
436impl SlotLedger {
437    pub const SPACE: usize = 8 + 32 + 8 + 8 + 8 + 8 + 1 + 1;
438}
439
440// ── Asset Engine (noviscia-asset-engine) ───────────────────────────────────
441
442/// Global engine registry PDA seed.
443pub const ASSET_REGISTRY_SEED: &[u8] = b"asset-registry";
444/// Per-asset pool PDA seed.
445pub const ASSET_POOL_SEED: &[u8] = b"asset-pool";
446/// Per-asset principal vault token-account PDA seed.
447pub const ASSET_VAULT_SEED: &[u8] = b"asset-vault";
448/// Per-asset premium fee vault token-account PDA seed.
449pub const ASSET_FEE_VAULT_SEED: &[u8] = b"asset-fees";
450/// PDA authorizing per-asset vault transfers.
451pub const ASSET_AUTHORITY_SEED: &[u8] = b"asset-authority";
452/// Institutional credit line PDA seed.
453pub const ASSET_CREDIT_LINE_SEED: &[u8] = b"credit-line";
454/// Per-desk per-mint borrow mirror PDA seed.
455pub const DESK_POSITION_SEED: &[u8] = b"desk-position";
456/// Per-pool ERC-4626 share-mint (nUSDC / nSOL / nNVSC) PDA seed.
457pub const ASSET_LP_MINT_SEED: &[u8] = b"asset-lp-mint";
458/// Per-(pool, LP) share-position ledger seed.
459pub const ASSET_LP_POSITION_SEED: &[u8] = b"asset-lp-position";
460/// Floating KYC/allocation window length (~24h @ 400ms blocks).
461pub const WINDOW_SLOTS: u64 = 216_000;
462/// Hard-escalation grace window (~2h @ 400ms blocks) before a desk "Breaches".
463pub const GRACE_SLOTS: u64 = 18_000;
464/// Micro-bps per overdue slot for the per-block late-fee taxi meter.
465pub const LATE_FEE_RATE_BPS: u64 = 50;
466pub const LATE_FEE_BASE: u64 = 10_000;
467
468/// On-chain program ID for `noviscia-asset-engine` (devnet) — now aliases the
469/// consolidated `noviscia-capacity` host (19→4 consolidation: the standalone
470/// `noviscia-asset-engine` was absorbed at Stage 2; see `docs/FROZEN.md` +
471/// `docs/CONSOLIDATION.md` §7). PDAs derive under the host ID.
472pub const ASSET_ENGINE_PROGRAM_ID: Pubkey =
473    anchor_lang::solana_program::pubkey!("JDsM18uSZ1UJEP49XdKSjumdftpuZ8cJbpb8CkBaBiMc");
474
475/// Wrap-SOL mint (native-interop profile for SOL exposure).
476pub const WSOL_MINT: Pubkey =
477    anchor_lang::solana_program::pubkey!("So11111111111111111111111111111111111111112");
478
479/// Global asset engine configuration — stores the three-tier Layered
480/// Governance multi-sig keys (Squads PDAs) that gate every authority path.
481#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
482pub struct AssetEngineRegistry {
483    /// Tier 1 — Emergency Risk Guard ("The Breaker"), 1-of-3 Squads:
484    /// freeze credit lines / pause the allocation loop, and nothing else.
485    pub breaker_authority: Pubkey,
486    /// Tier 2 — Risk Committee ("Parameter Vault"), 3-of-5 Squads:
487    /// credit limits, KYC roots, asset parameters, support tiers.
488    pub risk_committee_authority: Pubkey,
489    /// Tier 3 — Core Ecosystem Council, 5-of-7 Squads (72h timelock):
490    /// register assets, treasury withdrawals, program upgrades.
491    pub upgrade_authority: Pubkey,
492    pub wsol_mint: Pubkey,
493    pub usdc_mint: Pubkey,
494    pub nvsc_mint: Pubkey,
495    pub supported_count: u8,
496    pub paused: bool,
497    pub bump: u8,
498}
499
500impl AssetEngineRegistry {
501    pub const SPACE: usize = 8 + 32 * 3 + 32 * 3 + 3;
502}
503
504/// Per-mint pool profile: liquidity, premium params, and capacity ceiling.
505#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
506pub struct AssetPool {
507    pub mint: Pubkey,
508    pub pool_bump: u8,
509    pub vault: Pubkey,
510    pub fee_vault: Pubkey,
511    pub vault_authority: Pubkey,
512    pub decimals: u8,
513    pub supported: bool,
514    pub total_idle_capital: u64,
515    pub active_credit_utilization: u64,
516    pub base_premium_rate_bps: u16,
517    pub premium_cap_bps: u16,
518    pub min_premium_lamports: u64,
519    pub max_capacity: u64,
520    /// ERC-4626 share-mint for this pool (nUSDC / nSOL / nNVSC).
521    pub lp_mint: Pubkey,
522    pub total_lp_shares: u64,
523    pub lp_yield_split_bps: u16,
524}
525
526impl AssetPool {
527    pub const SPACE: usize =
528        8 + 32 + 1 + 32 + 32 + 32 + 1 + 1 + 8 + 8 + 2 + 2 + 8 + 8 + 32 + 8 + 2;
529}
530
531/// Aggregate institutional multi-asset credit ceiling + 24h floating window.
532#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
533pub struct InstitutionalCreditLine {
534    pub institution: Pubkey,
535    pub authority: Pubkey,
536    pub total_credit_limit: u64,
537    pub active_utilization: u64,
538    /// Provider-agnostic Merkle KYC root for this desk (keccak leaves).
539    pub kyc_merkle_root: [u8; 32],
540    /// Slot that opened the current 24h floating window (0 = none open).
541    pub window_start_slot: u64,
542    /// Highest active_utilization reached during the current window.
543    pub peak_active_utilization: u64,
544    /// Running micro-premium taxi meter (accrued, settled at window close).
545    pub accumulated_premiums: u64,
546    /// Unix timestamp of the last daily settlement (ledger reset).
547    pub last_settlement_timestamp: i64,
548    pub frozen: bool,
549    pub bump: u8,
550}
551
552impl InstitutionalCreditLine {
553    pub const SPACE: usize = 8 + 32 + 32 + 8 + 8 + 32 + 8 + 8 + 8 + 8 + 1 + 1;
554}
555
556/// Per-desk borrow mirror for one mint — principal out + settled premiums.
557#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
558pub struct DeskPosition {
559    pub institution: Pubkey,
560    pub mint: Pubkey,
561    /// Principal currently checked out of this mint's pool vault.
562    pub active_principal: u64,
563    /// Premium accrued this window in this mint (native-asset settlement).
564    pub accumulated_premiums: u64,
565    /// Daily invoices settled to date.
566    pub settled_invoices: u64,
567    pub bump: u8,
568}
569
570impl DeskPosition {
571    pub const SPACE: usize = 8 + 32 + 32 + 8 + 8 + 8 + 1;
572}
573
574// ── Tranche Vault (noviscia-tranche-vault) ─────────────────────────────────
575
576/// Dual-tranche vault config PDA seed.
577pub const TRANCHES_SEED: &[u8] = b"tranches";
578/// Protected tranche ledger/vault seeds.
579pub const PROTECTED_VAULT_SEED: &[u8] = b"protected-vault";
580/// Institutional tranche ledger/vault seeds.
581pub const INSTI_VAULT_SEED: &[u8] = b"insti-vault";
582/// Tranche position PDA seed.
583pub const TRANCHE_POSITION_SEED: &[u8] = b"position";
584
585/// On-chain program ID for `noviscia-tranche-vault` (devnet).
586pub const TRANCHE_VAULT_PROGRAM_ID: Pubkey =
587    anchor_lang::solana_program::pubkey!("9Sk1zLo7uprmtrskoZQS6zf1KFSNv4uTCxMsbqGVMCMb");
588
589/// Tranche discriminator.
590#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
591#[repr(u8)]
592pub enum Tranche {
593    #[default]
594    Protected = 0,
595    Institutional = 1,
596}
597
598/// Per-tranche NAV ledger.
599#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
600pub struct TrancheVault {
601    pub tranche: Tranche,
602    pub nav_usdc: u64,
603    pub total_shares: u64,
604    pub last_accrual_ts: i64,
605    pub bump: u8,
606}
607
608impl TrancheVault {
609    pub const SPACE: usize = 8 + 1 + 8 + 8 + 8 + 1;
610}
611
612/// LP position inside a tranche.
613#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
614pub struct TranchePosition {
615    pub owner: Pubkey,
616    pub tranche: Tranche,
617    pub shares: u64,
618    pub bump: u8,
619}
620
621impl TranchePosition {
622    pub const SPACE: usize = 8 + 32 + 1 + 8 + 1;
623}
624
625#[cfg(test)]
626mod capacity_tests {
627    use super::*;
628
629    #[test]
630    fn capacity_client_space_matches_constant() {
631        assert_eq!(ClientAccount::SPACE, 8 + 32 + 32 + 1 + 8 + 8 + 8 + 8 + 8 + 1 + 1);
632    }
633
634    #[test]
635    fn capacity_budget_accounts_margin() {
636        let c = ClientAccount {
637            credit_limit: 500_000_000,
638            margin_posted: 100_000_000,
639            active_utilization: 200_000_000,
640            ..ClientAccount::default()
641        };
642        assert_eq!(c.capacity_budget(), 400_000_000);
643    }
644}