may_cpi/
lib.rs

1use anchor_lang::prelude::*;
2
3#[cfg(feature = "local")]
4declare_id!("43bYyFn8WBwxXvXh28yQ22SQz1TMY1w5DYnRAzRqpJ1J");
5
6#[cfg(feature = "devnet")]
7declare_id!("MD2pPJCjpUT5ttJFUVeP2Xka1ZSvCJMZUoX4XTdPdet");
8
9#[cfg(feature = "mainnet")]
10declare_id!("AVMmmRzwc2kETQNhPiFVnyu62HrgsQXTD6D7SnSfEz7v");
11
12#[program]
13pub mod mayflower {
14    use super::*;
15
16    pub fn version(_ctx: Context<VersionAccounts>) -> Result<()> {
17        panic!("not implemented")
18    }
19
20    pub fn init_log_account(_ctx: Context<InitLogAccountAccounts>) -> Result<()> {
21        panic!("not implemented")
22    }
23
24    pub fn receive_log(_ctx: Context<ReceiveLogAccounts>, _log: [u8; 504]) -> Result<()> {
25        panic!("not implemented")
26    }
27
28    pub fn test_log(_ctx: Context<TestLogAccounts>) -> Result<()> {
29        panic!("not implemented")
30    }
31
32    /// Initialize a platform tenant.
33    ///
34    /// Tenants are the top-level organizational units in the protocol. Each tenant can have
35    /// multiple market groups, and receives a portion of all fees generated by markets under
36    /// their umbrella.
37    ///
38    /// # Arguments
39    ///
40    /// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
41    /// This fee is taken from all market operations and distributed to the tenant.
42    /// * `permissionless_group_creation` - If true, anyone can create market groups under this
43    /// tenant. If false, only the tenant admin can create new groups.
44    ///
45    /// # Access Control
46    ///
47    /// This instruction can only be called by the program itself (root authority).
48    pub fn tenant_init(
49        _ctx: Context<TenantInitAccounts>,
50        _fee_micro_bps: u32,
51        _permissionless_group_creation: bool,
52    ) -> Result<()> {
53        panic!("not implemented")
54    }
55
56    /// Initialize a platform tenant with an admin.
57    ///
58    /// This instruction is similar to `tenant_init` but allows specifying an admin
59    /// account that will have full control over the tenant.
60    ///
61    /// # Arguments
62    ///
63    /// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
64    /// This fee is taken from all market operations and distributed to the tenant.
65    /// * `permissionless_group_creation` - If true, anyone can create market groups under this
66    /// tenant. If false, only the tenant admin can create new groups.
67    /// * `admin` - Public key of the admin account that will have full control over the tenant.
68    pub fn tenant_init_with_admin(
69        _ctx: Context<TenantInitWithAdminAccounts>,
70        _fee_micro_bps: u32,
71        _permissionless_group_creation: bool,
72        _admin: Pubkey,
73    ) -> Result<()> {
74        panic!("not implemented")
75    }
76
77    /// Propose a new admin for the tenant.
78    ///
79    /// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
80    /// who must then accept the role using `tenant_accept_new_admin`.
81    pub fn tenant_propose_admin(
82        _ctx: Context<TenantProposeAdminAccounts>,
83        _new_admin: Pubkey,
84    ) -> Result<TenantProposeAdminEvent> {
85        panic!("not implemented")
86    }
87
88    /// Accept admin ownership of a tenant.
89    ///
90    /// Completes the two-step ownership transfer process. The proposed admin calls this
91    /// instruction to accept control of the tenant.
92    pub fn tenant_accept_new_admin(
93        _ctx: Context<TenantAcceptNewAdminAccounts>,
94    ) -> Result<TenantAcceptNewAdminEvent> {
95        panic!("not implemented")
96    }
97
98    /// Change the fee rate for a tenant.
99    ///
100    /// Updates the platform fee rate applied to all market operations under this tenant.
101    pub fn tenant_change_fee_mbps(
102        _ctx: Context<TenantChangeFeeMbpsAccounts>,
103        _fee_micro_bps: u32,
104    ) -> Result<TenantChangeFeeMbpsEvent> {
105        panic!("not implemented")
106    }
107
108    /// Initialize a market group under a tenant.
109    ///
110    /// Market groups are collections of markets that share the same fee structure and admin.
111    /// Each group can contain multiple markets with different token pairs and price curves.
112    /// The group admin has control over all markets within the group and collects trading fees.
113    ///
114    /// # Arguments
115    ///
116    /// * `args` - Initialization arguments containing:
117    /// - `fees`: Fee structure for buy, sell, borrow, and exercise operations
118    /// - `group_admin`: Public key that will administer this market group
119    ///
120    /// # Access Control
121    ///
122    /// If the tenant has `permissionless_group_creation` disabled, only the tenant admin
123    /// can create new market groups.
124    pub fn market_group_init(
125        _ctx: Context<MarketGroupInitAccounts>,
126        _args: MarketGroupInitArgs,
127    ) -> Result<()> {
128        panic!("not implemented")
129    }
130
131    /// Propose a new admin for the market group.
132    ///
133    /// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
134    /// who must then accept the role using `market_group_accept_new_admin`.
135    ///
136    /// # Arguments
137    ///
138    /// * `new_admin` - Public key of the proposed new admin
139    ///
140    /// # Access Control
141    ///
142    /// Only the current market group admin can propose a new admin.
143    ///
144    /// # Security
145    ///
146    /// Two-step transfer prevents accidental loss of admin control by requiring the new admin
147    /// to explicitly accept the role.
148    pub fn market_group_propose_admin(
149        _ctx: Context<MarketGroupProposeAdminAccounts>,
150        _new_admin: Pubkey,
151    ) -> Result<MarketGroupProposeAdminEvent> {
152        panic!("not implemented")
153    }
154
155    /// Accept admin ownership of a market group.
156    ///
157    /// Completes the two-step ownership transfer process. The proposed admin calls this
158    /// instruction to accept control of the market group.
159    ///
160    /// # Access Control
161    ///
162    /// Only the proposed new admin can accept ownership.
163    ///
164    /// # Effects
165    ///
166    /// - Transfers full admin control to the new admin
167    /// - Clears the proposed admin field
168    /// - The new admin gains ability to:
169    /// - Create new markets in the group
170    /// - Change group fees
171    /// - Collect accumulated revenue
172    /// - Modify market permissions
173    pub fn market_group_accept_new_admin(
174        _ctx: Context<MarketGroupAcceptNewAdminAccounts>,
175    ) -> Result<MarketGroupAcceptNewAdminEvent> {
176        panic!("not implemented")
177    }
178
179    /// Initialize a linear market with a simple price curve.
180    ///
181    /// Creates a new market with a linear bonding curve that determines token prices based on
182    /// supply. The curve has three segments: floor (constant price), shoulder (linear increase),
183    /// and tail (constant max price).
184    ///
185    /// # Arguments
186    ///
187    /// * `market_linear_args` - Configuration parameters including:
188    /// - `floor`: Minimum price per token (floor price)
189    /// - `target`: Target price where the shoulder segment ends
190    /// - `slope_numerator` / `slope_denominator`: Rate of price increase in shoulder segment
191    /// - `shoulder_start` / `shoulder_end`: Token supply range for linear price growth
192    /// - `tail_start`: Token supply where max price is reached
193    /// - `permissions`: Trading restrictions and feature flags
194    ///
195    /// # Access Control
196    ///
197    /// Only the market group admin can create new markets.
198    ///
199    /// # Created Accounts
200    ///
201    /// - Market account storing price curve and state
202    /// - Token mint for the market's synthetic token
203    /// - Option token mint for exercisable options
204    /// - Liquidity vault holding backing collateral
205    /// - Revenue escrow accounts for fee collection
206    pub fn market_linear_init(
207        _ctx: Context<MarketLinearInitAccounts>,
208        _market_linear_args: MarketLinearArgs,
209    ) -> Result<()> {
210        panic!("not implemented")
211    }
212
213    /// Initialize a linear market with Dutch auction price boost.
214    ///
215    /// Creates a linear market with an additional Dutch auction mechanism that provides
216    /// temporary price boosts. The boost decays over time from a maximum multiplier down
217    /// to 1x (no boost).
218    ///
219    /// # Arguments
220    ///
221    /// * `market_linear_init_with_dutch_args` - Configuration containing:
222    /// - All standard linear market parameters (floor, target, slopes, etc.)
223    /// - `dutch_numerator` / `dutch_denominator`: Maximum price boost multiplier
224    /// - `dutch_duration`: Time in seconds for boost to decay from max to 1x
225    /// - `dutch_start`: Unix timestamp when the Dutch auction begins
226    ///
227    /// # Dutch Auction Mechanics
228    ///
229    /// - Initial boost: price × (dutch_numerator / dutch_denominator)
230    /// - Linear decay over dutch_duration seconds
231    /// - After duration expires, boost remains at 1x (no effect)
232    /// - Useful for token launches to incentivize early buyers
233    ///
234    /// # Access Control
235    ///
236    /// Only the market group admin can create new markets.
237    pub fn market_linear_init_with_dutch(
238        _ctx: Context<MarketLinearInitWithDutchAccounts>,
239        _market_linear_init_with_dutch_args: MarketLinearInitWithDutchArgs,
240    ) -> Result<()> {
241        panic!("not implemented")
242    }
243
244    /// Initialize a linear market with Dutch auction and token unit scaling.
245    ///
246    /// This instruction extends `market_linear_init_with_dutch` with support for
247    /// token unit scaling. The `token_unit_scale` parameter controls how token
248    /// units map to curve units via the factor `2^token_unit_scale`:
249    ///
250    /// - `scale=0`: 1 token = 1 curve unit (no scaling, default behavior)
251    /// - `scale=3`: 8 tokens = 1 curve unit (for high-decimal tokens)
252    /// - `scale=-2`: 1 token = 4 curve units (for low-decimal tokens)
253    ///
254    /// # Use Cases
255    ///
256    /// - High-decimal tokens (e.g., 9 decimals): Use positive scale to reduce
257    /// the effective supply range the curve operates over
258    /// - Low-decimal tokens: Use negative scale to expand the curve's range
259    ///
260    /// # Access Control
261    ///
262    /// Only the market group admin can create new markets.
263    pub fn market_simple_init_v2(
264        _ctx: Context<MarketSimpleInitV2Accounts>,
265        _market_args: MarketSimpleInitV2Args,
266    ) -> Result<()> {
267        panic!("not implemented")
268    }
269
270    /// Mint option tokens by depositing market tokens.
271    ///
272    /// Converts market tokens into option tokens at a 1:1 ratio. Option tokens represent
273    /// the right to purchase market tokens at the floor price by depositing the main
274    /// backing token (e.g., USDC).
275    ///
276    /// # Arguments
277    ///
278    /// * `amount` - Number of market tokens to convert into options
279    ///
280    /// # Requirements
281    ///
282    /// - User must have sufficient market token balance
283    /// - Market must allow option minting (check permissions)
284    ///
285    /// # Use Cases
286    ///
287    /// - Hedge against price increases by locking in floor price
288    /// - Create structured products with downside protection
289    /// - Enable secondary markets for price speculation
290    pub fn mint_options(
291        _ctx: Context<MintOptionsAccounts>,
292        _amount: u64,
293    ) -> Result<MintOptionsEvent> {
294        panic!("not implemented")
295    }
296
297    /// Collect accumulated trading fees from a market group.
298    ///
299    /// Transfers fee revenue from the group's escrow account to the admin's wallet.
300    /// Fees accumulate from all trading operations (buy, sell, borrow, exercise) across
301    /// all markets in the group.
302    ///
303    /// # Arguments
304    ///
305    /// * `amount` - Amount to collect:
306    /// - `FullOrPartialU64::Full`: Collect entire escrow balance
307    /// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
308    ///
309    /// # Access Control
310    ///
311    /// Only the market group admin can collect revenue.
312    ///
313    /// # Fee Distribution
314    ///
315    /// Trading fees are split between:
316    /// - Tenant: Platform-level fee (set during tenant creation)
317    /// - Market Group: Admin fee (set during group creation)
318    ///
319    /// This instruction collects only the group's portion.
320    pub fn market_group_collect_rev(
321        _ctx: Context<MarketGroupCollectRevAccounts>,
322        _amount: FullOrPartialU64,
323    ) -> Result<MarketGroupCollectRevEvent> {
324        panic!("not implemented")
325    }
326
327    /// Collect accumulated platform fees from a tenant.
328    ///
329    /// Transfers platform fee revenue from the tenant's escrow account to the admin's wallet.
330    /// Platform fees accumulate from all trading operations (buy, sell, borrow, exercise) across
331    /// all markets under this tenant.
332    ///
333    /// # Arguments
334    ///
335    /// * `amount` - Amount to collect:
336    /// - `FullOrPartialU64::Full`: Collect entire escrow balance
337    /// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
338    ///
339    /// # Access Control
340    ///
341    /// Only the tenant admin can collect platform revenue.
342    ///
343    /// # Fee Distribution
344    ///
345    /// Trading fees are split between:
346    /// - Tenant: Platform-level fee (set during tenant creation)
347    /// - Market Group: Admin fee (set during group creation)
348    ///
349    /// This instruction collects only the tenant's platform fee portion.
350    pub fn tenant_collect_rev(
351        _ctx: Context<TenantCollectRevAccounts>,
352        _amount: FullOrPartialU64,
353    ) -> Result<TenantCollectRevEvent> {
354        panic!("not implemented")
355    }
356
357    /// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
358    ///
359    /// Raise the market floor price while preserving bonding curve area.
360    ///
361    /// Increases the minimum (floor) price of the market token while maintaining the
362    /// total area under the price curve. This ensures the market's total value capacity
363    /// remains constant while providing price support.
364    ///
365    /// # Arguments
366    ///
367    /// * `new_floor` - New minimum price per token (must be higher than current)
368    /// * `new_shoulder_end` - New token supply where shoulder segment ends
369    ///
370    /// # Curve Adjustment
371    ///
372    /// When the floor rises:
373    /// - Floor segment moves up to new price level
374    /// - Shoulder segment becomes steeper to preserve area
375    /// - Tail segment adjusts to maintain continuity
376    ///
377    /// # Requirements
378    ///
379    /// - Market must have excess liquidity to support higher floor
380    /// - New floor must be greater than current floor
381    /// - Curve area preservation must be mathematically valid
382    ///
383    /// # Access Control
384    ///
385    /// Can be triggered by authorized operators or through automated mechanisms.
386    pub fn raise_floor_preserve_area(
387        _ctx: Context<RaiseFloorPreserveAreaAccounts>,
388        _new_floor: DecimalSerialized,
389        _new_shoulder_end: u64,
390    ) -> Result<RaiseFloorFromTriggerEvent> {
391        panic!("not implemented")
392    }
393
394    /// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
395    ///
396    /// Raise the floor price with additional validation checks.
397    ///
398    /// Similar to `raise_floor_preserve_area` but includes extra safety checks to ensure
399    /// the operation maintains market integrity. Validates curve parameters and liquidity
400    /// requirements before applying changes.
401    ///
402    /// # Arguments
403    ///
404    /// * `args` - Parameters including:
405    /// - `new_floor`: Target floor price
406    /// - `new_shoulder_end`: Adjusted shoulder endpoint
407    /// - `max_deviation_bps`: Maximum allowed deviation in basis points
408    ///
409    /// # Additional Checks
410    ///
411    /// - Verifies sufficient backing liquidity exists
412    /// - Ensures curve area preservation within tolerance
413    /// - Validates no tokens would be instantly profitable to redeem
414    /// - Checks market state consistency after adjustment
415    ///
416    /// # Use Cases
417    ///
418    /// - Automated floor raising based on market conditions
419    /// - Protocol-driven price support mechanisms
420    /// - Treasury management operations
421    pub fn raise_floor_preserve_area_checked(
422        _ctx: Context<RaiseFloorPreserveAreaCheckedAccounts>,
423        _args: RaiseFloorPreserveAreaCheckedArgs,
424    ) -> Result<RaiseFloorPreserveAreaCheckedEvent> {
425        panic!("not implemented")
426    }
427
428    /// Raise the floor and preserve the area of the market
429    /// This instruction takes in constraints
430    /// * `new_floor` - The new floor price (must be greater than the current floor)
431    /// * `new_shoulder_end` - The new shoulder end (must be greater than the current shoulder end)
432    /// * `min_liq_ratio` - The minimum liquidity ratio (greater than or equal to 0.0)
433    /// * `max_area_shrinkage_tolerance_units` - The maximum token units that the total area of the curve is allowed to shrink by
434    /// This is set by the client to restrict overly aggressive floor raising, with a tolerance to account for "slippage"
435    ///
436    /// # Access Control
437    /// Only the market group admin can raise the floor price.
438    pub fn raise_floor_preserve_area_checked2(
439        _ctx: Context<RaiseFloorPreserveAreaChecked2Accounts>,
440        _args: RaiseFloorPreserveAreaCheckedArgs2,
441    ) -> Result<RaiseFloorPreserveAreaChecked2Event> {
442        panic!("not implemented")
443    }
444
445    /// DEPRECATED: use raise_floor_from_excess_liquidity2 instead, as it is more secure
446    ///
447    /// Raise the floor price using excess market liquidity.
448    ///
449    /// Automatically increases the floor price when the market has accumulated excess
450    /// backing liquidity beyond what's needed for the current token supply. This provides
451    /// organic price appreciation based on market performance.
452    ///
453    /// # Arguments
454    ///
455    /// * `floor_increase_ratio` - Percentage increase for the floor price (as decimal)
456    /// - 0.1 = 10% increase
457    /// - 0.05 = 5% increase
458    /// - Must be positive and reasonable (typically < 0.5)
459    ///
460    /// # Mechanism
461    ///
462    /// 1. Calculates available excess liquidity (cash above backing requirements)
463    /// 2. Determines maximum sustainable floor increase
464    /// 3. Applies requested ratio (capped by available excess)
465    /// 4. Adjusts curve parameters to preserve total area
466    ///
467    /// # Requirements
468    ///
469    /// - Market must have excess liquidity
470    /// - Floor increase must be sustainable given current token supply
471    /// - Market permissions must allow floor raising
472    ///
473    /// # Benefits
474    ///
475    /// - Rewards token holders when market performs well
476    /// - Creates deflationary pressure through higher floor
477    /// - Maintains full backing at new price levels
478    pub fn raise_floor_from_excess_liquidity(
479        _ctx: Context<RaiseFloorFromExcessLiquidityAccounts>,
480        _floor_increase_ratio: DecimalSerialized,
481    ) -> Result<RaiseFloorFromExcessLiquidityEvent> {
482        panic!("not implemented")
483    }
484
485    /// Raise the floor price using excess market liquidity.
486    ///
487    /// Automatically increases the floor price when the market has accumulated excess
488    /// backing liquidity beyond what's needed for the current token supply. This provides
489    /// organic price appreciation based on market performance.
490    ///
491    /// # Arguments
492    ///
493    /// * `args` - Parameters including:
494    /// - `max_new_floor`: The maximum new floor that is allowed
495    /// - `increase_ratio_micro_basis_points`: The amount to increase the floor by, in micro basis points
496    ///
497    /// # Access Control
498    ///
499    /// Only the market group admin can raise the floor price.
500    ///
501    /// # Use Cases
502    /// - Automated floor raising based on market conditions
503    /// - Protocol-driven price support mechanisms
504    /// - Treasury management operations
505    pub fn raise_floor_from_excess_liquidity_checked(
506        _ctx: Context<RaiseFloorFromExcessLiquidityCheckedAccounts>,
507        _args: RaiseFloorFromExcessLiquidityCheckedArgs,
508    ) -> Result<RaiseFloorFromExcessLiquidity2Event> {
509        panic!("not implemented")
510    }
511
512    /// Update market permissions and feature flags.
513    ///
514    /// Controls which operations are allowed on a market. Can be used to pause trading,
515    /// disable specific features, or adjust market behavior.
516    ///
517    /// # Arguments
518    ///
519    /// * `new_flags` - New permission set including:
520    /// - `can_buy`: Allow token purchases
521    /// - `can_sell`: Allow token sales
522    /// - `can_borrow`: Allow borrowing against collateral
523    /// - `can_add_liquidity`: Allow liquidity donations
524    /// - `can_remove_liquidity`: Allow liquidity removal
525    /// - `can_open_position`: Allow new position creation
526    /// - `can_close_position`: Allow position closure
527    /// - `can_change_fees`: Allow fee adjustments
528    ///
529    /// # Access Control
530    ///
531    /// Only the market group admin can change market flags.
532    ///
533    /// # Use Cases
534    ///
535    /// - Emergency pause during security incidents
536    /// - Gradual feature rollout
537    /// - Market maintenance windows
538    /// - Compliance-driven restrictions
539    pub fn market_flags_change(
540        _ctx: Context<MarketFlagsChangeAccounts>,
541        _new_flags: MarketPermissions,
542    ) -> Result<MarketFlagsChangeEvent> {
543        panic!("not implemented")
544    }
545
546    /// Update fee structure for all markets in a group.
547    ///
548    /// Changes the fee rates charged on trading operations. New fees apply to all future
549    /// transactions across all markets within the group.
550    ///
551    /// # Arguments
552    ///
553    /// * `new_fees` - Updated fee structure:
554    /// - `buy`: Fee on token purchases (micro basis points)
555    /// - `sell`: Fee on token sales (micro basis points)
556    /// - `borrow`: Fee on borrowing operations (micro basis points)
557    /// - `exercise`: Fee on option exercise (micro basis points)
558    ///
559    /// # Fee Calculation
560    ///
561    /// Fees are specified in micro basis points where:
562    /// - 1 micro bp = 1/100 of a basis point = 0.0001%
563    /// - 100 micro bps = 1 basis point = 0.01%
564    /// - 10,000 micro bps = 100 basis points = 1%
565    /// - Example: 50 micro bps = 0.5 basis points = 0.005% fee
566    ///
567    /// # Access Control
568    ///
569    /// Only the market group admin can change fees.
570    ///
571    /// # Considerations
572    ///
573    /// - Changes affect all markets in the group immediately
574    /// - Cannot exceed maximum fee limits set by protocol
575    /// - Platform (tenant) fees are added on top of group fees
576    pub fn market_group_change_fees(
577        _ctx: Context<MarketGroupChangeFeesAccounts>,
578        _new_fees: Fees,
579    ) -> Result<MarketGroupChangeFeesEvent> {
580        panic!("not implemented")
581    }
582
583    /// Initialize a personal position account for market interaction.
584    ///
585    /// Creates a user-specific account that tracks collateral deposits and debt obligations
586    /// for a particular market. Required before performing borrow operations or using
587    /// collateral-based features.
588    ///
589    /// # Position Features
590    ///
591    /// Personal positions enable:
592    /// - Collateral deposits (market tokens as collateral)
593    /// - Borrowing against collateral (up to LTV limits)
594    /// - Tracking debt obligations and interest
595    /// - Liquidation protection through collateralization
596    ///
597    /// # Account Structure
598    ///
599    /// - Unique per user per market
600    /// - Stores collateral and debt balances
601    /// - Tracks last update timestamp for interest
602    /// - Immutable market and owner references
603    ///
604    /// # One-Time Setup
605    ///
606    /// Each user needs only one position per market. Attempting to create a duplicate
607    /// will fail. The position persists until explicitly closed.
608    pub fn personal_position_init(
609        _ctx: Context<PersonalPositionInitAccounts>,
610    ) -> Result<PersonalPositionInitEvent> {
611        panic!("not implemented")
612    }
613
614    /// DEPRECATED: use donate_liquidity2 instead, as v2 gets logged by the indexer
615    ///
616    /// Donate backing liquidity to the market.
617    ///
618    /// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
619    /// market tokens in return. This creates excess liquidity that can be used to raise
620    /// the floor price or improve market stability.
621    ///
622    /// # Arguments
623    ///
624    /// * `amount` - Amount of main tokens to donate
625    ///
626    /// # Effects
627    ///
628    /// - Increases market's cash balance
629    /// - Creates excess liquidity (cash > backing requirements)
630    /// - Enables floor price increases
631    /// - Benefits all token holders through improved backing
632    ///
633    /// # Use Cases
634    ///
635    /// - Protocol treasury supporting market stability
636    /// - Community-funded price support
637    /// - Grants or subsidies to bootstrap markets
638    /// - Creating buffer for market operations
639    ///
640    /// # Note
641    ///
642    /// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
643    pub fn donate_liquidity(
644        _ctx: Context<DonateLiquidityAccounts>,
645        _amount: u64,
646    ) -> Result<DonateLiquidityEvent> {
647        panic!("not implemented")
648    }
649
650    /// Donate backing liquidity to the market.
651    ///
652    /// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
653    /// market tokens in return. This creates excess liquidity that can be used to raise
654    /// the floor price or improve market stability.
655    ///
656    /// # Arguments
657    ///
658    /// * `amount` - Amount of main tokens to donate
659    ///
660    /// # Effects
661    ///
662    /// - Increases market's cash balance
663    /// - Creates excess liquidity (cash > backing requirements)
664    /// - Enables floor price increases
665    /// - Benefits all token holders through improved backing
666    ///
667    /// # Use Cases
668    ///
669    /// - Protocol treasury supporting market stability
670    /// - Community-funded price support
671    /// - Grants or subsidies to bootstrap markets
672    /// - Creating buffer for market operations
673    ///
674    /// # Note
675    ///
676    /// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
677    pub fn donate_liquidity2(
678        _ctx: Context<DonateLiquidity2Accounts>,
679        _amount: u64,
680    ) -> Result<DonateLiquidityEvent> {
681        panic!("not implemented")
682    }
683
684    /// Buy market tokens using exact amount of main tokens.
685    ///
686    /// Purchases market tokens by depositing a specific amount of main tokens (e.g., USDC).
687    /// The number of tokens received depends on the current price curve position. Includes
688    /// slippage protection through minimum output requirement.
689    ///
690    /// # Arguments
691    ///
692    /// * `cash_in` - Exact amount of main tokens to spend
693    /// * `min_token_out` - Minimum market tokens to receive (reverts if not met)
694    ///
695    /// # Price Calculation
696    ///
697    /// Token price follows the bonding curve:
698    /// - Floor segment: Constant price at floor level
699    /// - Shoulder segment: Linear price increase
700    /// - Tail segment: Constant price at maximum
701    /// - Dutch boost: Temporary multiplier if active
702    ///
703    /// # Fees
704    ///
705    /// Buy fee is deducted from input amount:
706    /// - Platform fee (tenant level)
707    /// - Group fee (market group level)
708    /// - Net amount used for token purchase
709    ///
710    /// # Slippage Protection
711    ///
712    /// Transaction reverts if `tokens_received < min_token_out`
713    pub fn buy_with_exact_cash_in(
714        _ctx: Context<BuyWithExactCashInAccounts>,
715        _cash_in: u64,
716        _min_token_out: u64,
717    ) -> Result<BuyEvent> {
718        panic!("not implemented")
719    }
720
721    /// Buy market tokens and immediately deposit as collateral.
722    ///
723    /// Combines token purchase with collateral deposit in a single atomic transaction.
724    /// Useful for users who want to immediately use purchased tokens as collateral for
725    /// borrowing operations.
726    ///
727    /// # Arguments
728    ///
729    /// * `cash_in` - Exact amount of main tokens to spend
730    /// * `min_token_out` - Minimum market tokens to receive
731    ///
732    /// # Transaction Flow
733    ///
734    /// 1. Deduct fees from input amount
735    /// 2. Purchase tokens at current curve price
736    /// 3. Deposit all tokens into personal position
737    /// 4. Update position's collateral balance
738    ///
739    /// # Requirements
740    ///
741    /// - Personal position must exist (call `personal_position_init` first)
742    /// - Sufficient main token balance
743    /// - Market must allow buying and deposits
744    ///
745    /// # Benefits
746    ///
747    /// - Single transaction reduces costs
748    /// - Atomic operation prevents MEV
749    /// - Immediate collateral availability
750    pub fn buy_with_exact_cash_in_and_deposit(
751        _ctx: Context<BuyWithExactCashInAndDepositAccounts>,
752        _cash_in: u64,
753        _min_token_out: u64,
754    ) -> Result<BuyWithExactCashInAndDepositEvent> {
755        panic!("not implemented")
756    }
757
758    /// Buy market tokens and immediately deposit as collateral with debt.
759    ///
760    /// Combines token purchase with collateral deposit in a single atomic transaction.
761    /// Useful for users who want to immediately use purchased tokens as collateral for
762    /// borrowing operations.
763    ///
764    /// # Arguments
765    ///
766    /// * `args` - Arguments for the transaction
767    /// - `exact_cash_in` - Exact amount of cash to spend on tokens
768    /// - `min_token_received` - Minimum acceptable tokens to receive (slippage protection)
769    /// - `new_acquired_debt` - New debt amount to take on
770    pub fn buy_with_exact_cash_in_and_deposit_with_debt(
771        _ctx: Context<BuyWithExactCashInAndDepositWithDebtAccounts>,
772        _args: BuyWithExactCashInAndDepositWithDebtArgs,
773    ) -> Result<BuyWithExactCashInAndDepositWithDebtEvent> {
774        panic!("not implemented")
775    }
776
777    /// Sell exact amount of market tokens for main tokens.
778    ///
779    /// Sells a specific number of market tokens and receives main tokens (e.g., USDC)
780    /// based on the current bonding curve price. Includes slippage protection through
781    /// minimum output requirement.
782    ///
783    /// # Arguments
784    ///
785    /// * `amount_in` - Exact number of market tokens to sell
786    /// * `cash_out_min` - Minimum main tokens to receive (reverts if not met)
787    ///
788    /// # Price Calculation
789    ///
790    /// Sell price follows bonding curve in reverse:
791    /// - Reduces token supply, moving down the curve
792    /// - Higher supplies sell at higher prices first
793    /// - Cannot sell below floor price
794    ///
795    /// # Fees
796    ///
797    /// Sell fee is deducted from output amount:
798    /// - Gross proceeds calculated from curve
799    /// - Platform and group fees deducted
800    /// - Net amount sent to seller
801    ///
802    /// # Market Impact
803    ///
804    /// Large sells may experience price slippage as they move down the curve.
805    /// Consider breaking into smaller transactions for better execution.
806    pub fn sell_with_exact_token_in(
807        _ctx: Context<SellWithExactTokenInAccounts>,
808        _amount_in: u64,
809        _cash_out_min: u64,
810    ) -> Result<SellWithExactTokenInEvent> {
811        panic!("not implemented")
812    }
813
814    /// Withdraw collateral and sell tokens in one transaction.
815    ///
816    /// Atomically withdraws market tokens from a personal position and sells them for
817    /// main tokens. Useful for exiting collateralized positions or taking profits.
818    ///
819    /// # Arguments
820    ///
821    /// * `amount_in` - Number of tokens to withdraw and sell
822    /// * `cash_out_min` - Minimum main tokens to receive
823    ///
824    /// # Transaction Flow
825    ///
826    /// 1. Withdraw tokens from personal position
827    /// 2. Check position remains healthy (if debt exists)
828    /// 3. Sell tokens on bonding curve
829    /// 4. Transfer proceeds to user
830    ///
831    /// # Position Health
832    ///
833    /// If position has outstanding debt:
834    /// - Remaining collateral must maintain required LTV
835    /// - Transaction reverts if withdrawal would enable liquidation
836    /// - Consider repaying debt before large withdrawals
837    ///
838    /// # Use Cases
839    ///
840    /// - Taking profits while maintaining position
841    /// - Reducing exposure during market volatility
842    /// - Exiting positions efficiently
843    pub fn sell_with_exact_token_in_after_withdraw(
844        _ctx: Context<SellWithExactTokenInAfterWithdrawAccounts>,
845        _amount_in: u64,
846        _cash_out_min: u64,
847    ) -> Result<SellWithExactTokenInAfterWithdrawEvent> {
848        panic!("not implemented")
849    }
850
851    /// Deposit market tokens as collateral into personal position.
852    ///
853    /// Adds market tokens to your position's collateral balance, enabling borrowing
854    /// operations. Deposited tokens remain locked until withdrawn or liquidated.
855    ///
856    /// # Arguments
857    ///
858    /// * `amount` - Number of market tokens to deposit
859    ///
860    /// # Collateral Benefits
861    ///
862    /// - Enables borrowing main tokens up to LTV limit
863    /// - Earns potential appreciation if floor price rises
864    /// - Protects position from liquidation
865    /// - Can be withdrawn anytime (if position healthy)
866    ///
867    /// # Requirements
868    ///
869    /// - Personal position must exist
870    /// - Sufficient token balance in wallet
871    /// - Market must allow deposits
872    pub fn deposit(_ctx: Context<DepositAccounts>, _amount: u64) -> Result<DepositEvent> {
873        panic!("not implemented")
874    }
875
876    /// Withdraw collateral from personal position.
877    ///
878    /// Removes market tokens from collateral, returning them to your wallet. Withdrawal
879    /// is only allowed if the position remains healthy after removal.
880    ///
881    /// # Arguments
882    ///
883    /// * `amount` - Number of market tokens to withdraw
884    ///
885    /// # Health Requirements
886    ///
887    /// If position has debt:
888    /// - Remaining collateral value must exceed debt × (1 / LTV)
889    /// - Example: $1000 debt at 80% LTV requires $1250 collateral
890    /// - Transaction reverts if health check fails
891    ///
892    /// # Full Withdrawal
893    ///
894    /// To withdraw all collateral:
895    /// 1. Repay all outstanding debt first
896    /// 2. Then withdraw full collateral balance
897    pub fn withdraw(_ctx: Context<WithdrawAccounts>, _amount: u64) -> Result<WithdrawEvent> {
898        panic!("not implemented")
899    }
900
901    /// Borrow main tokens against deposited collateral.
902    ///
903    /// Takes a loan in main tokens (e.g., USDC) using market tokens as collateral.
904    /// Borrowed amount is limited by position's collateral value and market LTV ratio.
905    ///
906    /// # Arguments
907    ///
908    /// * `amount` - Amount of main tokens to borrow
909    ///
910    /// # Borrowing Limits
911    ///
912    /// Maximum borrow = Collateral Value × LTV Ratio
913    /// - Collateral valued at current floor price
914    /// - LTV typically 50-80% depending on market
915    /// - Cannot exceed available market liquidity
916    ///
917    /// # Interest Accrual
918    ///
919    /// - Interest calculated per-second at market rate
920    /// - Compounds continuously on outstanding debt
921    /// - Rate may vary based on utilization
922    ///
923    /// # Liquidation Risk
924    ///
925    /// Position can be liquidated if:
926    /// - Market token price drops significantly
927    /// - Accumulated interest pushes debt above limit
928    /// - Market LTV parameters change
929    ///
930    /// Monitor position health regularly to avoid liquidation.
931    pub fn borrow(_ctx: Context<BorrowAccounts>, _amount: u64) -> Result<BorrowEvent> {
932        panic!("not implemented")
933    }
934
935    /// Repay borrowed main tokens to reduce debt.
936    ///
937    /// Repays outstanding debt in main tokens, reducing position's obligations and
938    /// improving health factor. Can repay partial or full amounts.
939    ///
940    /// # Arguments
941    ///
942    /// * `amount` - Amount of main tokens to repay
943    ///
944    /// # Repayment Order
945    ///
946    /// Payments apply to:
947    /// 1. Accrued interest first
948    /// 2. Principal debt second
949    ///
950    /// # Benefits of Repayment
951    ///
952    /// - Reduces liquidation risk
953    /// - Stops interest accrual on repaid amount
954    /// - Frees up borrowing capacity
955    /// - Enables collateral withdrawal
956    ///
957    /// # Full Repayment
958    ///
959    /// To close position completely:
960    /// 1. Repay all debt including accrued interest
961    /// 2. Withdraw all collateral
962    /// 3. Position can then be closed if desired
963    pub fn repay(_ctx: Context<RepayAccounts>, _amount: u64) -> Result<RepayEvent> {
964        panic!("not implemented")
965    }
966
967    /// Withdraw collateral, sell it, and optionally repay debt from proceeds.
968    ///
969    /// Atomically combines withdraw, sell, and repay operations. Withdraws collateral tokens
970    /// from personal position, sells them back to the market, optionally repays debt from
971    /// the proceeds, and transfers remaining cash to the user.
972    ///
973    /// # Arguments
974    ///
975    /// * `args.collateral_reduce_by` - Amount of collateral tokens to withdraw and sell
976    /// * `args.debt_reduce_by` - Amount of debt to repay from sale proceeds (can be 0)
977    /// * `args.min_cash_to_user` - Minimum cash to receive after repaying debt (slippage protection)
978    ///
979    /// # Operation Flow
980    ///
981    /// 1. Withdraw collateral from position
982    /// 2. Sell withdrawn collateral to market
983    /// 3. Repay debt from sale proceeds (if debt_reduce_by > 0)
984    /// 4. Transfer remaining cash to user
985    ///
986    /// # Slippage Protection
987    ///
988    /// Transaction fails if:
989    /// - Sale proceeds < debt_reduce_by + min_cash_to_user
990    /// - Protects against unfavorable price movements
991    ///
992    /// # Debt Repayment
993    ///
994    /// - Debt repayment is optional (debt_reduce_by can be 0)
995    /// - If repaying, permission checks ensure repay is allowed
996    /// - Remaining sale proceeds go to user after repayment
997    ///
998    /// # Use Cases
999    ///
1000    /// - Close leveraged position: withdraw all collateral, sell, repay all debt
1001    /// - Partial deleverage: reduce position and debt simultaneously
1002    /// - Take profit: withdraw and sell collateral, keep debt unchanged (debt_reduce_by = 0)
1003    pub fn withdraw_sell_and_repay(
1004        _ctx: Context<WithdrawSellAndRepayAccounts>,
1005        _args: WithdrawSellAndRepayArgs,
1006    ) -> Result<WithdrawSellAndRepayEvent> {
1007        panic!("not implemented")
1008    }
1009
1010    /// Exercise option tokens to purchase market tokens at floor price.
1011    ///
1012    /// Converts option tokens into market tokens by paying the floor price in main tokens.
1013    /// This allows option holders to acquire tokens at a fixed price regardless of current
1014    /// market price.
1015    ///
1016    /// # Arguments
1017    ///
1018    /// * `amount` - Number of option tokens to exercise
1019    ///
1020    /// # Economics
1021    ///
1022    /// For each option token:
1023    /// - Pay: 1 unit of main token × floor price
1024    /// - Receive: 1 market token
1025    /// - Burn: 1 option token
1026    ///
1027    /// # Profitability
1028    ///
1029    /// Profitable when: Current Price > Floor Price + Exercise Fee
1030    /// - Check current bonding curve price
1031    /// - Account for exercise fees
1032    /// - Consider immediate sell vs holding
1033    ///
1034    /// # Requirements
1035    ///
1036    /// - Sufficient option token balance
1037    /// - Sufficient main tokens for payment
1038    /// - Market must allow option exercise
1039    pub fn exercise_options(
1040        _ctx: Context<ExerciseOptionsAccounts>,
1041        _amount: u64,
1042    ) -> Result<ExerciseOptionsEvent> {
1043        panic!("not implemented")
1044    }
1045
1046    /// Redeem market tokens at the guaranteed floor price.
1047    ///
1048    /// Allows token holders to exit at the floor price when market price is at or near
1049    /// the floor. This provides downside protection and ensures minimum redemption value.
1050    ///
1051    /// # Arguments
1052    ///
1053    /// * `amount_tokens_in` - Number of market tokens to redeem
1054    ///
1055    /// # Redemption Limits
1056    ///
1057    /// Maximum redeemable = Tail Width = (tail_start - shoulder_end)
1058    /// - Protects bonding curve integrity
1059    /// - Ensures sufficient liquidity for all holders
1060    /// - Resets as tokens are bought back
1061    ///
1062    /// # Price Guarantee
1063    ///
1064    /// Receives: Floor Price × Tokens - Fees
1065    /// - Always redeems at floor regardless of curve position
1066    /// - Sell fees still apply (platform + group)
1067    /// - Net proceeds = floor_price × tokens × (1 - total_fee_rate)
1068    ///
1069    /// # Use Cases
1070    ///
1071    /// - Exit strategy during market downturns
1072    /// - Arbitrage when market price < floor
1073    /// - Risk management for large positions
1074    pub fn redeem_at_floor(
1075        _ctx: Context<RedeemAtFloorAccounts>,
1076        _amount_tokens_in: u64,
1077    ) -> Result<RedeemAtFloorEvent> {
1078        panic!("not implemented")
1079    }
1080
1081    /// Initialize a multi-curve market with Dutch auction configuration.
1082    ///
1083    /// Creates a market using a multi-segment bonding curve that provides more flexibility
1084    /// than linear markets. Supports variable-length price curves with multiple segments,
1085    /// each with its own slope. Includes Dutch auction for initial price discovery.
1086    ///
1087    /// # Arguments
1088    ///
1089    /// * `args` - Configuration including:
1090    /// - `floor`: Base price per token
1091    /// - `target`: Maximum price per token
1092    /// - `shoulder_start` / `shoulder_end`: Range for initial linear segment
1093    /// - `tail_start`: Beginning of constant max price segment
1094    /// - `middle_segments`: Array of intermediate curve segments
1095    /// - Dutch auction parameters (multiplier, duration, start time)
1096    ///
1097    /// # Multi-Curve Advantages
1098    ///
1099    /// - Flexible price discovery through custom segments
1100    /// - Better modeling of complex tokenomics
1101    /// - Smooth transitions between price regions
1102    /// - Support for non-linear growth patterns
1103    ///
1104    /// # Segment Structure
1105    ///
1106    /// 1. Floor: Constant price from 0 to shoulder_start
1107    /// 2. First shoulder: Linear from shoulder_start to first middle segment
1108    /// 3. Middle segments: Variable slopes and ranges (can be empty)
1109    /// 4. Final shoulder: From last middle segment to shoulder_end
1110    /// 5. Tail: Constant max price from tail_start onward
1111    ///
1112    /// # Access Control
1113    ///
1114    /// Only the market group admin can create new markets.
1115    pub fn multi_market_init_with_dutch(
1116        _ctx: Context<MultiMarketInitWithDutchAccounts>,
1117        _args: MultiMarketInitWithDutchArgs,
1118    ) -> Result<()> {
1119        panic!("not implemented")
1120    }
1121
1122    /// Raise floor price for multi-curve markets with validation.
1123    ///
1124    /// Increases the minimum token price while preserving the total area under the
1125    /// multi-segment curve. More complex than linear markets due to multiple segments
1126    /// requiring coordinated adjustment.
1127    ///
1128    /// # Arguments
1129    ///
1130    /// * `args` - Parameters including:
1131    /// - `new_floor`: Target floor price
1132    /// - `new_shoulder_end`: Adjusted endpoint for price curve
1133    /// - `new_middle_segments`: Recalculated intermediate segments
1134    /// - `max_deviation_bps`: Tolerance for area preservation
1135    ///
1136    /// # Segment Adjustment
1137    ///
1138    /// When floor rises:
1139    /// 1. All segments shift up by floor delta
1140    /// 2. Slopes adjust to maintain total area
1141    /// 3. Segment boundaries may compress
1142    /// 4. Continuity preserved at all transitions
1143    ///
1144    /// # Validation Checks
1145    ///
1146    /// - Area preservation within tolerance
1147    /// - Sufficient backing liquidity
1148    /// - Valid segment progression (monotonic)
1149    /// - No instant arbitrage opportunities
1150    ///
1151    /// # Complexity Note
1152    ///
1153    /// Multi-curve floor raising requires careful calculation to maintain curve
1154    /// properties across all segments while preserving economic invariants.
1155    pub fn raise_floor_preserve_area_checked_multi(
1156        _ctx: Context<RaiseFloorPreserveAreaCheckedMultiAccounts>,
1157        _args: RaiseFloorPreserveAreaCheckedMultiArgs,
1158    ) -> Result<RaiseFloorPreserveAreaCheckedEvent> {
1159        panic!("not implemented")
1160    }
1161
1162    /// Buy from multi-curve market and deposit as collateral.
1163    ///
1164    /// Purchases tokens from a multi-segment bonding curve and immediately deposits them
1165    /// into a personal position. Combines acquisition and collateralization in one step.
1166    ///
1167    /// # Arguments
1168    ///
1169    /// * `cash_in` - Exact amount of main tokens to spend
1170    /// * `min_token_out` - Minimum tokens to receive (slippage protection)
1171    ///
1172    /// # Multi-Curve Pricing
1173    ///
1174    /// Price depends on current supply position:
1175    /// - Traverses multiple segments with different slopes
1176    /// - Large buys may span several segments
1177    /// - Each segment calculated independently
1178    /// - Dutch boost applies if active
1179    ///
1180    /// # Atomic Benefits
1181    ///
1182    /// - Single transaction for buy + deposit
1183    /// - Reduces transaction costs
1184    /// - Prevents front-running between operations
1185    /// - Immediate collateral availability
1186    ///
1187    /// # Requirements
1188    ///
1189    /// - Personal position must exist
1190    /// - Market must allow buying and deposits
1191    /// - Sufficient main token balance
1192    pub fn buy_with_exact_cash_in_and_deposit_multi(
1193        _ctx: Context<BuyWithExactCashInAndDepositMultiAccounts>,
1194        _cash_in: u64,
1195        _min_token_out: u64,
1196    ) -> Result<BuyWithExactCashInAndDepositEvent> {
1197        panic!("not implemented")
1198    }
1199
1200    /// Buy tokens from a multi-curve market.
1201    ///
1202    /// Purchases market tokens using a multi-segment bonding curve that can model
1203    /// complex price dynamics. Supports large purchases that span multiple curve
1204    /// segments with different characteristics.
1205    ///
1206    /// # Arguments
1207    ///
1208    /// * `cash_in` - Exact amount of main tokens to spend
1209    /// * `min_token_out` - Minimum tokens required (reverts if not met)
1210    ///
1211    /// # Execution Across Segments
1212    ///
1213    /// Large purchases may traverse multiple segments:
1214    /// 1. Start at current supply position
1215    /// 2. Buy at current segment's price/slope
1216    /// 3. If segment exhausted, continue to next
1217    /// 4. Accumulate tokens from each segment
1218    /// 5. Stop when cash exhausted or curve end reached
1219    ///
1220    /// # Price Impact
1221    ///
1222    /// - Each segment may have different price sensitivity
1223    /// - Steeper slopes mean higher price impact
1224    /// - Consider breaking very large orders
1225    ///
1226    /// # Fees
1227    ///
1228    /// Standard fee structure applies:
1229    /// - Platform fee to tenant
1230    /// - Group fee to market admin
1231    /// - Deducted from input amount
1232    pub fn buy_with_exact_cash_in_multi(
1233        _ctx: Context<BuyWithExactCashInMultiAccounts>,
1234        _cash_in: u64,
1235        _min_token_out: u64,
1236    ) -> Result<BuyEvent> {
1237        panic!("not implemented")
1238    }
1239
1240    /// Sell tokens to a multi-curve market.
1241    ///
1242    /// Sells market tokens back to the protocol following the multi-segment bonding curve
1243    /// in reverse. Large sales may span multiple segments with varying price impacts.
1244    ///
1245    /// # Arguments
1246    ///
1247    /// * `amount_in` - Exact number of tokens to sell
1248    /// * `cash_out_min` - Minimum main tokens to receive
1249    ///
1250    /// # Multi-Segment Execution
1251    ///
1252    /// Sells work backwards through curve:
1253    /// 1. Start at current supply position
1254    /// 2. Sell into current segment at its price
1255    /// 3. If more to sell, move to previous segment
1256    /// 4. Continue until all tokens sold
1257    /// 5. Cannot sell below floor price
1258    ///
1259    /// # Price Discovery
1260    ///
1261    /// - Higher supplies sell first (higher prices)
1262    /// - Price decreases as supply reduces
1263    /// - Each segment has independent characteristics
1264    /// - Floor provides absolute minimum
1265    ///
1266    /// # Slippage Considerations
1267    ///
1268    /// Multi-curve markets may have:
1269    /// - Variable liquidity across segments
1270    /// - Sudden price changes at boundaries
1271    /// - Different impacts in different regions
1272    pub fn sell_with_exact_token_in_multi(
1273        _ctx: Context<SellWithExactTokenInMultiAccounts>,
1274        _amount_in: u64,
1275        _cash_out_min: u64,
1276    ) -> Result<SellWithExactTokenInEvent> {
1277        panic!("not implemented")
1278    }
1279
1280    /// Exercise options in a multi-curve market.
1281    ///
1282    /// Converts option tokens to market tokens at the floor price, regardless of the
1283    /// current position on the multi-segment curve. Options provide downside protection
1284    /// in volatile multi-curve markets.
1285    ///
1286    /// # Arguments
1287    ///
1288    /// * `amount` - Number of option tokens to exercise
1289    ///
1290    /// # Exercise Mechanics
1291    ///
1292    /// Same as linear markets:
1293    /// - Pay floor price per option in main tokens
1294    /// - Receive one market token per option
1295    /// - Options are burned
1296    ///
1297    /// # Multi-Curve Considerations
1298    ///
1299    /// - Floor price is constant across all segments
1300    /// - Current curve position doesn't affect exercise
1301    /// - Especially valuable when price is in higher segments
1302    /// - Provides arbitrage during market dislocations
1303    ///
1304    /// # Strategic Use
1305    ///
1306    /// In multi-curve markets, options help:
1307    /// - Navigate complex price dynamics
1308    /// - Profit from segment transitions
1309    /// - Hedge against curve adjustments
1310    pub fn exercise_options_multi(
1311        _ctx: Context<ExerciseOptionsMultiAccounts>,
1312        _amount: u64,
1313    ) -> Result<ExerciseOptionsEvent> {
1314        panic!("not implemented")
1315    }
1316
1317    /// Repay debt in a multi-curve market.
1318    ///
1319    /// Repays borrowed main tokens to reduce debt obligations in a personal position.
1320    /// Multi-curve markets may have different interest dynamics based on utilization
1321    /// across curve segments.
1322    ///
1323    /// # Arguments
1324    ///
1325    /// * `amount` - Amount of main tokens to repay
1326    ///
1327    /// # Interest Considerations
1328    ///
1329    /// Multi-curve markets may feature:
1330    /// - Variable rates based on curve position
1331    /// - Different risk profiles across segments
1332    /// - Dynamic rate adjustments
1333    ///
1334    /// # Repayment Priority
1335    ///
1336    /// Same as linear markets:
1337    /// 1. Accrued interest first
1338    /// 2. Principal balance second
1339    /// 3. Excess returned to payer
1340    ///
1341    /// # Position Management
1342    ///
1343    /// Regular repayments recommended to:
1344    /// - Maintain healthy LTV ratios
1345    /// - Reduce liquidation risk
1346    /// - Take advantage of rate changes
1347    pub fn repay_multi(_ctx: Context<RepayMultiAccounts>, _amount: u64) -> Result<RepayEvent> {
1348        panic!("not implemented")
1349    }
1350
1351    /// Redeem tokens at floor price in multi-curve market.
1352    ///
1353    /// Provides guaranteed exit at the floor price for multi-curve market tokens.
1354    /// Essential safety mechanism given the complexity of multi-segment pricing.
1355    ///
1356    /// # Arguments
1357    ///
1358    /// * `amount_tokens_in` - Number of tokens to redeem at floor
1359    ///
1360    /// # Redemption in Complex Markets
1361    ///
1362    /// Multi-curve considerations:
1363    /// - Floor constant across all segments
1364    /// - Redemption bypasses curve complexity
1365    /// - Same tail width limits apply
1366    /// - Critical during segment transitions
1367    ///
1368    /// # Maximum Redemption
1369    ///
1370    /// Limited to tail width: (tail_start - shoulder_end)
1371    /// - Protects curve integrity
1372    /// - Ensures fair access for all holders
1373    /// - Resets as market activity continues
1374    ///
1375    /// # Use Cases
1376    ///
1377    /// Especially important in multi-curve markets for:
1378    /// - Exiting during curve adjustments
1379    /// - Arbitrage across segments
1380    /// - Risk management in complex dynamics
1381    /// - Guaranteed liquidity provision
1382    pub fn redeem_at_floor_multi(
1383        _ctx: Context<RedeemAtFloorMultiAccounts>,
1384        _amount_tokens_in: u64,
1385    ) -> Result<RedeemAtFloorEvent> {
1386        panic!("not implemented")
1387    }
1388
1389    /// Modify the price curve's sensitivity to supply changes at the current token supply level.
1390    ///
1391    /// Allows market administrators to dynamically adjust how quickly the token price changes
1392    /// in response to supply increases. The modification is applied at the current token supply
1393    /// level and affects the curve's behavior for all future supply levels beyond that point.
1394    ///
1395    /// # Arguments
1396    ///
1397    /// * `args` - Curve modification parameters including:
1398    /// - `multiplier`: Magnitude of slope change (0.0 < multiplier < 1.0)
1399    /// - `new_middle_segment_count`: Expected number of middle segments after modification
1400    /// - `increase`: Whether to increase (true) or decrease (false) sensitivity
1401    ///
1402    /// # How it works
1403    ///
1404    /// The function modifies the curve's vertex structure by either:
1405    /// - **Inserting a new vertex** at the current supply level if it falls within the final segment
1406    /// - **Removing the last vertex** if the current supply is not in the final segment and the
1407    /// sensitivity direction doesn't match the final segment's current direction
1408    ///
1409    /// # Sensitivity Direction
1410    ///
1411    /// - **`increase = true`** (`SensitivityDirection::Higher`): Makes the curve more sensitive to supply changes
1412    /// - Results in steeper slopes = faster price increases as supply grows
1413    /// - Useful for encouraging early adoption or responding to high demand
1414    ///
1415    /// - **`increase = false`** (`SensitivityDirection::Lower`): Makes the curve less sensitive to supply changes
1416    /// - Results in gentler slopes = slower price increases as supply grows
1417    /// - Useful for risk management or stabilizing prices in volatile conditions
1418    ///
1419    /// # Multiplier Effect
1420    ///
1421    /// The `multiplier` parameter (0.0 < multiplier < 1.0) determines the magnitude of change:
1422    /// - For `Higher` direction: new_slope = current_slope × (1 + multiplier)
1423    /// - For `Lower` direction: new_slope = current_slope × (1 - multiplier)
1424    ///
1425    /// # Access Control
1426    ///
1427    /// Only the market group admin can modify curves.
1428    ///
1429    /// # Use Cases
1430    ///
1431    /// - **Market Making**: Adjust sensitivity based on trading volume or market volatility
1432    /// - **Risk Management**: Reduce sensitivity in high-supply regions to prevent extreme price swings
1433    /// - **Liquidity Provision**: Increase sensitivity in low-supply regions to encourage early adoption
1434    /// - **Dynamic Pricing**: Respond to market conditions by modifying curve behavior
1435    ///
1436    /// # Constraints
1437    ///
1438    /// - `multiplier` must be between 0.0 and 1.0 (exclusive)
1439    /// - The function preserves curve continuity at segment boundaries
1440    /// - Modifications only affect the curve beyond the current supply level
1441    /// - The account must be reallocated to accommodate the new segment count
1442    ///
1443    /// # Safety Considerations
1444    ///
1445    /// - Changes are irreversible once applied
1446    /// - The operation will panic if the actual number of middle segments after modification
1447    /// doesn't match the expected `new_middle_segment_count`
1448    /// - Consider market impact before significant changes
1449    /// - Monitor market behavior after curve changes
1450    pub fn modify_curve_multi(
1451        _ctx: Context<ModifyCurveMultiAccounts>,
1452        _args: ModifyCurveArgs,
1453    ) -> Result<()> {
1454        panic!("not implemented")
1455    }
1456}
1457
1458// Instruction account structures
1459#[derive(Accounts)]
1460pub struct VersionAccounts<'info> {
1461    #[account(mut, signer)]
1462    pub payer: AccountInfo<'info>,
1463}
1464
1465#[derive(Accounts)]
1466pub struct InitLogAccountAccounts<'info> {
1467    #[account(mut, signer)]
1468    pub payer: AccountInfo<'info>,
1469    #[account(mut)]
1470    pub log_account: AccountInfo<'info>,
1471    pub system_program: AccountInfo<'info>,
1472}
1473
1474#[derive(Accounts)]
1475pub struct ReceiveLogAccounts<'info> {
1476    #[account(mut, signer)]
1477    pub log_account: AccountInfo<'info>,
1478}
1479
1480#[derive(Accounts)]
1481pub struct TestLogAccounts<'info> {
1482    #[account(mut, signer)]
1483    pub payer: AccountInfo<'info>,
1484    #[account(mut)]
1485    pub log_account: AccountInfo<'info>,
1486    pub self_program: AccountInfo<'info>,
1487}
1488
1489/// Initialize a platform tenant.
1490///
1491/// Tenants are the top-level organizational units in the protocol. Each tenant can have
1492/// multiple market groups, and receives a portion of all fees generated by markets under
1493/// their umbrella.
1494///
1495/// # Arguments
1496///
1497/// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
1498/// This fee is taken from all market operations and distributed to the tenant.
1499/// * `permissionless_group_creation` - If true, anyone can create market groups under this
1500/// tenant. If false, only the tenant admin can create new groups.
1501///
1502/// # Access Control
1503///
1504/// This instruction can only be called by the program itself (root authority).
1505#[derive(Accounts)]
1506pub struct TenantInitAccounts<'info> {
1507    /// Account paying for the tenant account creation.
1508    #[account(mut, signer)]
1509    pub payer: AccountInfo<'info>,
1510    /// Root authority (the program itself) authorizing tenant creation.
1511    #[account(signer)]
1512    pub root: AccountInfo<'info>,
1513    /// Seed signer used to derive the tenant's PDA address.
1514    #[account(signer)]
1515    pub tenant_seed: AccountInfo<'info>,
1516    /// The new tenant account being initialized.
1517    #[account(mut)]
1518    pub tenant: AccountInfo<'info>,
1519    /// System program for creating the tenant account.
1520    pub system_program: AccountInfo<'info>,
1521    #[account(mut)]
1522    pub log_account: AccountInfo<'info>,
1523    pub mayflower_program: AccountInfo<'info>,
1524}
1525
1526/// Initialize a platform tenant with an admin.
1527///
1528/// This instruction is similar to `tenant_init` but allows specifying an admin
1529/// account that will have full control over the tenant.
1530///
1531/// # Arguments
1532///
1533/// * `fee_micro_bps` - Platform fee rate in micro basis points (1 micro bp = 0.0001%).
1534/// This fee is taken from all market operations and distributed to the tenant.
1535/// * `permissionless_group_creation` - If true, anyone can create market groups under this
1536/// tenant. If false, only the tenant admin can create new groups.
1537/// * `admin` - Public key of the admin account that will have full control over the tenant.
1538#[derive(Accounts)]
1539pub struct TenantInitWithAdminAccounts<'info> {
1540    /// Account paying for the tenant account creation.
1541    #[account(mut, signer)]
1542    pub payer: AccountInfo<'info>,
1543    /// Root authority (the program itself) authorizing tenant creation.
1544    #[account(signer)]
1545    pub root: AccountInfo<'info>,
1546    /// Seed signer used to derive the tenant's PDA address.
1547    #[account(signer)]
1548    pub tenant_seed: AccountInfo<'info>,
1549    /// The new tenant account being initialized.
1550    #[account(mut)]
1551    pub tenant: AccountInfo<'info>,
1552    /// System program for creating the tenant account.
1553    pub system_program: AccountInfo<'info>,
1554    #[account(mut)]
1555    pub log_account: AccountInfo<'info>,
1556    pub mayflower_program: AccountInfo<'info>,
1557}
1558
1559/// Propose a new admin for the tenant.
1560///
1561/// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
1562/// who must then accept the role using `tenant_accept_new_admin`.
1563#[derive(Accounts)]
1564pub struct TenantProposeAdminAccounts<'info> {
1565    /// Current tenant admin proposing the transfer.
1566    #[account(mut, signer)]
1567    pub admin: AccountInfo<'info>,
1568    /// Tenant account for which a new admin is being proposed.
1569    #[account(mut)]
1570    pub tenant: AccountInfo<'info>,
1571    #[account(mut)]
1572    pub log_account: AccountInfo<'info>,
1573    pub mayflower_program: AccountInfo<'info>,
1574}
1575
1576/// Accept admin ownership of a tenant.
1577///
1578/// Completes the two-step ownership transfer process. The proposed admin calls this
1579/// instruction to accept control of the tenant.
1580#[derive(Accounts)]
1581pub struct TenantAcceptNewAdminAccounts<'info> {
1582    /// The proposed admin accepting ownership of the tenant.
1583    #[account(mut, signer)]
1584    pub new_admin: AccountInfo<'info>,
1585    /// Tenant account whose ownership is being transferred.
1586    #[account(mut)]
1587    pub tenant: AccountInfo<'info>,
1588    #[account(mut)]
1589    pub log_account: AccountInfo<'info>,
1590    pub mayflower_program: AccountInfo<'info>,
1591}
1592
1593/// Change the fee rate for a tenant.
1594///
1595/// Updates the platform fee rate applied to all market operations under this tenant.
1596#[derive(Accounts)]
1597pub struct TenantChangeFeeMbpsAccounts<'info> {
1598    /// Payer of the fee.
1599    #[account(mut, signer)]
1600    pub payer: AccountInfo<'info>,
1601    /// Root authority (the program itself) authorized to change the fee
1602    #[account(signer)]
1603    pub root: AccountInfo<'info>,
1604    /// Tenant account whose platform fee is being updated.
1605    #[account(mut)]
1606    pub tenant: AccountInfo<'info>,
1607    #[account(mut)]
1608    pub log_account: AccountInfo<'info>,
1609    pub mayflower_program: AccountInfo<'info>,
1610}
1611
1612/// Initialize a market group under a tenant.
1613///
1614/// Market groups are collections of markets that share the same fee structure and admin.
1615/// Each group can contain multiple markets with different token pairs and price curves.
1616/// The group admin has control over all markets within the group and collects trading fees.
1617///
1618/// # Arguments
1619///
1620/// * `args` - Initialization arguments containing:
1621/// - `fees`: Fee structure for buy, sell, borrow, and exercise operations
1622/// - `group_admin`: Public key that will administer this market group
1623///
1624/// # Access Control
1625///
1626/// If the tenant has `permissionless_group_creation` disabled, only the tenant admin
1627/// can create new market groups.
1628#[derive(Accounts)]
1629pub struct MarketGroupInitAccounts<'info> {
1630    /// Account paying for the market group account creation.
1631    #[account(mut, signer)]
1632    pub payer: AccountInfo<'info>,
1633    /// Tenant account that will own this market group.
1634    pub tenant: AccountInfo<'info>,
1635    /// Optional account, which only needs to match if the tenant does not allow permissionless group creation
1636    /// Must be the tenant admin if permissionless creation is disabled.
1637    #[account(signer)]
1638    pub tenant_admin: AccountInfo<'info>,
1639    /// Seed signer used to derive the market group's PDA address.
1640    #[account(signer)]
1641    pub seed: AccountInfo<'info>,
1642    /// The new market group account being initialized.
1643    #[account(mut)]
1644    pub market_group: AccountInfo<'info>,
1645    /// System program for creating the market group account.
1646    pub system_program: AccountInfo<'info>,
1647    #[account(mut)]
1648    pub log_account: AccountInfo<'info>,
1649    pub mayflower_program: AccountInfo<'info>,
1650}
1651
1652/// Propose a new admin for the market group.
1653///
1654/// Initiates a two-step ownership transfer process. The current admin proposes a new admin,
1655/// who must then accept the role using `market_group_accept_new_admin`.
1656///
1657/// # Arguments
1658///
1659/// * `new_admin` - Public key of the proposed new admin
1660///
1661/// # Access Control
1662///
1663/// Only the current market group admin can propose a new admin.
1664///
1665/// # Security
1666///
1667/// Two-step transfer prevents accidental loss of admin control by requiring the new admin
1668/// to explicitly accept the role.
1669#[derive(Accounts)]
1670pub struct MarketGroupProposeAdminAccounts<'info> {
1671    /// Current market group admin proposing the transfer.
1672    #[account(mut, signer)]
1673    pub admin: AccountInfo<'info>,
1674    /// Market group account for which a new admin is being proposed.
1675    #[account(mut)]
1676    pub market_group: AccountInfo<'info>,
1677    #[account(mut)]
1678    pub log_account: AccountInfo<'info>,
1679    pub mayflower_program: AccountInfo<'info>,
1680}
1681
1682/// Accept admin ownership of a market group.
1683///
1684/// Completes the two-step ownership transfer process. The proposed admin calls this
1685/// instruction to accept control of the market group.
1686///
1687/// # Access Control
1688///
1689/// Only the proposed new admin can accept ownership.
1690///
1691/// # Effects
1692///
1693/// - Transfers full admin control to the new admin
1694/// - Clears the proposed admin field
1695/// - The new admin gains ability to:
1696/// - Create new markets in the group
1697/// - Change group fees
1698/// - Collect accumulated revenue
1699/// - Modify market permissions
1700#[derive(Accounts)]
1701pub struct MarketGroupAcceptNewAdminAccounts<'info> {
1702    /// The proposed admin accepting ownership of the market group.
1703    #[account(mut, signer)]
1704    pub new_admin: AccountInfo<'info>,
1705    /// Market group account whose ownership is being transferred.
1706    #[account(mut)]
1707    pub market_group: AccountInfo<'info>,
1708    #[account(mut)]
1709    pub log_account: AccountInfo<'info>,
1710    pub mayflower_program: AccountInfo<'info>,
1711}
1712
1713/// Initialize a linear market with a simple price curve.
1714///
1715/// Creates a new market with a linear bonding curve that determines token prices based on
1716/// supply. The curve has three segments: floor (constant price), shoulder (linear increase),
1717/// and tail (constant max price).
1718///
1719/// # Arguments
1720///
1721/// * `market_linear_args` - Configuration parameters including:
1722/// - `floor`: Minimum price per token (floor price)
1723/// - `target`: Target price where the shoulder segment ends
1724/// - `slope_numerator` / `slope_denominator`: Rate of price increase in shoulder segment
1725/// - `shoulder_start` / `shoulder_end`: Token supply range for linear price growth
1726/// - `tail_start`: Token supply where max price is reached
1727/// - `permissions`: Trading restrictions and feature flags
1728///
1729/// # Access Control
1730///
1731/// Only the market group admin can create new markets.
1732///
1733/// # Created Accounts
1734///
1735/// - Market account storing price curve and state
1736/// - Token mint for the market's synthetic token
1737/// - Option token mint for exercisable options
1738/// - Liquidity vault holding backing collateral
1739/// - Revenue escrow accounts for fee collection
1740#[derive(Accounts)]
1741pub struct MarketLinearInitAccounts<'info> {
1742    /// Account paying for the creation of new accounts and transaction fees.
1743    #[account(mut, signer)]
1744    pub payer: AccountInfo<'info>,
1745    /// Market group admin authorizing the creation of this new market.
1746    #[account(mut, signer)]
1747    pub group_admin: AccountInfo<'info>,
1748    /// Seed signer used to derive the market_meta PDA address.
1749    #[account(signer)]
1750    pub seed: AccountInfo<'info>,
1751    /// Tenant account that owns the market group.
1752    pub tenant: AccountInfo<'info>,
1753    /// Market group account that will contain this market.
1754    /// Must be owned by the tenant and administered by group_admin.
1755    pub market_group: AccountInfo<'info>,
1756    /// Mint of the main token (e.g., USDC, SOL) used as the market's base currency.
1757    pub mint_main: AccountInfo<'info>,
1758    /// The token mint for this market's derivative token.
1759    /// This account must be created in a previous instruction
1760    /// With supply set to zero
1761    /// And mint authority assigned to the market_meta
1762    pub mint_token: AccountInfo<'info>,
1763    /// Mint for option tokens that can be exercised to purchase market tokens.
1764    #[account(mut)]
1765    pub mint_options: AccountInfo<'info>,
1766    /// Liquidity vault holding the main token reserves for this market.
1767    #[account(mut)]
1768    pub liq_vault_main: AccountInfo<'info>,
1769    /// Revenue escrow account for market group admin fees.
1770    #[account(mut)]
1771    pub rev_escrow_group: AccountInfo<'info>,
1772    /// Revenue escrow account for tenant platform fees.
1773    #[account(mut)]
1774    pub rev_escrow_tenant: AccountInfo<'info>,
1775    /// The linear market account storing price curve and state data.
1776    #[account(mut)]
1777    pub market: AccountInfo<'info>,
1778    /// Market metadata account storing configuration and token references.
1779    #[account(mut)]
1780    pub market_meta: AccountInfo<'info>,
1781    /// System program for creating new accounts.
1782    pub system_program: AccountInfo<'info>,
1783    /// Token program for the market's derivative token operations.
1784    pub token_program: AccountInfo<'info>,
1785    /// Token program interface for the main token operations.
1786    pub token_program_main: AccountInfo<'info>,
1787    #[account(mut)]
1788    pub log_account: AccountInfo<'info>,
1789    pub mayflower_program: AccountInfo<'info>,
1790}
1791
1792/// Initialize a linear market with Dutch auction price boost.
1793///
1794/// Creates a linear market with an additional Dutch auction mechanism that provides
1795/// temporary price boosts. The boost decays over time from a maximum multiplier down
1796/// to 1x (no boost).
1797///
1798/// # Arguments
1799///
1800/// * `market_linear_init_with_dutch_args` - Configuration containing:
1801/// - All standard linear market parameters (floor, target, slopes, etc.)
1802/// - `dutch_numerator` / `dutch_denominator`: Maximum price boost multiplier
1803/// - `dutch_duration`: Time in seconds for boost to decay from max to 1x
1804/// - `dutch_start`: Unix timestamp when the Dutch auction begins
1805///
1806/// # Dutch Auction Mechanics
1807///
1808/// - Initial boost: price × (dutch_numerator / dutch_denominator)
1809/// - Linear decay over dutch_duration seconds
1810/// - After duration expires, boost remains at 1x (no effect)
1811/// - Useful for token launches to incentivize early buyers
1812///
1813/// # Access Control
1814///
1815/// Only the market group admin can create new markets.
1816#[derive(Accounts)]
1817pub struct MarketLinearInitWithDutchAccounts<'info> {
1818    #[account(mut, signer)]
1819    pub payer: AccountInfo<'info>,
1820    #[account(mut, signer)]
1821    pub group_admin: AccountInfo<'info>,
1822    #[account(signer)]
1823    pub seed: AccountInfo<'info>,
1824    pub tenant: AccountInfo<'info>,
1825    pub market_group: AccountInfo<'info>,
1826    pub mint_main: AccountInfo<'info>,
1827    /// The token account for the market
1828    /// This account must be created in a previous instruction
1829    /// With supply set to zero
1830    /// And mint authority assigned to the market_meta
1831    pub mint_token: AccountInfo<'info>,
1832    #[account(mut)]
1833    pub mint_options: AccountInfo<'info>,
1834    #[account(mut)]
1835    pub liq_vault_main: AccountInfo<'info>,
1836    #[account(mut)]
1837    pub rev_escrow_group: AccountInfo<'info>,
1838    #[account(mut)]
1839    pub rev_escrow_tenant: AccountInfo<'info>,
1840    #[account(mut)]
1841    pub market: AccountInfo<'info>,
1842    #[account(mut)]
1843    pub market_meta: AccountInfo<'info>,
1844    pub system_program: AccountInfo<'info>,
1845    pub token_program: AccountInfo<'info>,
1846    pub token_program_main: AccountInfo<'info>,
1847    #[account(mut)]
1848    pub log_account: AccountInfo<'info>,
1849    pub mayflower_program: AccountInfo<'info>,
1850}
1851
1852/// Initialize a linear market with Dutch auction and token unit scaling.
1853///
1854/// This instruction extends `market_linear_init_with_dutch` with support for
1855/// token unit scaling. The `token_unit_scale` parameter controls how token
1856/// units map to curve units via the factor `2^token_unit_scale`:
1857///
1858/// - `scale=0`: 1 token = 1 curve unit (no scaling, default behavior)
1859/// - `scale=3`: 8 tokens = 1 curve unit (for high-decimal tokens)
1860/// - `scale=-2`: 1 token = 4 curve units (for low-decimal tokens)
1861///
1862/// # Use Cases
1863///
1864/// - High-decimal tokens (e.g., 9 decimals): Use positive scale to reduce
1865/// the effective supply range the curve operates over
1866/// - Low-decimal tokens: Use negative scale to expand the curve's range
1867///
1868/// # Access Control
1869///
1870/// Only the market group admin can create new markets.
1871#[derive(Accounts)]
1872pub struct MarketSimpleInitV2Accounts<'info> {
1873    #[account(mut, signer)]
1874    pub payer: AccountInfo<'info>,
1875    #[account(mut, signer)]
1876    pub group_admin: AccountInfo<'info>,
1877    #[account(signer)]
1878    pub seed: AccountInfo<'info>,
1879    pub tenant: AccountInfo<'info>,
1880    pub market_group: AccountInfo<'info>,
1881    pub mint_main: AccountInfo<'info>,
1882    /// The token account for the market
1883    /// This account must be created in a previous instruction
1884    /// With supply set to zero
1885    /// And mint authority assigned to the market_meta
1886    pub mint_token: AccountInfo<'info>,
1887    #[account(mut)]
1888    pub mint_options: AccountInfo<'info>,
1889    #[account(mut)]
1890    pub liq_vault_main: AccountInfo<'info>,
1891    #[account(mut)]
1892    pub rev_escrow_group: AccountInfo<'info>,
1893    #[account(mut)]
1894    pub rev_escrow_tenant: AccountInfo<'info>,
1895    #[account(mut)]
1896    pub market: AccountInfo<'info>,
1897    #[account(mut)]
1898    pub market_meta: AccountInfo<'info>,
1899    pub system_program: AccountInfo<'info>,
1900    pub token_program: AccountInfo<'info>,
1901    pub token_program_main: AccountInfo<'info>,
1902    #[account(mut)]
1903    pub log_account: AccountInfo<'info>,
1904    pub mayflower_program: AccountInfo<'info>,
1905}
1906
1907/// Mint option tokens by depositing market tokens.
1908///
1909/// Converts market tokens into option tokens at a 1:1 ratio. Option tokens represent
1910/// the right to purchase market tokens at the floor price by depositing the main
1911/// backing token (e.g., USDC).
1912///
1913/// # Arguments
1914///
1915/// * `amount` - Number of market tokens to convert into options
1916///
1917/// # Requirements
1918///
1919/// - User must have sufficient market token balance
1920/// - Market must allow option minting (check permissions)
1921///
1922/// # Use Cases
1923///
1924/// - Hedge against price increases by locking in floor price
1925/// - Create structured products with downside protection
1926/// - Enable secondary markets for price speculation
1927#[derive(Accounts)]
1928pub struct MintOptionsAccounts<'info> {
1929    /// Market group admin authorized to mint options.
1930    #[account(mut, signer)]
1931    pub admin: AccountInfo<'info>,
1932    /// Market metadata linking to the options mint.
1933    pub market_meta: AccountInfo<'info>,
1934    /// Market group that must be administered by the signer.
1935    pub market_group: AccountInfo<'info>,
1936    /// Mint for option tokens to be created.
1937    #[account(mut)]
1938    pub mint_options: AccountInfo<'info>,
1939    /// Destination token account to receive minted options.
1940    #[account(mut)]
1941    pub options_dst: AccountInfo<'info>,
1942    /// Token program for minting option tokens.
1943    pub token_program: AccountInfo<'info>,
1944    #[account(mut)]
1945    pub log_account: AccountInfo<'info>,
1946    pub mayflower_program: AccountInfo<'info>,
1947}
1948
1949/// Collect accumulated trading fees from a market group.
1950///
1951/// Transfers fee revenue from the group's escrow account to the admin's wallet.
1952/// Fees accumulate from all trading operations (buy, sell, borrow, exercise) across
1953/// all markets in the group.
1954///
1955/// # Arguments
1956///
1957/// * `amount` - Amount to collect:
1958/// - `FullOrPartialU64::Full`: Collect entire escrow balance
1959/// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
1960///
1961/// # Access Control
1962///
1963/// Only the market group admin can collect revenue.
1964///
1965/// # Fee Distribution
1966///
1967/// Trading fees are split between:
1968/// - Tenant: Platform-level fee (set during tenant creation)
1969/// - Market Group: Admin fee (set during group creation)
1970///
1971/// This instruction collects only the group's portion.
1972#[derive(Accounts)]
1973pub struct MarketGroupCollectRevAccounts<'info> {
1974    /// Market group admin authorized to collect revenue.
1975    #[account(mut, signer)]
1976    pub group_admin: AccountInfo<'info>,
1977    /// Market group that has accumulated revenue.
1978    pub market_group: AccountInfo<'info>,
1979    /// Market metadata linking to the revenue escrow account.
1980    pub market_meta: AccountInfo<'info>,
1981    /// Mint of the main token for revenue collection.
1982    pub mint_main: AccountInfo<'info>,
1983    /// Revenue escrow account holding accumulated fees for the market group.
1984    #[account(mut)]
1985    pub rev_escrow_group: AccountInfo<'info>,
1986    /// Destination token account to receive collected revenue.
1987    #[account(mut)]
1988    pub rev_dst: AccountInfo<'info>,
1989    /// Token program for transferring the revenue.
1990    pub token_program_main: AccountInfo<'info>,
1991    #[account(mut)]
1992    pub log_account: AccountInfo<'info>,
1993    pub mayflower_program: AccountInfo<'info>,
1994}
1995
1996/// Collect accumulated platform fees from a tenant.
1997///
1998/// Transfers platform fee revenue from the tenant's escrow account to the admin's wallet.
1999/// Platform fees accumulate from all trading operations (buy, sell, borrow, exercise) across
2000/// all markets under this tenant.
2001///
2002/// # Arguments
2003///
2004/// * `amount` - Amount to collect:
2005/// - `FullOrPartialU64::Full`: Collect entire escrow balance
2006/// - `FullOrPartialU64::Partial(n)`: Collect specific amount `n`
2007///
2008/// # Access Control
2009///
2010/// Only the tenant admin can collect platform revenue.
2011///
2012/// # Fee Distribution
2013///
2014/// Trading fees are split between:
2015/// - Tenant: Platform-level fee (set during tenant creation)
2016/// - Market Group: Admin fee (set during group creation)
2017///
2018/// This instruction collects only the tenant's platform fee portion.
2019#[derive(Accounts)]
2020pub struct TenantCollectRevAccounts<'info> {
2021    /// Root authority (the program itself) authorized to collect platform revenue.
2022    #[account(mut, signer)]
2023    pub root: AccountInfo<'info>,
2024    /// Market metadata linking to the revenue escrow account.
2025    pub market_meta: AccountInfo<'info>,
2026    /// Mint of the main token for revenue collection.
2027    pub mint_main: AccountInfo<'info>,
2028    /// Revenue escrow account holding accumulated platform fees for the tenant.
2029    #[account(mut)]
2030    pub rev_escrow_tenant: AccountInfo<'info>,
2031    /// Destination token account to receive collected platform revenue.
2032    #[account(mut)]
2033    pub rev_dst: AccountInfo<'info>,
2034    /// Token program for transferring the revenue.
2035    pub token_program_main: AccountInfo<'info>,
2036    #[account(mut)]
2037    pub log_account: AccountInfo<'info>,
2038    pub mayflower_program: AccountInfo<'info>,
2039}
2040
2041/// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
2042///
2043/// Raise the market floor price while preserving bonding curve area.
2044///
2045/// Increases the minimum (floor) price of the market token while maintaining the
2046/// total area under the price curve. This ensures the market's total value capacity
2047/// remains constant while providing price support.
2048///
2049/// # Arguments
2050///
2051/// * `new_floor` - New minimum price per token (must be higher than current)
2052/// * `new_shoulder_end` - New token supply where shoulder segment ends
2053///
2054/// # Curve Adjustment
2055///
2056/// When the floor rises:
2057/// - Floor segment moves up to new price level
2058/// - Shoulder segment becomes steeper to preserve area
2059/// - Tail segment adjusts to maintain continuity
2060///
2061/// # Requirements
2062///
2063/// - Market must have excess liquidity to support higher floor
2064/// - New floor must be greater than current floor
2065/// - Curve area preservation must be mathematically valid
2066///
2067/// # Access Control
2068///
2069/// Can be triggered by authorized operators or through automated mechanisms.
2070#[derive(Accounts)]
2071pub struct RaiseFloorPreserveAreaAccounts<'info> {
2072    /// Market group admin authorized to adjust floor parameters.
2073    #[account(mut, signer)]
2074    pub admin: AccountInfo<'info>,
2075    /// Market group that must be administered by the signer.
2076    pub market_group: AccountInfo<'info>,
2077    /// Market metadata linking to the market group.
2078    pub market_meta: AccountInfo<'info>,
2079    /// Linear market account whose floor price will be raised.
2080    #[account(mut)]
2081    pub market: AccountInfo<'info>,
2082    #[account(mut)]
2083    pub log_account: AccountInfo<'info>,
2084    pub mayflower_program: AccountInfo<'info>,
2085}
2086
2087/// DEPRECATED: use raise_floor_preserve_area_checked2 instead, as it is more secure
2088///
2089/// Raise the floor price with additional validation checks.
2090///
2091/// Similar to `raise_floor_preserve_area` but includes extra safety checks to ensure
2092/// the operation maintains market integrity. Validates curve parameters and liquidity
2093/// requirements before applying changes.
2094///
2095/// # Arguments
2096///
2097/// * `args` - Parameters including:
2098/// - `new_floor`: Target floor price
2099/// - `new_shoulder_end`: Adjusted shoulder endpoint
2100/// - `max_deviation_bps`: Maximum allowed deviation in basis points
2101///
2102/// # Additional Checks
2103///
2104/// - Verifies sufficient backing liquidity exists
2105/// - Ensures curve area preservation within tolerance
2106/// - Validates no tokens would be instantly profitable to redeem
2107/// - Checks market state consistency after adjustment
2108///
2109/// # Use Cases
2110///
2111/// - Automated floor raising based on market conditions
2112/// - Protocol-driven price support mechanisms
2113/// - Treasury management operations
2114#[derive(Accounts)]
2115pub struct RaiseFloorPreserveAreaCheckedAccounts<'info> {
2116    #[account(mut, signer)]
2117    pub admin: AccountInfo<'info>,
2118    pub market_group: AccountInfo<'info>,
2119    pub market_meta: AccountInfo<'info>,
2120    #[account(mut)]
2121    pub market: AccountInfo<'info>,
2122    #[account(mut)]
2123    pub log_account: AccountInfo<'info>,
2124    pub mayflower_program: AccountInfo<'info>,
2125}
2126
2127/// Raise the floor and preserve the area of the market
2128/// This instruction takes in constraints
2129/// * `new_floor` - The new floor price (must be greater than the current floor)
2130/// * `new_shoulder_end` - The new shoulder end (must be greater than the current shoulder end)
2131/// * `min_liq_ratio` - The minimum liquidity ratio (greater than or equal to 0.0)
2132/// * `max_area_shrinkage_tolerance_units` - The maximum token units that the total area of the curve is allowed to shrink by
2133/// This is set by the client to restrict overly aggressive floor raising, with a tolerance to account for "slippage"
2134///
2135/// # Access Control
2136/// Only the market group admin can raise the floor price.
2137#[derive(Accounts)]
2138pub struct RaiseFloorPreserveAreaChecked2Accounts<'info> {
2139    #[account(mut, signer)]
2140    pub admin: AccountInfo<'info>,
2141    pub market_group: AccountInfo<'info>,
2142    pub market_meta: AccountInfo<'info>,
2143    #[account(mut)]
2144    pub market: AccountInfo<'info>,
2145    #[account(mut)]
2146    pub log_account: AccountInfo<'info>,
2147    pub mayflower_program: AccountInfo<'info>,
2148}
2149
2150/// DEPRECATED: use raise_floor_from_excess_liquidity2 instead, as it is more secure
2151///
2152/// Raise the floor price using excess market liquidity.
2153///
2154/// Automatically increases the floor price when the market has accumulated excess
2155/// backing liquidity beyond what's needed for the current token supply. This provides
2156/// organic price appreciation based on market performance.
2157///
2158/// # Arguments
2159///
2160/// * `floor_increase_ratio` - Percentage increase for the floor price (as decimal)
2161/// - 0.1 = 10% increase
2162/// - 0.05 = 5% increase
2163/// - Must be positive and reasonable (typically < 0.5)
2164///
2165/// # Mechanism
2166///
2167/// 1. Calculates available excess liquidity (cash above backing requirements)
2168/// 2. Determines maximum sustainable floor increase
2169/// 3. Applies requested ratio (capped by available excess)
2170/// 4. Adjusts curve parameters to preserve total area
2171///
2172/// # Requirements
2173///
2174/// - Market must have excess liquidity
2175/// - Floor increase must be sustainable given current token supply
2176/// - Market permissions must allow floor raising
2177///
2178/// # Benefits
2179///
2180/// - Rewards token holders when market performs well
2181/// - Creates deflationary pressure through higher floor
2182/// - Maintains full backing at new price levels
2183#[derive(Accounts)]
2184pub struct RaiseFloorFromExcessLiquidityAccounts<'info> {
2185    #[account(mut, signer)]
2186    pub admin: AccountInfo<'info>,
2187    pub market_group: AccountInfo<'info>,
2188    pub market_meta: AccountInfo<'info>,
2189    #[account(mut)]
2190    pub market: AccountInfo<'info>,
2191    #[account(mut)]
2192    pub log_account: AccountInfo<'info>,
2193    pub mayflower_program: AccountInfo<'info>,
2194}
2195
2196/// Raise the floor price using excess market liquidity.
2197///
2198/// Automatically increases the floor price when the market has accumulated excess
2199/// backing liquidity beyond what's needed for the current token supply. This provides
2200/// organic price appreciation based on market performance.
2201///
2202/// # Arguments
2203///
2204/// * `args` - Parameters including:
2205/// - `max_new_floor`: The maximum new floor that is allowed
2206/// - `increase_ratio_micro_basis_points`: The amount to increase the floor by, in micro basis points
2207///
2208/// # Access Control
2209///
2210/// Only the market group admin can raise the floor price.
2211///
2212/// # Use Cases
2213/// - Automated floor raising based on market conditions
2214/// - Protocol-driven price support mechanisms
2215/// - Treasury management operations
2216#[derive(Accounts)]
2217pub struct RaiseFloorFromExcessLiquidityCheckedAccounts<'info> {
2218    #[account(mut, signer)]
2219    pub admin: AccountInfo<'info>,
2220    pub market_group: AccountInfo<'info>,
2221    pub market_meta: AccountInfo<'info>,
2222    #[account(mut)]
2223    pub market: AccountInfo<'info>,
2224    #[account(mut)]
2225    pub log_account: AccountInfo<'info>,
2226    pub mayflower_program: AccountInfo<'info>,
2227}
2228
2229/// Update market permissions and feature flags.
2230///
2231/// Controls which operations are allowed on a market. Can be used to pause trading,
2232/// disable specific features, or adjust market behavior.
2233///
2234/// # Arguments
2235///
2236/// * `new_flags` - New permission set including:
2237/// - `can_buy`: Allow token purchases
2238/// - `can_sell`: Allow token sales
2239/// - `can_borrow`: Allow borrowing against collateral
2240/// - `can_add_liquidity`: Allow liquidity donations
2241/// - `can_remove_liquidity`: Allow liquidity removal
2242/// - `can_open_position`: Allow new position creation
2243/// - `can_close_position`: Allow position closure
2244/// - `can_change_fees`: Allow fee adjustments
2245///
2246/// # Access Control
2247///
2248/// Only the market group admin can change market flags.
2249///
2250/// # Use Cases
2251///
2252/// - Emergency pause during security incidents
2253/// - Gradual feature rollout
2254/// - Market maintenance windows
2255/// - Compliance-driven restrictions
2256#[derive(Accounts)]
2257pub struct MarketFlagsChangeAccounts<'info> {
2258    /// Market group admin authorized to change market permissions.
2259    #[account(mut, signer)]
2260    pub admin: AccountInfo<'info>,
2261    /// Market group that must be administered by the signer.
2262    pub market_group: AccountInfo<'info>,
2263    /// Market metadata whose permissions will be updated.
2264    #[account(mut)]
2265    pub market_meta: AccountInfo<'info>,
2266    #[account(mut)]
2267    pub log_account: AccountInfo<'info>,
2268    pub mayflower_program: AccountInfo<'info>,
2269}
2270
2271/// Update fee structure for all markets in a group.
2272///
2273/// Changes the fee rates charged on trading operations. New fees apply to all future
2274/// transactions across all markets within the group.
2275///
2276/// # Arguments
2277///
2278/// * `new_fees` - Updated fee structure:
2279/// - `buy`: Fee on token purchases (micro basis points)
2280/// - `sell`: Fee on token sales (micro basis points)
2281/// - `borrow`: Fee on borrowing operations (micro basis points)
2282/// - `exercise`: Fee on option exercise (micro basis points)
2283///
2284/// # Fee Calculation
2285///
2286/// Fees are specified in micro basis points where:
2287/// - 1 micro bp = 1/100 of a basis point = 0.0001%
2288/// - 100 micro bps = 1 basis point = 0.01%
2289/// - 10,000 micro bps = 100 basis points = 1%
2290/// - Example: 50 micro bps = 0.5 basis points = 0.005% fee
2291///
2292/// # Access Control
2293///
2294/// Only the market group admin can change fees.
2295///
2296/// # Considerations
2297///
2298/// - Changes affect all markets in the group immediately
2299/// - Cannot exceed maximum fee limits set by protocol
2300/// - Platform (tenant) fees are added on top of group fees
2301#[derive(Accounts)]
2302pub struct MarketGroupChangeFeesAccounts<'info> {
2303    /// Market group admin authorized to change fees.
2304    #[account(mut, signer)]
2305    pub admin: AccountInfo<'info>,
2306    /// Market group account whose fees will be updated.
2307    #[account(mut)]
2308    pub market_group: AccountInfo<'info>,
2309    #[account(mut)]
2310    pub log_account: AccountInfo<'info>,
2311    pub mayflower_program: AccountInfo<'info>,
2312}
2313
2314/// Initialize a personal position account for market interaction.
2315///
2316/// Creates a user-specific account that tracks collateral deposits and debt obligations
2317/// for a particular market. Required before performing borrow operations or using
2318/// collateral-based features.
2319///
2320/// # Position Features
2321///
2322/// Personal positions enable:
2323/// - Collateral deposits (market tokens as collateral)
2324/// - Borrowing against collateral (up to LTV limits)
2325/// - Tracking debt obligations and interest
2326/// - Liquidation protection through collateralization
2327///
2328/// # Account Structure
2329///
2330/// - Unique per user per market
2331/// - Stores collateral and debt balances
2332/// - Tracks last update timestamp for interest
2333/// - Immutable market and owner references
2334///
2335/// # One-Time Setup
2336///
2337/// Each user needs only one position per market. Attempting to create a duplicate
2338/// will fail. The position persists until explicitly closed.
2339#[derive(Accounts)]
2340pub struct PersonalPositionInitAccounts<'info> {
2341    /// Account paying for the personal position and escrow account creation.
2342    #[account(mut, signer)]
2343    pub payer: AccountInfo<'info>,
2344    /// The owner who will control the personal position.
2345    pub owner: AccountInfo<'info>,
2346    /// Market metadata identifying which market this position belongs to.
2347    pub market_meta: AccountInfo<'info>,
2348    /// Mint for the market tokens that can be deposited as collateral.
2349    pub mint_token: AccountInfo<'info>,
2350    /// The new personal position account being initialized.
2351    #[account(mut)]
2352    pub personal_position: AccountInfo<'info>,
2353    /// Escrow token account for holding collateral tokens.
2354    #[account(mut)]
2355    pub escrow: AccountInfo<'info>,
2356    /// Token program for creating the escrow account.
2357    pub token_program: AccountInfo<'info>,
2358    /// System program for creating new accounts.
2359    pub system_program: AccountInfo<'info>,
2360    #[account(mut)]
2361    pub log_account: AccountInfo<'info>,
2362    pub mayflower_program: AccountInfo<'info>,
2363}
2364
2365/// DEPRECATED: use donate_liquidity2 instead, as v2 gets logged by the indexer
2366///
2367/// Donate backing liquidity to the market.
2368///
2369/// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
2370/// market tokens in return. This creates excess liquidity that can be used to raise
2371/// the floor price or improve market stability.
2372///
2373/// # Arguments
2374///
2375/// * `amount` - Amount of main tokens to donate
2376///
2377/// # Effects
2378///
2379/// - Increases market's cash balance
2380/// - Creates excess liquidity (cash > backing requirements)
2381/// - Enables floor price increases
2382/// - Benefits all token holders through improved backing
2383///
2384/// # Use Cases
2385///
2386/// - Protocol treasury supporting market stability
2387/// - Community-funded price support
2388/// - Grants or subsidies to bootstrap markets
2389/// - Creating buffer for market operations
2390///
2391/// # Note
2392///
2393/// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
2394#[derive(Accounts)]
2395pub struct DonateLiquidityAccounts<'info> {
2396    /// Donor of the liquidity
2397    /// Account providing main tokens to boost market liquidity.
2398    #[account(mut, signer)]
2399    pub payer: AccountInfo<'info>,
2400    /// Market metadata with all market configuration and references.
2401    pub market_meta: AccountInfo<'info>,
2402    /// Linear market account to update cash balance.
2403    #[account(mut)]
2404    pub market: AccountInfo<'info>,
2405    /// Source account containing main tokens to donate.
2406    #[account(mut)]
2407    pub main_src: AccountInfo<'info>,
2408    /// The liquidity vault for the main token in the market
2409    /// Receives the donated tokens to increase market reserves.
2410    #[account(mut)]
2411    pub liq_vault_main: AccountInfo<'info>,
2412    /// Mint for the main token being donated.
2413    pub mint_main: AccountInfo<'info>,
2414    /// Token program for the main token.
2415    pub token_program_main: AccountInfo<'info>,
2416}
2417
2418/// Donate backing liquidity to the market.
2419///
2420/// Adds main tokens (e.g., USDC) to the market's liquidity vault without receiving
2421/// market tokens in return. This creates excess liquidity that can be used to raise
2422/// the floor price or improve market stability.
2423///
2424/// # Arguments
2425///
2426/// * `amount` - Amount of main tokens to donate
2427///
2428/// # Effects
2429///
2430/// - Increases market's cash balance
2431/// - Creates excess liquidity (cash > backing requirements)
2432/// - Enables floor price increases
2433/// - Benefits all token holders through improved backing
2434///
2435/// # Use Cases
2436///
2437/// - Protocol treasury supporting market stability
2438/// - Community-funded price support
2439/// - Grants or subsidies to bootstrap markets
2440/// - Creating buffer for market operations
2441///
2442/// # Note
2443///
2444/// Donations are irreversible. Donors receive no tokens or claims on the liquidity.
2445#[derive(Accounts)]
2446pub struct DonateLiquidity2Accounts<'info> {
2447    /// Donor of the liquidity
2448    /// Account providing main tokens to boost market liquidity.
2449    #[account(mut, signer)]
2450    pub payer: AccountInfo<'info>,
2451    /// Market metadata with all market configuration and references.
2452    pub market_meta: AccountInfo<'info>,
2453    /// Linear market account to update cash balance.
2454    #[account(mut)]
2455    pub market: AccountInfo<'info>,
2456    /// Source account containing main tokens to donate.
2457    #[account(mut)]
2458    pub main_src: AccountInfo<'info>,
2459    /// The liquidity vault for the main token in the market
2460    /// Receives the donated tokens to increase market reserves.
2461    #[account(mut)]
2462    pub liq_vault_main: AccountInfo<'info>,
2463    /// Mint for the main token being donated.
2464    pub mint_main: AccountInfo<'info>,
2465    /// Token program for the main token.
2466    pub token_program_main: AccountInfo<'info>,
2467    #[account(mut)]
2468    pub log_account: AccountInfo<'info>,
2469    pub mayflower_program: AccountInfo<'info>,
2470}
2471
2472/// Buy market tokens using exact amount of main tokens.
2473///
2474/// Purchases market tokens by depositing a specific amount of main tokens (e.g., USDC).
2475/// The number of tokens received depends on the current price curve position. Includes
2476/// slippage protection through minimum output requirement.
2477///
2478/// # Arguments
2479///
2480/// * `cash_in` - Exact amount of main tokens to spend
2481/// * `min_token_out` - Minimum market tokens to receive (reverts if not met)
2482///
2483/// # Price Calculation
2484///
2485/// Token price follows the bonding curve:
2486/// - Floor segment: Constant price at floor level
2487/// - Shoulder segment: Linear price increase
2488/// - Tail segment: Constant price at maximum
2489/// - Dutch boost: Temporary multiplier if active
2490///
2491/// # Fees
2492///
2493/// Buy fee is deducted from input amount:
2494/// - Platform fee (tenant level)
2495/// - Group fee (market group level)
2496/// - Net amount used for token purchase
2497///
2498/// # Slippage Protection
2499///
2500/// Transaction reverts if `tokens_received < min_token_out`
2501#[derive(Accounts)]
2502pub struct BuyWithExactCashInAccounts<'info> {
2503    /// The trader buying tokens from the market.
2504    #[account(mut, signer)]
2505    pub signer: AccountInfo<'info>,
2506    /// Tenant account for platform fee distribution.
2507    pub tenant: AccountInfo<'info>,
2508    /// Market group containing fee configuration.
2509    pub market_group: AccountInfo<'info>,
2510    /// Market metadata with all market configuration and references.
2511    pub market_meta: AccountInfo<'info>,
2512    /// Linear market account containing price curve and state.
2513    #[account(mut)]
2514    pub market: AccountInfo<'info>,
2515    /// Mint for the market's derivative token.
2516    #[account(mut)]
2517    pub mint_token: AccountInfo<'info>,
2518    /// Mint for the main token used as payment.
2519    pub mint_main: AccountInfo<'info>,
2520    /// Destination token account to receive the purchased market tokens.
2521    #[account(mut)]
2522    pub token_dst: AccountInfo<'info>,
2523    /// Source account containing main tokens for payment.
2524    #[account(mut)]
2525    pub main_src: AccountInfo<'info>,
2526    /// Market's liquidity vault receiving the main token payment.
2527    #[account(mut)]
2528    pub liq_vault_main: AccountInfo<'info>,
2529    /// Revenue escrow for market group admin fees.
2530    #[account(mut)]
2531    pub rev_escrow_group: AccountInfo<'info>,
2532    /// Revenue escrow for tenant platform fees.
2533    #[account(mut)]
2534    pub rev_escrow_tenant: AccountInfo<'info>,
2535    /// Token program for the market's derivative token.
2536    pub token_program: AccountInfo<'info>,
2537    /// Token program for the main token.
2538    pub token_program_main: AccountInfo<'info>,
2539    #[account(mut)]
2540    pub log_account: AccountInfo<'info>,
2541    pub mayflower_program: AccountInfo<'info>,
2542}
2543
2544/// Buy market tokens and immediately deposit as collateral.
2545///
2546/// Combines token purchase with collateral deposit in a single atomic transaction.
2547/// Useful for users who want to immediately use purchased tokens as collateral for
2548/// borrowing operations.
2549///
2550/// # Arguments
2551///
2552/// * `cash_in` - Exact amount of main tokens to spend
2553/// * `min_token_out` - Minimum market tokens to receive
2554///
2555/// # Transaction Flow
2556///
2557/// 1. Deduct fees from input amount
2558/// 2. Purchase tokens at current curve price
2559/// 3. Deposit all tokens into personal position
2560/// 4. Update position's collateral balance
2561///
2562/// # Requirements
2563///
2564/// - Personal position must exist (call `personal_position_init` first)
2565/// - Sufficient main token balance
2566/// - Market must allow buying and deposits
2567///
2568/// # Benefits
2569///
2570/// - Single transaction reduces costs
2571/// - Atomic operation prevents MEV
2572/// - Immediate collateral availability
2573#[derive(Accounts)]
2574pub struct BuyWithExactCashInAndDepositAccounts<'info> {
2575    /// The trader buying tokens and depositing them as collateral.
2576    #[account(mut, signer)]
2577    pub owner: AccountInfo<'info>,
2578    /// Tenant account for platform fee collection.
2579    pub tenant: AccountInfo<'info>,
2580    /// Market group that owns this market.
2581    pub market_group: AccountInfo<'info>,
2582    /// Market metadata containing configuration and linked accounts.
2583    pub market_meta: AccountInfo<'info>,
2584    /// Linear market account with price curve and state.
2585    #[account(mut)]
2586    pub market: AccountInfo<'info>,
2587    /// Personal position that will receive the purchased tokens as collateral.
2588    #[account(mut)]
2589    pub personal_position: AccountInfo<'info>,
2590    /// Escrow account that will receive the purchased tokens as collateral.
2591    #[account(mut)]
2592    pub escrow: AccountInfo<'info>,
2593    /// Mint for the market's derivative token being purchased.
2594    #[account(mut)]
2595    pub mint_token: AccountInfo<'info>,
2596    /// Mint for the main token used as payment.
2597    pub mint_main: AccountInfo<'info>,
2598    /// Temporary destination for purchased tokens before deposit to escrow.
2599    #[account(mut)]
2600    pub token_dst: AccountInfo<'info>,
2601    /// Source account containing main tokens for payment.
2602    #[account(mut)]
2603    pub main_src: AccountInfo<'info>,
2604    /// Liquidity vault receiving the main token payment.
2605    #[account(mut)]
2606    pub liq_vault_main: AccountInfo<'info>,
2607    /// Revenue escrow for market group admin fees.
2608    #[account(mut)]
2609    pub rev_escrow_group: AccountInfo<'info>,
2610    /// Revenue escrow for tenant platform fees.
2611    #[account(mut)]
2612    pub rev_escrow_tenant: AccountInfo<'info>,
2613    /// Token program for the market's derivative token.
2614    pub token_program: AccountInfo<'info>,
2615    /// Token program for the main token.
2616    pub token_program_main: AccountInfo<'info>,
2617    #[account(mut)]
2618    pub log_account: AccountInfo<'info>,
2619    pub mayflower_program: AccountInfo<'info>,
2620}
2621
2622/// Buy market tokens and immediately deposit as collateral with debt.
2623///
2624/// Combines token purchase with collateral deposit in a single atomic transaction.
2625/// Useful for users who want to immediately use purchased tokens as collateral for
2626/// borrowing operations.
2627///
2628/// # Arguments
2629///
2630/// * `args` - Arguments for the transaction
2631/// - `exact_cash_in` - Exact amount of cash to spend on tokens
2632/// - `min_token_received` - Minimum acceptable tokens to receive (slippage protection)
2633/// - `new_acquired_debt` - New debt amount to take on
2634#[derive(Accounts)]
2635pub struct BuyWithExactCashInAndDepositWithDebtAccounts<'info> {
2636    /// The trader buying tokens and depositing them as collateral.
2637    #[account(mut, signer)]
2638    pub owner: AccountInfo<'info>,
2639    /// Tenant account for platform fee collection.
2640    pub tenant: AccountInfo<'info>,
2641    /// Market group that owns this market.
2642    pub market_group: AccountInfo<'info>,
2643    /// Market metadata containing configuration and linked accounts.
2644    pub market_meta: AccountInfo<'info>,
2645    /// Linear market account with price curve and state.
2646    #[account(mut)]
2647    pub market: AccountInfo<'info>,
2648    /// Personal position that will receive the purchased tokens as collateral.
2649    #[account(mut)]
2650    pub personal_position: AccountInfo<'info>,
2651    /// Escrow account that will receive the purchased tokens as collateral.
2652    #[account(mut)]
2653    pub escrow: AccountInfo<'info>,
2654    /// Mint for the market's derivative token being purchased.
2655    #[account(mut)]
2656    pub mint_token: AccountInfo<'info>,
2657    /// Mint for the main token used as payment.
2658    pub mint_main: AccountInfo<'info>,
2659    /// Source account containing main tokens for payment.
2660    #[account(mut)]
2661    pub main_src: AccountInfo<'info>,
2662    /// Liquidity vault receiving the main token payment.
2663    #[account(mut)]
2664    pub liq_vault_main: AccountInfo<'info>,
2665    /// Revenue escrow for market group admin fees.
2666    #[account(mut)]
2667    pub rev_escrow_group: AccountInfo<'info>,
2668    /// Revenue escrow for tenant platform fees.
2669    #[account(mut)]
2670    pub rev_escrow_tenant: AccountInfo<'info>,
2671    /// Token program for the market's derivative token.
2672    pub token_program: AccountInfo<'info>,
2673    /// Token program for the main token.
2674    pub token_program_main: AccountInfo<'info>,
2675    #[account(mut)]
2676    pub log_account: AccountInfo<'info>,
2677    pub mayflower_program: AccountInfo<'info>,
2678}
2679
2680/// Sell exact amount of market tokens for main tokens.
2681///
2682/// Sells a specific number of market tokens and receives main tokens (e.g., USDC)
2683/// based on the current bonding curve price. Includes slippage protection through
2684/// minimum output requirement.
2685///
2686/// # Arguments
2687///
2688/// * `amount_in` - Exact number of market tokens to sell
2689/// * `cash_out_min` - Minimum main tokens to receive (reverts if not met)
2690///
2691/// # Price Calculation
2692///
2693/// Sell price follows bonding curve in reverse:
2694/// - Reduces token supply, moving down the curve
2695/// - Higher supplies sell at higher prices first
2696/// - Cannot sell below floor price
2697///
2698/// # Fees
2699///
2700/// Sell fee is deducted from output amount:
2701/// - Gross proceeds calculated from curve
2702/// - Platform and group fees deducted
2703/// - Net amount sent to seller
2704///
2705/// # Market Impact
2706///
2707/// Large sells may experience price slippage as they move down the curve.
2708/// Consider breaking into smaller transactions for better execution.
2709#[derive(Accounts)]
2710pub struct SellWithExactTokenInAccounts<'info> {
2711    /// The trader selling tokens back to the market.
2712    #[account(mut, signer)]
2713    pub user: AccountInfo<'info>,
2714    /// Tenant account for platform fee distribution.
2715    pub tenant: AccountInfo<'info>,
2716    /// Market group containing fee configuration.
2717    pub market_group: AccountInfo<'info>,
2718    /// Market metadata with all market configuration and references.
2719    pub market_meta: AccountInfo<'info>,
2720    /// Linear market account containing price curve and state.
2721    #[account(mut)]
2722    pub market: AccountInfo<'info>,
2723    /// Revenue escrow for market group admin fees.
2724    #[account(mut)]
2725    pub rev_escrow_group: AccountInfo<'info>,
2726    /// Revenue escrow for tenant platform fees.
2727    #[account(mut)]
2728    pub rev_escrow_tenant: AccountInfo<'info>,
2729    /// Market's liquidity vault providing main tokens for the sale.
2730    #[account(mut)]
2731    pub liq_vault_main: AccountInfo<'info>,
2732    /// Mint for the market's derivative token being sold.
2733    #[account(mut)]
2734    pub mint_token: AccountInfo<'info>,
2735    /// Mint for the main token received from the sale.
2736    pub mint_main: AccountInfo<'info>,
2737    /// Destination account to receive main tokens from the sale.
2738    #[account(mut)]
2739    pub main_dst: AccountInfo<'info>,
2740    /// Source account containing market tokens to sell.
2741    #[account(mut)]
2742    pub token_src: AccountInfo<'info>,
2743    /// Token program for the main token.
2744    pub token_program_main: AccountInfo<'info>,
2745    /// Token program for the market's derivative token.
2746    pub token_program: AccountInfo<'info>,
2747    #[account(mut)]
2748    pub log_account: AccountInfo<'info>,
2749    pub mayflower_program: AccountInfo<'info>,
2750}
2751
2752/// Withdraw collateral and sell tokens in one transaction.
2753///
2754/// Atomically withdraws market tokens from a personal position and sells them for
2755/// main tokens. Useful for exiting collateralized positions or taking profits.
2756///
2757/// # Arguments
2758///
2759/// * `amount_in` - Number of tokens to withdraw and sell
2760/// * `cash_out_min` - Minimum main tokens to receive
2761///
2762/// # Transaction Flow
2763///
2764/// 1. Withdraw tokens from personal position
2765/// 2. Check position remains healthy (if debt exists)
2766/// 3. Sell tokens on bonding curve
2767/// 4. Transfer proceeds to user
2768///
2769/// # Position Health
2770///
2771/// If position has outstanding debt:
2772/// - Remaining collateral must maintain required LTV
2773/// - Transaction reverts if withdrawal would enable liquidation
2774/// - Consider repaying debt before large withdrawals
2775///
2776/// # Use Cases
2777///
2778/// - Taking profits while maintaining position
2779/// - Reducing exposure during market volatility
2780/// - Exiting positions efficiently
2781#[derive(Accounts)]
2782pub struct SellWithExactTokenInAfterWithdrawAccounts<'info> {
2783    /// Owner of the personal position withdrawing and selling tokens.
2784    #[account(mut, signer)]
2785    pub owner: AccountInfo<'info>,
2786    /// Tenant account for platform fee collection.
2787    pub tenant: AccountInfo<'info>,
2788    /// Market group that owns this market.
2789    pub market_group: AccountInfo<'info>,
2790    /// Market metadata containing configuration and linked accounts.
2791    pub market_meta: AccountInfo<'info>,
2792    /// Linear market account with price curve and state.
2793    #[account(mut)]
2794    pub market: AccountInfo<'info>,
2795    /// Personal position from which collateral will be withdrawn.
2796    #[account(mut)]
2797    pub personal_position: AccountInfo<'info>,
2798    /// Liquidity vault sending out main tokens from the sale.
2799    #[account(mut)]
2800    pub liq_vault_main: AccountInfo<'info>,
2801    /// Revenue escrow for market group admin fees.
2802    #[account(mut)]
2803    pub rev_escrow_group: AccountInfo<'info>,
2804    /// Revenue escrow for tenant platform fees.
2805    #[account(mut)]
2806    pub rev_escrow_tenant: AccountInfo<'info>,
2807    /// Mint for the market tokens being sold.
2808    #[account(mut)]
2809    pub mint_token: AccountInfo<'info>,
2810    /// Mint for the main token received from sale.
2811    pub mint_main: AccountInfo<'info>,
2812    /// Destination account to receive main tokens from sale.
2813    #[account(mut)]
2814    pub main_dst: AccountInfo<'info>,
2815    /// Source account for tokens (will be the escrow after withdrawal).
2816    #[account(mut)]
2817    pub token_src: AccountInfo<'info>,
2818    /// Escrow account from which tokens are withdrawn before selling.
2819    #[account(mut)]
2820    pub escrow: AccountInfo<'info>,
2821    /// Token program for the main token.
2822    pub token_program_main: AccountInfo<'info>,
2823    /// Token program for the market's derivative token.
2824    pub token_program: AccountInfo<'info>,
2825    #[account(mut)]
2826    pub log_account: AccountInfo<'info>,
2827    pub mayflower_program: AccountInfo<'info>,
2828}
2829
2830/// Deposit market tokens as collateral into personal position.
2831///
2832/// Adds market tokens to your position's collateral balance, enabling borrowing
2833/// operations. Deposited tokens remain locked until withdrawn or liquidated.
2834///
2835/// # Arguments
2836///
2837/// * `amount` - Number of market tokens to deposit
2838///
2839/// # Collateral Benefits
2840///
2841/// - Enables borrowing main tokens up to LTV limit
2842/// - Earns potential appreciation if floor price rises
2843/// - Protects position from liquidation
2844/// - Can be withdrawn anytime (if position healthy)
2845///
2846/// # Requirements
2847///
2848/// - Personal position must exist
2849/// - Sufficient token balance in wallet
2850/// - Market must allow deposits
2851#[derive(Accounts)]
2852pub struct DepositAccounts<'info> {
2853    /// The depositor can be anyone
2854    /// They are depositing tokens into the personal position's escrow.
2855    #[account(mut, signer)]
2856    pub payer: AccountInfo<'info>,
2857    /// Market metadata identifying which market these tokens belong to.
2858    pub market_meta: AccountInfo<'info>,
2859    /// Mint for the market tokens being deposited.
2860    pub mint_token: AccountInfo<'info>,
2861    /// Linear market account to update collateral tracking.
2862    /// Constrained by market_meta
2863    #[account(mut)]
2864    pub market: AccountInfo<'info>,
2865    /// Personal position receiving the collateral deposit.
2866    #[account(mut)]
2867    pub personal_position: AccountInfo<'info>,
2868    /// Escrow token account holding the position's collateral.
2869    #[account(mut)]
2870    pub escrow: AccountInfo<'info>,
2871    /// Source token account containing tokens to deposit.
2872    #[account(mut)]
2873    pub token_src: AccountInfo<'info>,
2874    /// Token program for the market's derivative token.
2875    pub token_program: AccountInfo<'info>,
2876    #[account(mut)]
2877    pub log_account: AccountInfo<'info>,
2878    pub mayflower_program: AccountInfo<'info>,
2879}
2880
2881/// Withdraw collateral from personal position.
2882///
2883/// Removes market tokens from collateral, returning them to your wallet. Withdrawal
2884/// is only allowed if the position remains healthy after removal.
2885///
2886/// # Arguments
2887///
2888/// * `amount` - Number of market tokens to withdraw
2889///
2890/// # Health Requirements
2891///
2892/// If position has debt:
2893/// - Remaining collateral value must exceed debt × (1 / LTV)
2894/// - Example: $1000 debt at 80% LTV requires $1250 collateral
2895/// - Transaction reverts if health check fails
2896///
2897/// # Full Withdrawal
2898///
2899/// To withdraw all collateral:
2900/// 1. Repay all outstanding debt first
2901/// 2. Then withdraw full collateral balance
2902#[derive(Accounts)]
2903pub struct WithdrawAccounts<'info> {
2904    /// Owner of the personal position withdrawing collateral.
2905    #[account(mut, signer)]
2906    pub owner: AccountInfo<'info>,
2907    /// Market metadata identifying which market these tokens belong to.
2908    pub market_meta: AccountInfo<'info>,
2909    /// Mint for the market tokens being withdrawn.
2910    pub mint_token: AccountInfo<'info>,
2911    /// Linear market account to update collateral tracking.
2912    #[account(mut)]
2913    pub market: AccountInfo<'info>,
2914    /// Personal position from which collateral is being withdrawn.
2915    /// Must be owned by the signer and have no outstanding debt.
2916    #[account(mut)]
2917    pub personal_position: AccountInfo<'info>,
2918    /// Escrow token account holding the position's collateral.
2919    #[account(mut)]
2920    pub escrow: AccountInfo<'info>,
2921    /// Destination token account to receive withdrawn tokens.
2922    #[account(mut)]
2923    pub token_dst: AccountInfo<'info>,
2924    /// Token program for the market's derivative token.
2925    pub token_program: AccountInfo<'info>,
2926    #[account(mut)]
2927    pub log_account: AccountInfo<'info>,
2928    pub mayflower_program: AccountInfo<'info>,
2929}
2930
2931/// Borrow main tokens against deposited collateral.
2932///
2933/// Takes a loan in main tokens (e.g., USDC) using market tokens as collateral.
2934/// Borrowed amount is limited by position's collateral value and market LTV ratio.
2935///
2936/// # Arguments
2937///
2938/// * `amount` - Amount of main tokens to borrow
2939///
2940/// # Borrowing Limits
2941///
2942/// Maximum borrow = Collateral Value × LTV Ratio
2943/// - Collateral valued at current floor price
2944/// - LTV typically 50-80% depending on market
2945/// - Cannot exceed available market liquidity
2946///
2947/// # Interest Accrual
2948///
2949/// - Interest calculated per-second at market rate
2950/// - Compounds continuously on outstanding debt
2951/// - Rate may vary based on utilization
2952///
2953/// # Liquidation Risk
2954///
2955/// Position can be liquidated if:
2956/// - Market token price drops significantly
2957/// - Accumulated interest pushes debt above limit
2958/// - Market LTV parameters change
2959///
2960/// Monitor position health regularly to avoid liquidation.
2961#[derive(Accounts)]
2962pub struct BorrowAccounts<'info> {
2963    /// Owner of the personal position borrowing funds.
2964    #[account(mut, signer)]
2965    pub owner: AccountInfo<'info>,
2966    /// Tenant account for platform fee distribution.
2967    pub tenant: AccountInfo<'info>,
2968    /// Market group containing borrow fee configuration.
2969    pub market_group: AccountInfo<'info>,
2970    /// Market metadata with all market configuration and references.
2971    pub market_meta: AccountInfo<'info>,
2972    /// Market's liquidity vault providing the borrowed funds.
2973    #[account(mut)]
2974    pub liq_vault_main: AccountInfo<'info>,
2975    /// Revenue escrow for market group admin fees.
2976    #[account(mut)]
2977    pub rev_escrow_group: AccountInfo<'info>,
2978    /// Revenue escrow for tenant platform fees.
2979    #[account(mut)]
2980    pub rev_escrow_tenant: AccountInfo<'info>,
2981    /// Mint for the main token being borrowed.
2982    pub mint_main: AccountInfo<'info>,
2983    /// Destination account to receive borrowed main tokens.
2984    #[account(mut)]
2985    pub main_dst: AccountInfo<'info>,
2986    /// Linear market account to update liquidity and debt tracking.
2987    /// Constrained by market_meta
2988    #[account(mut)]
2989    pub market: AccountInfo<'info>,
2990    /// Personal position using collateral to secure the loan.
2991    /// Must have sufficient collateral for the requested borrow amount.
2992    #[account(mut)]
2993    pub personal_position: AccountInfo<'info>,
2994    /// Token program for the main token.
2995    pub token_program_main: AccountInfo<'info>,
2996    #[account(mut)]
2997    pub log_account: AccountInfo<'info>,
2998    pub mayflower_program: AccountInfo<'info>,
2999}
3000
3001/// Repay borrowed main tokens to reduce debt.
3002///
3003/// Repays outstanding debt in main tokens, reducing position's obligations and
3004/// improving health factor. Can repay partial or full amounts.
3005///
3006/// # Arguments
3007///
3008/// * `amount` - Amount of main tokens to repay
3009///
3010/// # Repayment Order
3011///
3012/// Payments apply to:
3013/// 1. Accrued interest first
3014/// 2. Principal debt second
3015///
3016/// # Benefits of Repayment
3017///
3018/// - Reduces liquidation risk
3019/// - Stops interest accrual on repaid amount
3020/// - Frees up borrowing capacity
3021/// - Enables collateral withdrawal
3022///
3023/// # Full Repayment
3024///
3025/// To close position completely:
3026/// 1. Repay all debt including accrued interest
3027/// 2. Withdraw all collateral
3028/// 3. Position can then be closed if desired
3029#[derive(Accounts)]
3030pub struct RepayAccounts<'info> {
3031    /// The account repaying the debt (can be anyone, not just the position owner).
3032    #[account(mut, signer)]
3033    pub repayer: AccountInfo<'info>,
3034    /// Market metadata with all market configuration and references.
3035    pub market_meta: AccountInfo<'info>,
3036    /// Linear market account to update liquidity and debt tracking.
3037    #[account(mut)]
3038    pub market: AccountInfo<'info>,
3039    /// Personal position whose debt is being repaid.
3040    #[account(mut)]
3041    pub personal_position: AccountInfo<'info>,
3042    /// Mint for the main token being repaid.
3043    pub mint_main: AccountInfo<'info>,
3044    /// Source account containing main tokens for repayment.
3045    #[account(mut)]
3046    pub main_src: AccountInfo<'info>,
3047    /// Market's liquidity vault receiving the repayment.
3048    #[account(mut)]
3049    pub liq_vault_main: AccountInfo<'info>,
3050    /// Token program for the main token.
3051    pub token_program_main: AccountInfo<'info>,
3052    #[account(mut)]
3053    pub log_account: AccountInfo<'info>,
3054    pub mayflower_program: AccountInfo<'info>,
3055}
3056
3057/// Withdraw collateral, sell it, and optionally repay debt from proceeds.
3058///
3059/// Atomically combines withdraw, sell, and repay operations. Withdraws collateral tokens
3060/// from personal position, sells them back to the market, optionally repays debt from
3061/// the proceeds, and transfers remaining cash to the user.
3062///
3063/// # Arguments
3064///
3065/// * `args.collateral_reduce_by` - Amount of collateral tokens to withdraw and sell
3066/// * `args.debt_reduce_by` - Amount of debt to repay from sale proceeds (can be 0)
3067/// * `args.min_cash_to_user` - Minimum cash to receive after repaying debt (slippage protection)
3068///
3069/// # Operation Flow
3070///
3071/// 1. Withdraw collateral from position
3072/// 2. Sell withdrawn collateral to market
3073/// 3. Repay debt from sale proceeds (if debt_reduce_by > 0)
3074/// 4. Transfer remaining cash to user
3075///
3076/// # Slippage Protection
3077///
3078/// Transaction fails if:
3079/// - Sale proceeds < debt_reduce_by + min_cash_to_user
3080/// - Protects against unfavorable price movements
3081///
3082/// # Debt Repayment
3083///
3084/// - Debt repayment is optional (debt_reduce_by can be 0)
3085/// - If repaying, permission checks ensure repay is allowed
3086/// - Remaining sale proceeds go to user after repayment
3087///
3088/// # Use Cases
3089///
3090/// - Close leveraged position: withdraw all collateral, sell, repay all debt
3091/// - Partial deleverage: reduce position and debt simultaneously
3092/// - Take profit: withdraw and sell collateral, keep debt unchanged (debt_reduce_by = 0)
3093#[derive(Accounts)]
3094pub struct WithdrawSellAndRepayAccounts<'info> {
3095    /// Owner of the personal position performing the operation.
3096    #[account(mut, signer)]
3097    pub owner: AccountInfo<'info>,
3098    /// Tenant account for platform fee collection.
3099    pub tenant: AccountInfo<'info>,
3100    /// Market group that owns this market.
3101    pub market_group: AccountInfo<'info>,
3102    /// Market metadata containing configuration and linked accounts.
3103    pub market_meta: AccountInfo<'info>,
3104    /// Linear market account with price curve and state.
3105    #[account(mut)]
3106    pub market: AccountInfo<'info>,
3107    /// Personal position from which collateral is being withdrawn.
3108    #[account(mut)]
3109    pub personal_position: AccountInfo<'info>,
3110    /// Escrow account holding the position's collateral tokens.
3111    #[account(mut)]
3112    pub escrow: AccountInfo<'info>,
3113    /// Mint for the market's derivative token being sold.
3114    #[account(mut)]
3115    pub mint_token: AccountInfo<'info>,
3116    /// Mint for the main token received from the sale.
3117    pub mint_main: AccountInfo<'info>,
3118    /// Destination account to receive main tokens from the sale (after debt repayment).
3119    #[account(mut)]
3120    pub main_dst: AccountInfo<'info>,
3121    /// Liquidity vault that provides cash for the sale.
3122    #[account(mut)]
3123    pub liq_vault_main: AccountInfo<'info>,
3124    /// Revenue escrow for market group admin fees.
3125    #[account(mut)]
3126    pub rev_escrow_group: AccountInfo<'info>,
3127    /// Revenue escrow for tenant platform fees.
3128    #[account(mut)]
3129    pub rev_escrow_tenant: AccountInfo<'info>,
3130    /// Token program for the market's derivative token.
3131    pub token_program: AccountInfo<'info>,
3132    /// Token program for the main token.
3133    pub token_program_main: AccountInfo<'info>,
3134    #[account(mut)]
3135    pub log_account: AccountInfo<'info>,
3136    pub mayflower_program: AccountInfo<'info>,
3137}
3138
3139/// Exercise option tokens to purchase market tokens at floor price.
3140///
3141/// Converts option tokens into market tokens by paying the floor price in main tokens.
3142/// This allows option holders to acquire tokens at a fixed price regardless of current
3143/// market price.
3144///
3145/// # Arguments
3146///
3147/// * `amount` - Number of option tokens to exercise
3148///
3149/// # Economics
3150///
3151/// For each option token:
3152/// - Pay: 1 unit of main token × floor price
3153/// - Receive: 1 market token
3154/// - Burn: 1 option token
3155///
3156/// # Profitability
3157///
3158/// Profitable when: Current Price > Floor Price + Exercise Fee
3159/// - Check current bonding curve price
3160/// - Account for exercise fees
3161/// - Consider immediate sell vs holding
3162///
3163/// # Requirements
3164///
3165/// - Sufficient option token balance
3166/// - Sufficient main tokens for payment
3167/// - Market must allow option exercise
3168#[derive(Accounts)]
3169pub struct ExerciseOptionsAccounts<'info> {
3170    /// The account exercising options and paying the exercise price.
3171    #[account(mut, signer)]
3172    pub payer: AccountInfo<'info>,
3173    /// Tenant account for platform fee distribution.
3174    pub tenant: AccountInfo<'info>,
3175    /// Market group containing exercise option fee configuration.
3176    pub market_group: AccountInfo<'info>,
3177    /// Market metadata with all market configuration and references.
3178    pub market_meta: AccountInfo<'info>,
3179    /// Linear market account to update supply tracking.
3180    #[account(mut)]
3181    pub market: AccountInfo<'info>,
3182    /// Source account containing main tokens to pay exercise price.
3183    #[account(mut)]
3184    pub main_src: AccountInfo<'info>,
3185    /// Source account containing option tokens to burn.
3186    #[account(mut)]
3187    pub options_src: AccountInfo<'info>,
3188    /// Destination account to receive market tokens.
3189    #[account(mut)]
3190    pub token_dst: AccountInfo<'info>,
3191    /// Market's liquidity vault receiving the exercise payment.
3192    #[account(mut)]
3193    pub liq_vault_main: AccountInfo<'info>,
3194    /// Mint for option tokens being burned.
3195    #[account(mut)]
3196    pub mint_options: AccountInfo<'info>,
3197    /// Mint for market tokens being received.
3198    #[account(mut)]
3199    pub mint_token: AccountInfo<'info>,
3200    /// Mint for main tokens used as payment.
3201    pub mint_main: AccountInfo<'info>,
3202    /// Revenue escrow for tenant platform fees.
3203    #[account(mut)]
3204    pub rev_escrow_tenant: AccountInfo<'info>,
3205    /// Revenue escrow for market group admin fees.
3206    #[account(mut)]
3207    pub rev_escrow_group: AccountInfo<'info>,
3208    /// Token program for option and market tokens.
3209    pub token_program: AccountInfo<'info>,
3210    /// Token program for the main token.
3211    pub token_program_main: AccountInfo<'info>,
3212    #[account(mut)]
3213    pub log_account: AccountInfo<'info>,
3214    pub mayflower_program: AccountInfo<'info>,
3215}
3216
3217/// Redeem market tokens at the guaranteed floor price.
3218///
3219/// Allows token holders to exit at the floor price when market price is at or near
3220/// the floor. This provides downside protection and ensures minimum redemption value.
3221///
3222/// # Arguments
3223///
3224/// * `amount_tokens_in` - Number of market tokens to redeem
3225///
3226/// # Redemption Limits
3227///
3228/// Maximum redeemable = Tail Width = (tail_start - shoulder_end)
3229/// - Protects bonding curve integrity
3230/// - Ensures sufficient liquidity for all holders
3231/// - Resets as tokens are bought back
3232///
3233/// # Price Guarantee
3234///
3235/// Receives: Floor Price × Tokens - Fees
3236/// - Always redeems at floor regardless of curve position
3237/// - Sell fees still apply (platform + group)
3238/// - Net proceeds = floor_price × tokens × (1 - total_fee_rate)
3239///
3240/// # Use Cases
3241///
3242/// - Exit strategy during market downturns
3243/// - Arbitrage when market price < floor
3244/// - Risk management for large positions
3245#[derive(Accounts)]
3246pub struct RedeemAtFloorAccounts<'info> {
3247    #[account(mut, signer)]
3248    pub payer: AccountInfo<'info>,
3249    pub tenant: AccountInfo<'info>,
3250    pub market_group: AccountInfo<'info>,
3251    pub market_meta: AccountInfo<'info>,
3252    #[account(mut)]
3253    pub market: AccountInfo<'info>,
3254    #[account(mut)]
3255    pub rev_escrow_group: AccountInfo<'info>,
3256    #[account(mut)]
3257    pub rev_escrow_tenant: AccountInfo<'info>,
3258    #[account(mut)]
3259    pub liq_vault_main: AccountInfo<'info>,
3260    #[account(mut)]
3261    pub mint_token: AccountInfo<'info>,
3262    pub mint_main: AccountInfo<'info>,
3263    #[account(mut)]
3264    pub main_dst: AccountInfo<'info>,
3265    #[account(mut)]
3266    pub token_src: AccountInfo<'info>,
3267    pub token_program_main: AccountInfo<'info>,
3268    pub token_program: AccountInfo<'info>,
3269    #[account(mut)]
3270    pub log_account: AccountInfo<'info>,
3271    pub mayflower_program: AccountInfo<'info>,
3272}
3273
3274/// Initialize a multi-curve market with Dutch auction configuration.
3275///
3276/// Creates a market using a multi-segment bonding curve that provides more flexibility
3277/// than linear markets. Supports variable-length price curves with multiple segments,
3278/// each with its own slope. Includes Dutch auction for initial price discovery.
3279///
3280/// # Arguments
3281///
3282/// * `args` - Configuration including:
3283/// - `floor`: Base price per token
3284/// - `target`: Maximum price per token
3285/// - `shoulder_start` / `shoulder_end`: Range for initial linear segment
3286/// - `tail_start`: Beginning of constant max price segment
3287/// - `middle_segments`: Array of intermediate curve segments
3288/// - Dutch auction parameters (multiplier, duration, start time)
3289///
3290/// # Multi-Curve Advantages
3291///
3292/// - Flexible price discovery through custom segments
3293/// - Better modeling of complex tokenomics
3294/// - Smooth transitions between price regions
3295/// - Support for non-linear growth patterns
3296///
3297/// # Segment Structure
3298///
3299/// 1. Floor: Constant price from 0 to shoulder_start
3300/// 2. First shoulder: Linear from shoulder_start to first middle segment
3301/// 3. Middle segments: Variable slopes and ranges (can be empty)
3302/// 4. Final shoulder: From last middle segment to shoulder_end
3303/// 5. Tail: Constant max price from tail_start onward
3304///
3305/// # Access Control
3306///
3307/// Only the market group admin can create new markets.
3308#[derive(Accounts)]
3309pub struct MultiMarketInitWithDutchAccounts<'info> {
3310    #[account(mut, signer)]
3311    pub payer: AccountInfo<'info>,
3312    #[account(signer)]
3313    pub group_admin: AccountInfo<'info>,
3314    #[account(signer)]
3315    pub seed: AccountInfo<'info>,
3316    pub tenant: AccountInfo<'info>,
3317    pub market_group: AccountInfo<'info>,
3318    pub mint_main: AccountInfo<'info>,
3319    /// The token account for the market
3320    /// This account must be created in a previous instruction
3321    /// With supply set to zero
3322    /// And mint authority assigned to the market_meta
3323    pub mint_token: AccountInfo<'info>,
3324    #[account(mut)]
3325    pub mint_options: AccountInfo<'info>,
3326    #[account(mut)]
3327    pub liq_vault_main: AccountInfo<'info>,
3328    #[account(mut)]
3329    pub rev_escrow_group: AccountInfo<'info>,
3330    #[account(mut)]
3331    pub rev_escrow_tenant: AccountInfo<'info>,
3332    #[account(mut)]
3333    pub market: AccountInfo<'info>,
3334    #[account(mut)]
3335    pub market_meta: AccountInfo<'info>,
3336    pub system_program: AccountInfo<'info>,
3337    pub token_program: AccountInfo<'info>,
3338    pub token_program_main: AccountInfo<'info>,
3339}
3340
3341/// Raise floor price for multi-curve markets with validation.
3342///
3343/// Increases the minimum token price while preserving the total area under the
3344/// multi-segment curve. More complex than linear markets due to multiple segments
3345/// requiring coordinated adjustment.
3346///
3347/// # Arguments
3348///
3349/// * `args` - Parameters including:
3350/// - `new_floor`: Target floor price
3351/// - `new_shoulder_end`: Adjusted endpoint for price curve
3352/// - `new_middle_segments`: Recalculated intermediate segments
3353/// - `max_deviation_bps`: Tolerance for area preservation
3354///
3355/// # Segment Adjustment
3356///
3357/// When floor rises:
3358/// 1. All segments shift up by floor delta
3359/// 2. Slopes adjust to maintain total area
3360/// 3. Segment boundaries may compress
3361/// 4. Continuity preserved at all transitions
3362///
3363/// # Validation Checks
3364///
3365/// - Area preservation within tolerance
3366/// - Sufficient backing liquidity
3367/// - Valid segment progression (monotonic)
3368/// - No instant arbitrage opportunities
3369///
3370/// # Complexity Note
3371///
3372/// Multi-curve floor raising requires careful calculation to maintain curve
3373/// properties across all segments while preserving economic invariants.
3374#[derive(Accounts)]
3375pub struct RaiseFloorPreserveAreaCheckedMultiAccounts<'info> {
3376    #[account(mut, signer)]
3377    pub admin: AccountInfo<'info>,
3378    pub market_group: AccountInfo<'info>,
3379    pub market_meta: AccountInfo<'info>,
3380    #[account(mut)]
3381    pub market: AccountInfo<'info>,
3382}
3383
3384/// Buy from multi-curve market and deposit as collateral.
3385///
3386/// Purchases tokens from a multi-segment bonding curve and immediately deposits them
3387/// into a personal position. Combines acquisition and collateralization in one step.
3388///
3389/// # Arguments
3390///
3391/// * `cash_in` - Exact amount of main tokens to spend
3392/// * `min_token_out` - Minimum tokens to receive (slippage protection)
3393///
3394/// # Multi-Curve Pricing
3395///
3396/// Price depends on current supply position:
3397/// - Traverses multiple segments with different slopes
3398/// - Large buys may span several segments
3399/// - Each segment calculated independently
3400/// - Dutch boost applies if active
3401///
3402/// # Atomic Benefits
3403///
3404/// - Single transaction for buy + deposit
3405/// - Reduces transaction costs
3406/// - Prevents front-running between operations
3407/// - Immediate collateral availability
3408///
3409/// # Requirements
3410///
3411/// - Personal position must exist
3412/// - Market must allow buying and deposits
3413/// - Sufficient main token balance
3414#[derive(Accounts)]
3415pub struct BuyWithExactCashInAndDepositMultiAccounts<'info> {
3416    /// The trader buying tokens and depositing them as collateral.
3417    #[account(mut, signer)]
3418    pub owner: AccountInfo<'info>,
3419    /// Tenant account for platform fee collection.
3420    pub tenant: AccountInfo<'info>,
3421    /// Market group that owns this market.
3422    pub market_group: AccountInfo<'info>,
3423    /// Market metadata containing configuration and linked accounts.
3424    pub market_meta: AccountInfo<'info>,
3425    /// Multi-curve market account with price curve and state.
3426    #[account(mut)]
3427    pub market: AccountInfo<'info>,
3428    /// Personal position that will receive the purchased tokens as collateral.
3429    #[account(mut)]
3430    pub personal_position: AccountInfo<'info>,
3431    /// Escrow account that will receive the purchased tokens as collateral.
3432    #[account(mut)]
3433    pub escrow: AccountInfo<'info>,
3434    /// Mint for the market's derivative token being purchased.
3435    #[account(mut)]
3436    pub mint_token: AccountInfo<'info>,
3437    /// Mint for the main token used as payment.
3438    pub mint_main: AccountInfo<'info>,
3439    /// Temporary destination for purchased tokens before deposit to escrow.
3440    #[account(mut)]
3441    pub token_dst: AccountInfo<'info>,
3442    /// Source account containing main tokens for payment.
3443    #[account(mut)]
3444    pub main_src: AccountInfo<'info>,
3445    /// Liquidity vault receiving the main token payment.
3446    #[account(mut)]
3447    pub liq_vault_main: AccountInfo<'info>,
3448    /// Revenue escrow for market group admin fees.
3449    #[account(mut)]
3450    pub rev_escrow_group: AccountInfo<'info>,
3451    /// Revenue escrow for tenant platform fees.
3452    #[account(mut)]
3453    pub rev_escrow_tenant: AccountInfo<'info>,
3454    /// Token program for the market's derivative token.
3455    pub token_program: AccountInfo<'info>,
3456    /// Token program for the main token.
3457    pub token_program_main: AccountInfo<'info>,
3458    #[account(mut)]
3459    pub log_account: AccountInfo<'info>,
3460    pub mayflower_program: AccountInfo<'info>,
3461}
3462
3463/// Buy tokens from a multi-curve market.
3464///
3465/// Purchases market tokens using a multi-segment bonding curve that can model
3466/// complex price dynamics. Supports large purchases that span multiple curve
3467/// segments with different characteristics.
3468///
3469/// # Arguments
3470///
3471/// * `cash_in` - Exact amount of main tokens to spend
3472/// * `min_token_out` - Minimum tokens required (reverts if not met)
3473///
3474/// # Execution Across Segments
3475///
3476/// Large purchases may traverse multiple segments:
3477/// 1. Start at current supply position
3478/// 2. Buy at current segment's price/slope
3479/// 3. If segment exhausted, continue to next
3480/// 4. Accumulate tokens from each segment
3481/// 5. Stop when cash exhausted or curve end reached
3482///
3483/// # Price Impact
3484///
3485/// - Each segment may have different price sensitivity
3486/// - Steeper slopes mean higher price impact
3487/// - Consider breaking very large orders
3488///
3489/// # Fees
3490///
3491/// Standard fee structure applies:
3492/// - Platform fee to tenant
3493/// - Group fee to market admin
3494/// - Deducted from input amount
3495#[derive(Accounts)]
3496pub struct BuyWithExactCashInMultiAccounts<'info> {
3497    /// The buyer purchasing market tokens.
3498    #[account(mut, signer)]
3499    pub signer: AccountInfo<'info>,
3500    /// Tenant account for platform fee collection.
3501    pub tenant: AccountInfo<'info>,
3502    /// Market group that owns this market.
3503    pub market_group: AccountInfo<'info>,
3504    /// Market metadata containing configuration and linked accounts.
3505    pub market_meta: AccountInfo<'info>,
3506    /// Multi-curve market account with price curve and state.
3507    #[account(mut)]
3508    pub market: AccountInfo<'info>,
3509    /// Mint for the market's derivative token.
3510    #[account(mut)]
3511    pub mint_token: AccountInfo<'info>,
3512    /// Mint for the main token used as payment.
3513    pub mint_main: AccountInfo<'info>,
3514    /// Destination token account to receive purchased tokens.
3515    #[account(mut)]
3516    pub token_dst: AccountInfo<'info>,
3517    /// Source account containing main tokens for payment.
3518    #[account(mut)]
3519    pub main_src: AccountInfo<'info>,
3520    /// Liquidity vault receiving the main tokens.
3521    #[account(mut)]
3522    pub liq_vault_main: AccountInfo<'info>,
3523    /// Revenue escrow for market group admin fees.
3524    #[account(mut)]
3525    pub rev_escrow_group: AccountInfo<'info>,
3526    /// Revenue escrow for tenant platform fees.
3527    #[account(mut)]
3528    pub rev_escrow_tenant: AccountInfo<'info>,
3529    /// Token program for the market's derivative token.
3530    pub token_program: AccountInfo<'info>,
3531    /// Token program for the main token.
3532    pub token_program_main: AccountInfo<'info>,
3533    #[account(mut)]
3534    pub log_account: AccountInfo<'info>,
3535    pub mayflower_program: AccountInfo<'info>,
3536}
3537
3538/// Sell tokens to a multi-curve market.
3539///
3540/// Sells market tokens back to the protocol following the multi-segment bonding curve
3541/// in reverse. Large sales may span multiple segments with varying price impacts.
3542///
3543/// # Arguments
3544///
3545/// * `amount_in` - Exact number of tokens to sell
3546/// * `cash_out_min` - Minimum main tokens to receive
3547///
3548/// # Multi-Segment Execution
3549///
3550/// Sells work backwards through curve:
3551/// 1. Start at current supply position
3552/// 2. Sell into current segment at its price
3553/// 3. If more to sell, move to previous segment
3554/// 4. Continue until all tokens sold
3555/// 5. Cannot sell below floor price
3556///
3557/// # Price Discovery
3558///
3559/// - Higher supplies sell first (higher prices)
3560/// - Price decreases as supply reduces
3561/// - Each segment has independent characteristics
3562/// - Floor provides absolute minimum
3563///
3564/// # Slippage Considerations
3565///
3566/// Multi-curve markets may have:
3567/// - Variable liquidity across segments
3568/// - Sudden price changes at boundaries
3569/// - Different impacts in different regions
3570#[derive(Accounts)]
3571pub struct SellWithExactTokenInMultiAccounts<'info> {
3572    /// User selling market tokens back to the protocol.
3573    #[account(mut, signer)]
3574    pub user: AccountInfo<'info>,
3575    /// Tenant account for platform fee collection.
3576    pub tenant: AccountInfo<'info>,
3577    /// Market group that owns this market.
3578    pub market_group: AccountInfo<'info>,
3579    /// Market metadata containing configuration and linked accounts.
3580    pub market_meta: AccountInfo<'info>,
3581    /// Multi-curve market account with price curve and state.
3582    #[account(mut)]
3583    pub market: AccountInfo<'info>,
3584    /// Revenue escrow for market group admin fees.
3585    #[account(mut)]
3586    pub rev_escrow_group: AccountInfo<'info>,
3587    /// Revenue escrow for tenant platform fees.
3588    #[account(mut)]
3589    pub rev_escrow_tenant: AccountInfo<'info>,
3590    /// Liquidity vault sending out main tokens.
3591    #[account(mut)]
3592    pub liq_vault_main: AccountInfo<'info>,
3593    /// Mint for the market tokens being sold.
3594    #[account(mut)]
3595    pub mint_token: AccountInfo<'info>,
3596    /// Mint for the main token received from sale.
3597    pub mint_main: AccountInfo<'info>,
3598    /// Destination account to receive main tokens from sale.
3599    #[account(mut)]
3600    pub main_dst: AccountInfo<'info>,
3601    /// Source account containing market tokens to sell.
3602    #[account(mut)]
3603    pub token_src: AccountInfo<'info>,
3604    /// Token program for the main token.
3605    pub token_program_main: AccountInfo<'info>,
3606    /// Token program for the market's derivative token.
3607    pub token_program: AccountInfo<'info>,
3608    #[account(mut)]
3609    pub log_account: AccountInfo<'info>,
3610    pub mayflower_program: AccountInfo<'info>,
3611}
3612
3613/// Exercise options in a multi-curve market.
3614///
3615/// Converts option tokens to market tokens at the floor price, regardless of the
3616/// current position on the multi-segment curve. Options provide downside protection
3617/// in volatile multi-curve markets.
3618///
3619/// # Arguments
3620///
3621/// * `amount` - Number of option tokens to exercise
3622///
3623/// # Exercise Mechanics
3624///
3625/// Same as linear markets:
3626/// - Pay floor price per option in main tokens
3627/// - Receive one market token per option
3628/// - Options are burned
3629///
3630/// # Multi-Curve Considerations
3631///
3632/// - Floor price is constant across all segments
3633/// - Current curve position doesn't affect exercise
3634/// - Especially valuable when price is in higher segments
3635/// - Provides arbitrage during market dislocations
3636///
3637/// # Strategic Use
3638///
3639/// In multi-curve markets, options help:
3640/// - Navigate complex price dynamics
3641/// - Profit from segment transitions
3642/// - Hedge against curve adjustments
3643#[derive(Accounts)]
3644pub struct ExerciseOptionsMultiAccounts<'info> {
3645    #[account(mut, signer)]
3646    pub payer: AccountInfo<'info>,
3647    pub tenant: AccountInfo<'info>,
3648    pub market_group: AccountInfo<'info>,
3649    pub market_meta: AccountInfo<'info>,
3650    #[account(mut)]
3651    pub market: AccountInfo<'info>,
3652    #[account(mut)]
3653    pub main_src: AccountInfo<'info>,
3654    #[account(mut)]
3655    pub options_src: AccountInfo<'info>,
3656    #[account(mut)]
3657    pub token_dst: AccountInfo<'info>,
3658    #[account(mut)]
3659    pub liq_vault_main: AccountInfo<'info>,
3660    #[account(mut)]
3661    pub mint_options: AccountInfo<'info>,
3662    #[account(mut)]
3663    pub mint_token: AccountInfo<'info>,
3664    pub mint_main: AccountInfo<'info>,
3665    #[account(mut)]
3666    pub rev_escrow_tenant: AccountInfo<'info>,
3667    #[account(mut)]
3668    pub rev_escrow_group: AccountInfo<'info>,
3669    pub token_program: AccountInfo<'info>,
3670    pub token_program_main: AccountInfo<'info>,
3671    #[account(mut)]
3672    pub log_account: AccountInfo<'info>,
3673    pub mayflower_program: AccountInfo<'info>,
3674}
3675
3676/// Repay debt in a multi-curve market.
3677///
3678/// Repays borrowed main tokens to reduce debt obligations in a personal position.
3679/// Multi-curve markets may have different interest dynamics based on utilization
3680/// across curve segments.
3681///
3682/// # Arguments
3683///
3684/// * `amount` - Amount of main tokens to repay
3685///
3686/// # Interest Considerations
3687///
3688/// Multi-curve markets may feature:
3689/// - Variable rates based on curve position
3690/// - Different risk profiles across segments
3691/// - Dynamic rate adjustments
3692///
3693/// # Repayment Priority
3694///
3695/// Same as linear markets:
3696/// 1. Accrued interest first
3697/// 2. Principal balance second
3698/// 3. Excess returned to payer
3699///
3700/// # Position Management
3701///
3702/// Regular repayments recommended to:
3703/// - Maintain healthy LTV ratios
3704/// - Reduce liquidation risk
3705/// - Take advantage of rate changes
3706#[derive(Accounts)]
3707pub struct RepayMultiAccounts<'info> {
3708    #[account(mut, signer)]
3709    pub repayer: AccountInfo<'info>,
3710    pub market_meta: AccountInfo<'info>,
3711    #[account(mut)]
3712    pub market: AccountInfo<'info>,
3713    #[account(mut)]
3714    pub personal_position: AccountInfo<'info>,
3715    pub mint_main: AccountInfo<'info>,
3716    #[account(mut)]
3717    pub main_src: AccountInfo<'info>,
3718    #[account(mut)]
3719    pub liq_vault_main: AccountInfo<'info>,
3720    pub token_program_main: AccountInfo<'info>,
3721    #[account(mut)]
3722    pub log_account: AccountInfo<'info>,
3723    pub mayflower_program: AccountInfo<'info>,
3724}
3725
3726/// Redeem tokens at floor price in multi-curve market.
3727///
3728/// Provides guaranteed exit at the floor price for multi-curve market tokens.
3729/// Essential safety mechanism given the complexity of multi-segment pricing.
3730///
3731/// # Arguments
3732///
3733/// * `amount_tokens_in` - Number of tokens to redeem at floor
3734///
3735/// # Redemption in Complex Markets
3736///
3737/// Multi-curve considerations:
3738/// - Floor constant across all segments
3739/// - Redemption bypasses curve complexity
3740/// - Same tail width limits apply
3741/// - Critical during segment transitions
3742///
3743/// # Maximum Redemption
3744///
3745/// Limited to tail width: (tail_start - shoulder_end)
3746/// - Protects curve integrity
3747/// - Ensures fair access for all holders
3748/// - Resets as market activity continues
3749///
3750/// # Use Cases
3751///
3752/// Especially important in multi-curve markets for:
3753/// - Exiting during curve adjustments
3754/// - Arbitrage across segments
3755/// - Risk management in complex dynamics
3756/// - Guaranteed liquidity provision
3757#[derive(Accounts)]
3758pub struct RedeemAtFloorMultiAccounts<'info> {
3759    #[account(mut, signer)]
3760    pub payer: AccountInfo<'info>,
3761    pub tenant: AccountInfo<'info>,
3762    pub market_group: AccountInfo<'info>,
3763    pub market_meta: AccountInfo<'info>,
3764    #[account(mut)]
3765    pub market: AccountInfo<'info>,
3766    #[account(mut)]
3767    pub rev_escrow_group: AccountInfo<'info>,
3768    #[account(mut)]
3769    pub rev_escrow_tenant: AccountInfo<'info>,
3770    #[account(mut)]
3771    pub liq_vault_main: AccountInfo<'info>,
3772    #[account(mut)]
3773    pub mint_token: AccountInfo<'info>,
3774    pub mint_main: AccountInfo<'info>,
3775    #[account(mut)]
3776    pub main_dst: AccountInfo<'info>,
3777    #[account(mut)]
3778    pub token_src: AccountInfo<'info>,
3779    pub token_program_main: AccountInfo<'info>,
3780    pub token_program: AccountInfo<'info>,
3781    #[account(mut)]
3782    pub log_account: AccountInfo<'info>,
3783    pub mayflower_program: AccountInfo<'info>,
3784}
3785
3786/// Modify the price curve's sensitivity to supply changes at the current token supply level.
3787///
3788/// Allows market administrators to dynamically adjust how quickly the token price changes
3789/// in response to supply increases. The modification is applied at the current token supply
3790/// level and affects the curve's behavior for all future supply levels beyond that point.
3791///
3792/// # Arguments
3793///
3794/// * `args` - Curve modification parameters including:
3795/// - `multiplier`: Magnitude of slope change (0.0 < multiplier < 1.0)
3796/// - `new_middle_segment_count`: Expected number of middle segments after modification
3797/// - `increase`: Whether to increase (true) or decrease (false) sensitivity
3798///
3799/// # How it works
3800///
3801/// The function modifies the curve's vertex structure by either:
3802/// - **Inserting a new vertex** at the current supply level if it falls within the final segment
3803/// - **Removing the last vertex** if the current supply is not in the final segment and the
3804/// sensitivity direction doesn't match the final segment's current direction
3805///
3806/// # Sensitivity Direction
3807///
3808/// - **`increase = true`** (`SensitivityDirection::Higher`): Makes the curve more sensitive to supply changes
3809/// - Results in steeper slopes = faster price increases as supply grows
3810/// - Useful for encouraging early adoption or responding to high demand
3811///
3812/// - **`increase = false`** (`SensitivityDirection::Lower`): Makes the curve less sensitive to supply changes
3813/// - Results in gentler slopes = slower price increases as supply grows
3814/// - Useful for risk management or stabilizing prices in volatile conditions
3815///
3816/// # Multiplier Effect
3817///
3818/// The `multiplier` parameter (0.0 < multiplier < 1.0) determines the magnitude of change:
3819/// - For `Higher` direction: new_slope = current_slope × (1 + multiplier)
3820/// - For `Lower` direction: new_slope = current_slope × (1 - multiplier)
3821///
3822/// # Access Control
3823///
3824/// Only the market group admin can modify curves.
3825///
3826/// # Use Cases
3827///
3828/// - **Market Making**: Adjust sensitivity based on trading volume or market volatility
3829/// - **Risk Management**: Reduce sensitivity in high-supply regions to prevent extreme price swings
3830/// - **Liquidity Provision**: Increase sensitivity in low-supply regions to encourage early adoption
3831/// - **Dynamic Pricing**: Respond to market conditions by modifying curve behavior
3832///
3833/// # Constraints
3834///
3835/// - `multiplier` must be between 0.0 and 1.0 (exclusive)
3836/// - The function preserves curve continuity at segment boundaries
3837/// - Modifications only affect the curve beyond the current supply level
3838/// - The account must be reallocated to accommodate the new segment count
3839///
3840/// # Safety Considerations
3841///
3842/// - Changes are irreversible once applied
3843/// - The operation will panic if the actual number of middle segments after modification
3844/// doesn't match the expected `new_middle_segment_count`
3845/// - Consider market impact before significant changes
3846/// - Monitor market behavior after curve changes
3847#[derive(Accounts)]
3848pub struct ModifyCurveMultiAccounts<'info> {
3849    #[account(mut, signer)]
3850    pub payer: AccountInfo<'info>,
3851    #[account(mut, signer)]
3852    pub admin: AccountInfo<'info>,
3853    pub market_group: AccountInfo<'info>,
3854    pub market_meta: AccountInfo<'info>,
3855    #[account(mut)]
3856    pub market: AccountInfo<'info>,
3857    pub system_program: AccountInfo<'info>,
3858}
3859
3860// Account structures
3861#[account]
3862pub struct LogAccount {
3863    pub counter: u64,
3864    pub bump: [u8; 1],
3865}
3866
3867/// Market group account managing a collection of related markets with shared fee structures.
3868///
3869/// A MarketGroup acts as an intermediate administrative layer between a Tenant and individual
3870/// Markets. It defines the fee structure that applies to all markets within the group and
3871/// manages permissions for market operations. Multiple markets can belong to the same group,
3872/// sharing common fee configurations while maintaining independent bonding curves and liquidity.
3873///
3874/// # Ownership Hierarchy
3875/// - Owned by a single Tenant account
3876/// - Owns multiple MarketMeta accounts (which reference specific Market implementations)
3877/// - Controls fee distribution between market group admin and tenant platform
3878///
3879/// # Fee Management
3880/// The MarketGroup defines four types of fees that apply to all its markets:
3881/// - Buy fees: charged when purchasing tokens from the market
3882/// - Sell fees: charged when selling tokens back to the market
3883/// - Borrow fees: charged when borrowing against collateral
3884/// - Exercise option fees: charged when exercising token options
3885///
3886/// Fees collected are split between the market group admin and the tenant based on
3887/// the tenant's platform fee configuration.
3888#[account]
3889pub struct MarketGroup {
3890    /// The tenant account that owns this market group.
3891    /// All markets in this group must belong to the same tenant.
3892    pub tenant: Pubkey,
3893    /// The admin public key with control over this market group.
3894    /// Can update group settings, manage fees, and create new markets.
3895    pub admin: Pubkey,
3896    /// The proposed new admin for ownership transfer (None if no transfer pending).
3897    /// Requires acceptance by the proposed admin to complete the transfer.
3898    pub proposed_admin: Option<Pubkey>,
3899    /// PDA metadata containing the seed and bump used to derive this account's address.
3900    /// Used for signing operations and address verification.
3901    pub pda_meta: PdaMeta,
3902    /// Fee configuration for all markets within this group.
3903    /// Contains buy, sell, borrow, and exercise option fee rates.
3904    pub fees: Fees,
3905}
3906
3907/// Market implementation using a linear bonding curve with shoulder configuration.
3908///
3909/// MarketLinear implements a two-segment linear price curve that provides dynamic pricing
3910/// for token purchases and sales. The curve consists of a steeper "shoulder" segment at
3911/// low supply levels (providing higher initial prices) and a gentler "tail" segment for
3912/// the bulk of the supply range.
3913///
3914/// # Bonding Curve Design
3915/// The linear market uses a piecewise linear function:
3916/// - Shoulder segment: Higher slope (m1) from 0 to shoulder point
3917/// - Tail segment: Lower slope (m2) from shoulder point onwards
3918/// - Floor price: Minimum price below which tokens cannot trade
3919///
3920/// # Use Cases
3921/// - Simple bonding curve markets with predictable price dynamics
3922/// - Markets requiring a price premium for early adopters
3923/// - Token launches with controlled price discovery
3924///
3925/// # Relationship to MarketMeta
3926/// Each MarketLinear is paired with exactly one MarketMeta account that contains
3927/// the market's configuration, token mints, vaults, and permissions.
3928/// The `token_unit_scale` for x-axis scaling is stored in MarketMeta.
3929#[account]
3930pub struct MarketLinear {
3931    /// Reference to the MarketMeta account containing shared market configuration.
3932    /// Links this market implementation to its metadata and token mints.
3933    pub market_meta: Pubkey,
3934    /// Current state of the market including liquidity, debt, supply, and collateral.
3935    /// Tracks all dynamic values that change during market operations.
3936    pub state: MarketState,
3937    /// Serialized linear price curve parameters defining market pricing.
3938    /// Contains slopes, floor price, and shoulder configuration for the bonding curve.
3939    pub price_curve: LinearPriceCurveSerialized,
3940}
3941
3942/// Market metadata account containing configuration shared across all market implementations.
3943///
3944/// MarketMeta serves as the central configuration hub for a market, storing references to
3945/// all associated accounts (tokens, vaults, escrows) and operational parameters. It acts
3946/// as a bridge between the market's administrative structure (Tenant/MarketGroup) and its
3947/// implementation (MarketLinear or MarketMultiCurve).
3948///
3949/// # Key Relationships
3950/// - References its parent MarketGroup for fee configurations
3951/// - Referenced by exactly one Market implementation (Linear or MultiCurve)
3952/// - Controls three token mints: main (collateral), token (traded), and options
3953/// - Manages liquidity vault and revenue distribution escrows
3954///
3955/// # Permissions System
3956/// MarketMeta includes a flexible permissions bitfield that controls which operations
3957/// are allowed on the market. This enables fine-grained control over market functionality,
3958/// allowing administrators to disable specific features during maintenance or in response
3959/// to market conditions.
3960///
3961/// # Dutch Auction
3962/// Markets can optionally use a Dutch auction mechanism at launch, providing time-based
3963/// price incentives to early participants. The auction boost decreases over time according
3964/// to the configured parameters.
3965#[account]
3966pub struct MarketMeta {
3967    /// Mint for the main backing token (the cash token).
3968    /// This is the token used as collateral and for liquidity (e.g., USDC, SOL).
3969    pub mint_main: Pubkey,
3970    /// Mint for the token being traded in this market.
3971    /// This is the derivative token that users can buy/sell/borrow.
3972    pub mint_token: Pubkey,
3973    /// Mint for the options token associated with this market.
3974    /// Options tokens can be minted and later exercised to purchase the traded token.
3975    pub mint_options: Pubkey,
3976    /// The market group that this market belongs to.
3977    /// Determines fee structure and admin permissions for this market.
3978    pub market_group: Pubkey,
3979    /// The market account (Linear or MultiCurve) associated with this metadata.
3980    /// Ensures a 1:1 relationship between market and market meta accounts.
3981    pub market: Pubkey,
3982    /// The token program ID for the main token.
3983    /// Usually SPL Token or Token-2022, used for CPI calls.
3984    pub token_program_main: Pubkey,
3985    /// Vault that holds the liquidity pool for the main token.
3986    /// All market liquidity (cash) is stored here.
3987    pub liq_vault_main: Pubkey,
3988    /// Revenue escrow account for the market group.
3989    /// Collects group admin's share of fees from market operations.
3990    pub rev_escrow_group: Pubkey,
3991    /// Revenue escrow account for the tenant.
3992    /// Collects platform fees allocated to the tenant.
3993    pub rev_escrow_tenant: Pubkey,
3994    /// PDA metadata containing the seed and bump used to derive this account's address.
3995    /// Used for signing operations when the market acts as an authority.
3996    pub pda_meta: PdaMeta,
3997    /// Number of decimal places for the main token.
3998    /// Used for precise calculations and proper display formatting.
3999    pub decimals: u8,
4000    /// Bitfield controlling which operations are permitted on this market.
4001    /// Allows fine-grained control over market functionality.
4002    pub permissions: MarketPermissions,
4003    /// Unix timestamp when the market becomes active.
4004    /// Trading operations are restricted before this time.
4005    pub start_time: u64,
4006    /// Configuration for Dutch auction price boost mechanism.
4007    /// Provides time-based price incentives after market launch.
4008    pub dutch_config: DutchConfigSerialized,
4009    /// Power-of-2 exponent for scaling raw token units on the price curve's x-axis.
4010    ///
4011    /// When computing prices, the raw token supply is scaled by `2^token_unit_scale`:
4012    /// - Positive k: `scaled_supply = raw_supply >> k` (divide by 2^k)
4013    /// - Negative k: `scaled_supply = raw_supply << |k|` (multiply by 2^|k|)
4014    /// - Zero (default): no scaling, `scaled_supply = raw_supply`
4015    ///
4016    /// # Purpose
4017    /// Normalizes the price curve slope to ~1.0 for better fixed-point precision.
4018    /// Without scaling, tokens with vastly different values produce slopes that
4019    /// are either extremely small or extremely large, causing precision loss.
4020    ///
4021    /// # Example: BTC vs BONK
4022    /// - **BTC**: 8 decimals, ~$100k → 1 satoshi = $0.001 → slope might be ~15e9
4023    /// - **BONK**: 5 decimals, ~$1e-6 → 1 raw unit = $1e-11 → slope might be ~1e-22
4024    ///
4025    /// After applying appropriate `token_unit_scale`:
4026    /// - BTC with k=13: slope becomes ~1.2
4027    /// - BONK with k=76: slope becomes ~1.1
4028    ///
4029    /// # Calculation
4030    /// Use `find_x_scale_for_raw_units()` in `slope_helper.rs` to compute optimal k:
4031    /// `k = round(-log₂(m_raw))` where `m_raw` is the slope in raw token units.
4032    ///
4033    /// # Why Base-2?
4034    /// - Bit shifts (`>>` / `<<`) are exact operations with no rounding error
4035    /// - Native to binary fixed-point arithmetic
4036    /// - More precise than base-10 (~41% max deviation vs ~216%)
4037    pub token_unit_scale: i8,
4038}
4039
4040/// Market implementation using a multi-segment bonding curve with dynamic complexity.
4041///
4042/// MarketMultiCurve extends the linear market concept by supporting multiple linear segments,
4043/// allowing for more sophisticated price curves that can adapt over time. This is particularly
4044/// useful when the floor price is raised, as the curve can maintain area-under-curve invariants
4045/// by adding intermediate segments.
4046///
4047/// # Advanced Bonding Curve
4048/// The multi-curve market supports:
4049/// - Initial shoulder segment with configurable slope multiplier
4050/// - Dynamic middle segments added when floor is raised
4051/// - Final tail segment extending to maximum supply
4052/// - Area preservation during floor adjustments
4053///
4054/// # Use Cases
4055/// - Markets requiring complex price dynamics
4056/// - Adaptive curves that evolve with market conditions
4057/// - Floor raising with liquidity preservation
4058/// - Multi-phase token distribution strategies
4059///
4060/// # Dynamic Segment Management
4061/// When the floor is raised, the curve automatically adds middle segments to:
4062/// - Preserve the total area under the curve (maintaining market cap)
4063/// - Ensure price continuity at segment boundaries
4064/// - Maintain monotonic price increases
4065#[account]
4066pub struct MarketMultiCurve {
4067    /// Reference to the MarketMeta account containing shared market configuration.
4068    /// Links this market implementation to its metadata and token mints.
4069    pub market_meta: Pubkey,
4070    /// Current state of the market including liquidity, debt, supply, and collateral.
4071    /// Tracks all dynamic values that change during market operations.
4072    pub state: MarketState,
4073    /// Serialized multi-segment price curve with dynamic middle segments.
4074    /// Supports complex bonding curves with multiple linear segments.
4075    pub price_curve: MultiPriceCurveSerialized,
4076}
4077
4078/// Personal position account tracking an individual user's collateral and debt in a market.
4079///
4080/// PersonalPosition represents a user's borrowing position within a specific market. It tracks
4081/// both the collateral deposited (in market tokens) and any outstanding debt (in main tokens
4082/// like USDC). This account enables collateralized borrowing, where users can deposit market
4083/// tokens and borrow main tokens against them.
4084///
4085/// # Collateralization Model
4086/// - Users deposit market tokens as collateral into an escrow account
4087/// - Against this collateral, users can borrow main tokens (e.g., USDC)
4088/// - The maximum borrowing capacity depends on the market's collateralization ratio
4089/// - Collateral remains locked until all debt is repaid
4090///
4091/// # Account Lifecycle
4092/// 1. Created when a user first deposits collateral or borrows
4093/// 2. Persists as long as there's collateral or debt
4094/// 3. Can be closed when both collateral and debt reach zero
4095///
4096/// # Security
4097/// - Only the owner can perform operations on their position
4098/// - Collateral is held in a separate escrow account for security
4099/// - Position is tied to a specific market and cannot be transferred
4100#[account]
4101pub struct PersonalPosition {
4102    /// The market metadata account this position belongs to.
4103    /// Determines which market's tokens can be deposited and borrowed against.
4104    pub market_meta: Pubkey,
4105    /// The owner's public key who controls this position.
4106    /// Only the owner can deposit, withdraw, borrow, or repay.
4107    pub owner: Pubkey,
4108    /// The escrow token account holding deposited collateral tokens.
4109    /// Tokens are locked here while being used as collateral for borrowing.
4110    pub escrow: Pubkey,
4111    /// Amount of market tokens deposited as collateral.
4112    /// Can be withdrawn if debt is zero, or used to secure borrows.
4113    pub deposited_token_balance: u64,
4114    /// Amount of main tokens (e.g., USDC) currently borrowed against collateral.
4115    /// Must be repaid before collateral can be withdrawn.
4116    pub debt: u64,
4117    /// The PDA bump seed used to derive this account's address.
4118    /// Stored to avoid recalculation during operations.
4119    pub bump: [u8; 1],
4120}
4121
4122/// Tenant account representing a platform operator or protocol administrator.
4123///
4124/// The Tenant is the top-level entity in the Mayflower protocol hierarchy. Each tenant
4125/// can manage multiple market groups, set platform-wide fees, and control permissions
4126/// for market group creation. Tenants enable multi-tenancy within the protocol, allowing
4127/// different operators to run their own instances with custom configurations.
4128///
4129/// # Account Hierarchy
4130/// ```
4131/// Tenant (Platform Operator)
4132/// └── MarketGroup (Fee Configuration)
4133/// └── MarketMeta (Market Configuration)
4134/// └── Market (Linear or MultiCurve Implementation)
4135/// ```
4136///
4137/// # Key Responsibilities
4138/// - Platform fee collection across all markets under this tenant
4139/// - Control over market group creation permissions
4140/// - Admin transfer and succession management
4141/// - Platform-level configuration and governance
4142#[account]
4143pub struct Tenant {
4144    /// The seed public key used to derive this tenant's PDA address.
4145    /// This ensures deterministic address generation and prevents duplicate tenants.
4146    pub seed: Pubkey,
4147    /// The PDA bump seed used to derive this account's address.
4148    /// Stored to avoid recalculation during CPI calls.
4149    pub bump: [u8; 1],
4150    /// The admin public key with control to create market groups.
4151    pub admin: Pubkey,
4152    /// The proposed new admin for ownership transfer (None if no transfer pending).
4153    /// Requires acceptance by the proposed admin to complete the transfer.
4154    pub proposed_admin: Option<Pubkey>,
4155    /// Platform fee rate in micro basis points (1 micro bp = 1/100 bp = 0.0001%).
4156    /// Applied to transactions within markets under this tenant.
4157    pub platform_fee_micro_bps: u32,
4158    /// Whether market groups can be created without explicit permission from the tenant admin.
4159    /// When true, any user can create market groups under this tenant.
4160    pub permissionless_group_creation: bool,
4161}
4162
4163// Type structures
4164#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4165pub struct BuyWithExactCashInAndDepositEvent {
4166    /// The account that purchased tokens and deposited them as collateral.
4167    pub trader: Pubkey,
4168    /// The address of the market metadata account.
4169    pub market_meta: Pubkey,
4170    /// The address of the personal position account.
4171    pub personal_position: Pubkey,
4172    /// The amount of market tokens purchased.
4173    pub token_out: u64,
4174    /// The amount of main tokens paid by the trader (excluding fees).
4175    pub net_cash_in: u64,
4176    /// The fee amount allocated to the market group admin.
4177    pub fee_market_group: u64,
4178    /// The fee amount allocated to the platform.
4179    pub fee_platform: u64,
4180    /// The new market price after the purchase and deposit.
4181    pub new_market_price: DecimalSerialized,
4182    /// The new balance of the personal position after the purchase and deposit.
4183    pub new_personal_position_balance: u64,
4184}
4185
4186/// Snapshot of the complete state of a market at a specific point in time.
4187/// This struct captures all relevant market data for off-chain analysis and record-keeping.
4188#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4189pub struct MarketStateSnapshot {
4190    /// The market metadata account address for this market.
4191    /// This is the PDA that stores configuration and references to all associated accounts.
4192    pub market_metadata_address: Pubkey,
4193    /// Total amount of market tokens deposited as collateral across all personal positions.
4194    /// These tokens are held in escrow and can be withdrawn if debt obligations are met.
4195    pub total_market_deposited_collateral: u64,
4196    /// Total amount of main tokens (e.g., USDC, SOL) in the market's liquidity pool.
4197    /// This is the reserve available for purchases, borrows, and redemptions.
4198    pub total_main_token_in_liquidity_pool: u64,
4199    /// Total debt owed to the market across all personal positions.
4200    /// Represents main tokens that were borrowed and must be repaid.
4201    pub total_market_debt: u64,
4202    /// The floor price of the market (minimum price at supply = 0).
4203    /// This is the lowest price at which tokens can be sold back to the market.
4204    pub floor_price: DecimalSerialized,
4205    /// The current market price (marginal price at current supply).
4206    /// This is the price for buying the next infinitesimal amount of tokens.
4207    pub market_price: DecimalSerialized,
4208    /// The area under the price curve from 0 to current supply.
4209    /// Measured in token units, represents the total value locked in the curve.
4210    pub area_under_curve: u64,
4211    /// Total supply of market tokens currently minted and in circulation.
4212    /// This includes tokens in personal positions (collateral) and tokens held by traders.
4213    pub token_supply: u64,
4214    /// Unix timestamp (in seconds) when this snapshot was created.
4215    pub unix_timestamp: u64,
4216}
4217
4218#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4219pub struct SellWithExactTokenInAfterWithdrawEvent {
4220    /// The account that sold tokens back to the market.
4221    pub trader: Pubkey,
4222    /// The address of the market metadata account.
4223    pub market_meta: Pubkey,
4224    /// The amount of market tokens burned in the sale.
4225    pub token_in: u64,
4226    /// The amount of main tokens received by the trader after fees.
4227    /// This is the net amount transferred to the trader.
4228    pub net_cash_out: u64,
4229    /// The fee amount allocated to the platform.
4230    pub fee_platform: u64,
4231    /// The fee amount allocated to the market group admin.
4232    pub fee_market_group: u64,
4233    /// The new balance of the personal position
4234    pub new_personal_position_balance: u64,
4235    /// The address of the personal position account.
4236    pub personal_position: Pubkey,
4237    /// The new market price after the sell.
4238    pub new_market_price: DecimalSerialized,
4239}
4240
4241#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4242pub struct ModifyCurveArgs {
4243    /// The multiplier to apply to the curve (between 0.0 and 1.0)
4244    pub multiplier: f32,
4245    /// The new number of middle segments
4246    pub new_middle_segment_count: u8,
4247    /// If true, the sensitivity direction is higher, otherwise it is lower
4248    pub increase: bool,
4249}
4250
4251#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4252pub struct MultiMarketInitWithDutchArgs {
4253    pub shoulder_slope_scalar: f64,
4254    pub main_slope: f64,
4255    pub f: f32,
4256    pub start_time: u64,
4257    pub dutch_config: DutchConfigSerialized,
4258    pub permissions: MarketPermissions,
4259}
4260
4261#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4262pub struct RaiseFloorPreserveAreaCheckedMultiArgs {
4263    /// The ratio of the floor increase (greater than 0.0)
4264    pub floor_increase_ratio: DecimalSerialized,
4265    /// The new shoulder end (must be greater than the current shoulder end)
4266    pub new_shoulder_end: u64,
4267    /// The minimum liquidity ratio (greater than or equal to 0.0)
4268    /// This is the ratio of the liqudity after the shoulder end to the liquidity of the shoulder
4269    pub min_liq_ratio: DecimalSerialized,
4270    /// If true, there was no way to raise the floor without backtracking from a vertex,
4271    /// extending the a neighbor segment backwards
4272    ///
4273    /// This happens if the shoulder must sweep forward over segments that increase in slope
4274    /// and there is no solution, since the shoulder slope increases when it intersects the new higher slope
4275    /// the area under the curve would be too small
4276    pub must_backtrack: bool,
4277}
4278
4279#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4280pub struct BuyWithExactCashInAndDepositWithDebtArgs {
4281    /// Exact amount of cash to spend on tokens
4282    pub exact_cash_in: u64,
4283    /// Minimum acceptable tokens to receive (slippage protection)
4284    pub min_token_received: u64,
4285    /// New debt amount to take on
4286    pub new_acquired_debt: u64,
4287}
4288
4289#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4290pub struct MarketLinearInitWithDutchArgs {
4291    pub x2: u64,
4292    pub m2: DecimalSerialized,
4293    pub m1: DecimalSerialized,
4294    pub f: DecimalSerialized,
4295    pub b2: DecimalSerialized,
4296    pub start_time: u64,
4297    pub dutch_config: DutchConfigSerialized,
4298    pub permissions: MarketPermissions,
4299}
4300
4301#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4302pub struct MarketLinearArgs {
4303    pub x2: u64,
4304    pub m2: DecimalSerialized,
4305    pub m1: DecimalSerialized,
4306    pub f: DecimalSerialized,
4307    pub b2: DecimalSerialized,
4308}
4309
4310/// Arguments for initializing a market with Dutch auction and token scaling support.
4311#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4312pub struct MarketSimpleInitV2Args {
4313    /// Slope of the main segment after the shoulder.
4314    pub m2: DecimalSerialized,
4315    /// Multiplier for the m1 slope as a percentage of m2.
4316    /// must be greater than 100u32
4317    pub m1_multiplier_percent: u32,
4318    /// Floor price - minimum price the token can trade at.
4319    pub f: DecimalSerialized,
4320    /// Unix timestamp when trading begins (0 for immediate).
4321    pub start_time: u64,
4322    /// Dutch auction configuration for launch price boost.
4323    pub dutch_config: DutchConfigSerialized,
4324    /// Market permissions (buy, sell, borrow, etc.).
4325    pub permissions: MarketPermissions,
4326    /// Token unit scale factor (power of 2).
4327    /// Controls the ratio between token units and curve units.
4328    /// - 0: 1 token = 1 curve unit (default)
4329    /// - positive: 2^scale tokens = 1 curve unit
4330    /// - negative: 1 token = 2^|scale| curve units
4331    pub token_unit_scale: i8,
4332}
4333
4334#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4335pub struct RaiseFloorFromExcessLiquidityCheckedArgs {
4336    /// the maximum new floor that is allowed
4337    pub max_new_floor: DecimalSerialized,
4338    /// the amount to increase the floor by
4339    pub increase_ratio_micro_basis_points: u32,
4340}
4341
4342#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4343pub struct RaiseFloorPreserveAreaCheckedArgs2 {
4344    /// The maximum new floor price (must be greater than the current floor)
4345    pub max_new_floor: DecimalSerialized,
4346    /// The increase ratio
4347    pub floor_increase_ratio: DecimalSerialized,
4348    /// The new shoulder end (must be greater than the current shoulder end)
4349    pub new_shoulder_end: u64,
4350    /// The minimum liquidity ratio (greater than or equal to 0.0)
4351    /// This is the ratio of the liqudity after the shoulder end to the liquidity of the shoulder
4352    /// if the ratio is 0.0, then the floor is permitted to rise such that the new shoulder is equal to supply
4353    pub min_liq_ratio: DecimalSerialized,
4354    /// the maximum token units that the total area of the curve is allowed to shrink by
4355    /// this is set by the client to restrict overly aggressive floor raising, with a tolerance to account for "slippage"
4356    pub max_area_shrinkage_tolerance_units: u64,
4357}
4358
4359#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4360pub struct RaiseFloorPreserveAreaCheckedArgs {
4361    /// The ratio of the floor increase (greater than 0.0)
4362    pub floor_increase_ratio: DecimalSerialized,
4363    /// The new shoulder end (must be greater than the current shoulder end)
4364    pub new_shoulder_end: u64,
4365    /// The minimum liquidity ratio (greater than or equal to 0.0)
4366    /// This is the ratio of the liqudity after the shoulder end to the liquidity of the shoulder
4367    pub min_liq_ratio: DecimalSerialized,
4368}
4369
4370#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4371pub struct WithdrawSellAndRepayArgs {
4372    /// Amount of collateral to withdraw and sell
4373    pub collateral_reduce_by: u64,
4374    /// Amount of debt to repay from sale proceeds
4375    pub debt_reduce_by: u64,
4376    /// Minimum cash to receive after repaying debt (slippage protection)
4377    pub min_cash_to_user: u64,
4378}
4379
4380#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4381pub struct MarketGroupInitArgs {
4382    pub fees: Fees,
4383    pub group_admin: Pubkey,
4384}
4385
4386/// Wrapper for serializing and deserializing high-precision decimal values.
4387///
4388/// Solana accounts require all data to be serialized as bytes. This struct provides
4389/// a bridge between Rust's Decimal type (used for precise financial calculations)
4390/// and the byte array representation stored on-chain.
4391///
4392/// # Usage
4393/// - Serialize: Convert Decimal to 16-byte array for storage
4394/// - Deserialize: Reconstruct Decimal from stored bytes
4395/// - Preserves full decimal precision across serialization
4396///
4397/// # Why This Matters
4398/// Financial calculations require high precision to avoid rounding errors that could
4399/// accumulate over thousands of transactions. The 16-byte representation maintains
4400/// the full 128-bit precision of the Decimal type.
4401#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4402pub struct DecimalSerialized {
4403    /// Serialized Decimal value as a 16-byte array.
4404    /// Used for storing fixed-point decimal numbers in Solana accounts.
4405    pub val: [u8; 16],
4406}
4407
4408/// Metadata for Program Derived Address (PDA) accounts.
4409///
4410/// PDAs are deterministically derived addresses that can only be controlled by the program.
4411/// This struct stores the components needed to derive and verify PDA addresses, enabling
4412/// efficient Cross-Program Invocations (CPIs) without recomputing the address.
4413///
4414/// # PDA Derivation
4415/// Solana PDAs are derived from:
4416/// 1. A string seed (defined per account type)
4417/// 2. A unique seed (usually a Pubkey)
4418/// 3. A bump seed (ensures the address is off-curve)
4419///
4420/// # Performance Optimization
4421/// Storing the bump seed avoids expensive recomputation during CPIs, as finding the bump
4422/// requires iterating through possible values until finding one that produces an off-curve point.
4423///
4424/// # Security
4425/// PDAs cannot be controlled by external signers, making them ideal for program-controlled
4426/// accounts like escrows, vaults, and authority accounts.
4427#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4428pub struct PdaMeta {
4429    /// The PDA bump seed used to derive the account address.
4430    /// Stored to enable efficient CPI calls without recomputation.
4431    pub bump: [u8; 1],
4432    /// The seed public key used as input to the PDA derivation.
4433    /// Combined with string seeds and bump to create unique addresses.
4434    pub seed: Pubkey,
4435}
4436
4437/// Fee configuration structure for market operations within a market group.
4438///
4439/// All fees are denominated in micro-basis points (micro-bps), where:
4440/// - 1 micro-bp = 1/100 of a basis point = 0.0001%
4441/// - 100 micro-bps = 1 basis point = 0.01%
4442/// - 10,000 micro-bps = 100 basis points = 1%
4443///
4444/// This granular fee precision allows for fine-tuned economic models while maintaining
4445/// integer arithmetic for computational efficiency on-chain.
4446///
4447/// # Example
4448/// A buy fee of 250 micro-bps equals 2.5 basis points or 0.025% of the transaction amount.
4449#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4450pub struct Fees {
4451    /// Fee charged when buying tokens from the market (in micro basis points).
4452    /// Applied to the purchase amount before tokens are transferred.
4453    pub buy: u32,
4454    /// Fee charged when selling tokens back to the market (in micro basis points).
4455    /// Applied to the sale proceeds before main tokens are transferred.
4456    pub sell: u32,
4457    /// Fee charged when borrowing against collateral (in micro basis points).
4458    /// Applied to the borrowed amount at the time of borrowing.
4459    pub borrow: u32,
4460    /// Fee charged when exercising options to purchase tokens (in micro basis points).
4461    /// Applied to the option exercise amount.
4462    pub exercise_option: u32,
4463}
4464
4465/// Serialized representation of a linear bonding curve with shoulder configuration.
4466///
4467/// This structure stores the parameters that define a two-segment linear price curve.
4468/// The curve provides higher prices at low supply (shoulder) and more gradual price
4469/// increases at higher supply (tail), creating favorable conditions for early participants
4470/// while maintaining sustainable economics at scale.
4471///
4472/// # Curve Equation
4473/// ```text
4474/// if x < x2 (shoulder region):
4475/// price = floor + m1 * x
4476/// else (tail region):
4477/// price = floor + m2 * x + b2
4478/// ```
4479///
4480/// # Parameters
4481/// - `floor`: Minimum price guarantee
4482/// - `m1`: Shoulder slope (typically steeper)
4483/// - `m2`: Tail slope (typically gentler)
4484/// - `x2`: Transition point from shoulder to tail
4485/// - `b2`: Y-intercept adjustment for tail segment continuity
4486#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4487pub struct LinearPriceCurveSerialized {
4488    /// Minimum price floor for the token (serialized Decimal).
4489    /// Price cannot fall below this value regardless of supply.
4490    /// DIMENSIONLESS - no scaling
4491    pub floor: [u8; 16],
4492    /// Slope of the shoulder segment (m1, serialized Decimal).
4493    /// Steeper initial slope providing higher prices at low supply.
4494    /// SCALED by market meta 2^token_unit_scale
4495    pub m1: [u8; 16],
4496    /// Slope of the main segment (m2, serialized Decimal).
4497    /// Gentler slope for bulk of the curve after shoulder point.
4498    /// SCALED by market meta 2^token_unit_scale
4499    pub m2: [u8; 16],
4500    /// X-coordinate where shoulder transitions to main slope (supply units).
4501    /// Defines the breakpoint between steep and gentle price curves.
4502    /// NOT SCALED - stored in raw token units
4503    pub x2: u64,
4504    /// Y-intercept of the main segment (b2, serialized Decimal).
4505    /// Determines vertical offset of the main price curve.
4506    /// DIMENSIONLESS - no scaling
4507    pub b2: [u8; 16],
4508}
4509
4510/// Bitfield structure managing market operation permissions.
4511///
4512/// Uses a compact 16-bit representation where each bit corresponds to a specific
4513/// market operation. This allows for efficient storage and checking of multiple
4514/// permissions simultaneously. All permissions default to enabled (0xFFFF) for
4515/// new markets.
4516///
4517/// # Permission Management
4518/// - Individual bits can be toggled without affecting others
4519/// - Permissions are checked before each corresponding operation
4520/// - Failed permission checks return specific error codes for debugging
4521#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4522pub struct MarketPermissions {
4523    /// Bitfield value storing all permission flags.
4524    /// Each bit represents a different permission from the MarketPermission enum.
4525    pub val: u16,
4526}
4527
4528/// Configuration for Dutch auction fee boost mechanism.
4529///
4530/// Implements a time-decaying fee boost that increases trading fees immediately
4531/// after market launch, gradually decreasing to normal fees over the auction duration.
4532/// This mechanism incentivizes early liquidity provision and helps with price discovery.
4533///
4534/// # Auction Mechanics
4535/// The boost follows an exponential decay curve and scales with remaining fee space:
4536/// - Maximum fee boost (`init_boost`) at t=0 (market launch)
4537/// - Boost scales with remaining space: `effective_fee = base_fee + boost * (1 - base_fee)`
4538/// - This ensures effective_fee never exceeds 100% regardless of configuration
4539/// - Gradually decreases over `duration` seconds
4540/// - Curvature parameter controls the decay shape
4541/// - Boost reaches 0 after duration expires
4542///
4543/// # Example
4544/// With base_fee = 5% and init_boost = 0.50 (50%):
4545/// - remaining_space = 100% - 5% = 95%
4546/// - scaled_boost = 50% × 95% = 47.5%
4547/// - effective_fee = 5% + 47.5% = 52.5%
4548///
4549/// # Safety
4550/// All float parameters are validated to prevent NaN, infinity, and overflow conditions
4551/// that could compromise market operations. init_boost must be in range [0, 1.0).
4552/// The scaling mechanism guarantees effective fees stay bounded regardless of configuration.
4553#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4554pub struct DutchConfigSerialized {
4555    /// Initial fee boost value representing fraction of remaining fee space to consume.
4556    /// Must be in range [0, 1.0) and gradually decays to 0 over the auction duration.
4557    /// Example: init_boost = 0.50 with base_fee = 5% → effective_fee = 5% + 50% × 95% = 52.5%
4558    pub init_boost: f64,
4559    /// Duration of the Dutch auction in seconds.
4560    /// After this period, the boost reaches 0 and normal pricing applies.
4561    pub duration: u32,
4562    /// Curvature parameter controlling the decay rate of the boost.
4563    /// Higher values create steeper initial drops and slower final decay.
4564    pub curvature: f64,
4565}
4566
4567/// Serialized representation of a single linear segment in a multi-segment curve.
4568///
4569/// Each segment defines a linear price function over a specific supply range,
4570/// with seamless transitions to adjacent segments ensuring price continuity.
4571#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4572pub struct SegmentSerialized {
4573    /// Starting X-coordinate of this segment (serialized Decimal).
4574    /// Represents the supply level where this segment begins.
4575    pub start: [u8; 16],
4576    /// Ending X-coordinate of this segment (serialized Decimal).
4577    /// Represents the supply level where this segment ends.
4578    pub end: [u8; 16],
4579    /// Slope of this linear segment (serialized Decimal).
4580    /// Determines how quickly price changes with supply in this range.
4581    pub m: [u8; 16],
4582    /// Y-intercept of this segment (serialized Decimal).
4583    /// Base price offset for the linear equation y = mx + b.
4584    pub b: [u8; 16],
4585}
4586
4587/// Serialized representation of a multi-segment bonding curve with adaptive complexity.
4588///
4589/// This structure enables sophisticated price curves that can evolve over time while
4590/// maintaining important invariants like area-under-curve preservation. The curve
4591/// consists of an initial shoulder region, optional middle segments, and a final
4592/// tail segment extending to maximum supply.
4593///
4594/// # Curve Evolution
4595/// The curve starts simple (shoulder + tail) but gains complexity when:
4596/// - Floor price is raised (adds middle segments)
4597/// - Market conditions require price curve adjustments
4598/// - Area preservation constraints need to be maintained
4599///
4600/// # Segment Organization
4601/// 1. Implicit shoulder: [0, shoulder_end] with slope = final_segment.m * shoulder_slope_scalar
4602/// 2. Middle segments: Variable-length array for intermediate price regions
4603/// 3. Final segment: Extends from last middle segment (or shoulder) to u64::MAX
4604#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4605pub struct MultiPriceCurveSerialized {
4606    /// Minimum price floor for the token (serialized Decimal).
4607    /// Price cannot fall below this value regardless of supply.
4608    pub floor_height: [u8; 16],
4609    /// Multiplier for shoulder slope relative to neighboring segment (serialized Decimal).
4610    /// Creates steeper initial pricing for early adopters.
4611    pub shoulder_slope_scalar: [u8; 16],
4612    /// Variable-length array of middle curve segments.
4613    /// Empty for simple curves, populated when floor is raised.
4614    pub middle_segments: Vec<SegmentSerialized>,
4615    /// The main segment extending to maximum supply (u64::MAX).
4616    /// Defines the long-tail pricing behavior of the market.
4617    pub final_segment: SegmentSerialized,
4618}
4619
4620/// Dynamic state tracking for market operations and accounting.
4621///
4622/// MarketState maintains all mutable values that change during market operations,
4623/// separate from the static configuration in MarketMeta and the price curve parameters.
4624/// This separation allows for efficient state updates without modifying larger structures.
4625///
4626/// # State Components
4627/// - **Token Supply**: Total minted tokens in circulation
4628/// - **Cash Liquidity**: Available main token (e.g., USDC) for operations
4629/// - **Debt**: Total borrowed amount across all positions
4630/// - **Collateral**: Total deposited tokens used as collateral
4631/// - **Revenue**: Cumulative fees collected for market group and tenant
4632///
4633/// # Accounting Invariants
4634/// The state maintains several important invariants:
4635/// - Token supply reflects actual minted tokens
4636/// - Cash liquidity equals vault balance minus outstanding debt
4637/// - Total debt equals sum of all individual position debts
4638/// - Total collateral equals sum of all position collateral deposits
4639///
4640/// # Revenue Distribution
4641/// Fees collected from market operations are tracked separately for:
4642/// - Market group admin (receives majority of fees)
4643/// - Tenant platform (receives platform fee percentage)
4644#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4645pub struct MarketState {
4646    /// Total supply of tokens minted by this market.
4647    /// Increases when users buy tokens, decreases when tokens are sold back.
4648    pub token_supply: u64,
4649    /// Total amount of main token (cash) held in the market's liquidity vault.
4650    /// Represents available liquidity for sells and borrows.
4651    pub total_cash_liquidity: u64,
4652    /// Total outstanding debt across all borrowers in this market.
4653    /// Sum of all individual borrow positions.
4654    pub total_debt: u64,
4655    /// Total token collateral deposited across all positions in this market.
4656    /// Sum of all individual collateral deposits.
4657    pub total_collateral: u64,
4658    /// Cumulative revenue earned by the market group (in main token units).
4659    /// Tracks total fees collected for the market group admin.
4660    pub cumulative_revenue_market: u128,
4661    /// Cumulative revenue earned by the tenant (in main token units).
4662    /// Tracks platform fees collected for the tenant.
4663    pub cumulative_revenue_tenant: u128,
4664}
4665
4666#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4667pub enum MultiMarketInitValidationError {
4668    ShoulderSlopeScalarNotGreaterThanOne,
4669    ShoulderSlopeScalarNotFinite,
4670    MainSlopeNotPositive,
4671    MainSlopeNotFinite,
4672    FloorNotPositive,
4673    FloorNotFinite,
4674    DutchConfigValidationError(/* Complex fields */),
4675}
4676
4677#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4678pub enum MarketLinearInitValidationError {
4679    M2MustBeGreaterThanZero,
4680    M1MustBeGreaterThanM2,
4681    FMustBeGreaterThanZero,
4682    InvalidCurveParameters,
4683}
4684
4685#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4686pub enum FeeBoundsError {
4687    GreaterThanOne,
4688}
4689
4690#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4691pub enum SetFeeError {
4692    NegativeFee,
4693    GreaterThanOne,
4694}
4695
4696#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4697pub enum DutchConfigValidationError {
4698    InitBoostNotPositive,
4699    CurvatureZero,
4700    CurvatureNegative,
4701    InitBoostInfinity,
4702    InitBoostNaN,
4703    CurvatureInfinity,
4704    CurvatureNaN,
4705    InitBoostTooLarge,
4706    CurvatureTooLarge,
4707    DurationZero,
4708    InvalidParameters,
4709}
4710
4711#[derive(Clone, Debug, AnchorSerialize, AnchorDeserialize)]
4712pub enum FullOrPartialU64 {
4713    Full,
4714    Partial(u64),
4715}
4716
4717pub type MicroBasisPoints = u32;
4718
4719// Event structures
4720#[event]
4721pub struct BorrowEvent {
4722    pub fee_market_group: u64,
4723    pub fee_tenant: u64,
4724    pub net_cash_out: u64,
4725    pub new_debt: u64,
4726    pub personal_position_owner: Pubkey,
4727    pub personal_position_address: Pubkey,
4728    pub market_state_snapshot: MarketStateSnapshot,
4729}
4730
4731#[event]
4732pub struct BuyEvent {
4733    pub trader: Pubkey,
4734    pub token_out: u64,
4735    pub net_cash_in: u64,
4736    pub fee_market_group: u64,
4737    pub fee_tenant: u64,
4738    pub market_state_snapshot: MarketStateSnapshot,
4739}
4740
4741#[event]
4742pub struct BuyWithExactCashInAndDepositWithDebtEvent {
4743    pub personal_position_owner: Pubkey,
4744    pub personal_position: Pubkey,
4745    pub trader: Pubkey,
4746    pub net_cash_spent: u64,
4747    pub trader_cash_spend: u64,
4748    pub newly_acquired_debt: u64,
4749    pub token_out: u64,
4750    pub new_personal_position_collateral: u64,
4751    pub new_personal_position_debt: u64,
4752    pub fee_market_group_borrow: u64,
4753    pub fee_market_group_buy: u64,
4754    pub fee_platform_borrow: u64,
4755    pub fee_platform_buy: u64,
4756    pub market_state_snapshot: MarketStateSnapshot,
4757}
4758
4759#[event]
4760pub struct DepositEvent {
4761    pub payer: Pubkey,
4762    pub personal_position_address: Pubkey,
4763    pub amount: u64,
4764    pub new_balance: u64,
4765    pub market_state_snapshot: MarketStateSnapshot,
4766}
4767
4768#[event]
4769pub struct ExerciseOptionsEvent {
4770    pub owner: Pubkey,
4771    pub amount: u64,
4772    pub fee_tenant: u64,
4773    pub fee_market_group: u64,
4774    pub market_state_snapshot: MarketStateSnapshot,
4775}
4776
4777#[event]
4778pub struct RedeemAtFloorEvent {
4779    pub trader: Pubkey,
4780    pub token_in: u64,
4781    pub fee_platform: u64,
4782    pub fee_market_group: u64,
4783    pub net_cash_out: u64,
4784    pub market_state_snapshot: MarketStateSnapshot,
4785}
4786
4787#[event]
4788pub struct RepayEvent {
4789    pub repayer: Pubkey,
4790    pub personal_position_owner: Pubkey,
4791    pub personal_position_address: Pubkey,
4792    pub amount: u64,
4793    pub new_debt: u64,
4794    pub market_state_snapshot: MarketStateSnapshot,
4795}
4796
4797#[event]
4798pub struct SellWithExactTokenInEvent {
4799    pub trader: Pubkey,
4800    pub token_in: u64,
4801    pub actual_cash_out: u64,
4802    pub fee_platform: u64,
4803    pub fee_market_group: u64,
4804    pub market_state_snapshot: MarketStateSnapshot,
4805}
4806
4807#[event]
4808pub struct WithdrawEvent {
4809    pub personal_position_owner: Pubkey,
4810    pub personal_position_address: Pubkey,
4811    pub amount: u64,
4812    pub new_balance: u64,
4813    pub market_state_snapshot: MarketStateSnapshot,
4814}
4815
4816#[event]
4817pub struct WithdrawSellAndRepayEvent {
4818    pub personal_position_owner: Pubkey,
4819    pub personal_position_address: Pubkey,
4820    pub fee_to_platform: u64,
4821    pub fee_to_market_group: u64,
4822    pub cash_to_user: u64,
4823    pub collateral_sold: u64,
4824    pub debt_repaid: u64,
4825    pub new_personal_position_collateral_balance: u64,
4826    pub new_personal_position_debt_balance: u64,
4827    pub market_state_snapshot: MarketStateSnapshot,
4828}
4829
4830#[event]
4831pub struct DonateLiquidityEvent {
4832    pub payer: Pubkey,
4833    pub market_meta: Pubkey,
4834    pub new_cash_balance: u64,
4835    pub amount: u64,
4836}
4837
4838#[event]
4839pub struct MarketLinearInitEvent {
4840    pub market_meta: Pubkey,
4841    pub market_state: Pubkey,
4842    pub group: Pubkey,
4843}
4844
4845#[event]
4846pub struct RaiseFloorFromExcessLiquidity2Event {
4847    pub market_meta: Pubkey,
4848    pub prev_floor: DecimalSerialized,
4849    pub new_floor: DecimalSerialized,
4850    pub new_area_under_curve: u64,
4851    pub prev_area_under_curve: u64,
4852    pub total_liquidity: u64,
4853}
4854
4855#[event]
4856pub struct RaiseFloorFromExcessLiquidityEvent {
4857    pub market_meta: Pubkey,
4858    pub new_floor: DecimalSerialized,
4859    pub new_area_under_curve: u64,
4860}
4861
4862#[event]
4863pub struct RaiseFloorFromTriggerEvent {
4864    pub market_meta: Pubkey,
4865    pub new_floor: DecimalSerialized,
4866    pub new_shoulder_end: u64,
4867    pub new_area: u64,
4868    pub prev_area: u64,
4869}
4870
4871#[event]
4872pub struct RaiseFloorPreserveAreaChecked2Event {
4873    pub market_meta: Pubkey,
4874    pub new_floor: DecimalSerialized,
4875    pub new_shoulder_end: u64,
4876    pub new_liq_ratio: DecimalSerialized,
4877    pub prev_area: u64,
4878    pub new_area: u64,
4879}
4880
4881#[event]
4882pub struct RaiseFloorPreserveAreaCheckedEvent {
4883    pub new_floor: DecimalSerialized,
4884    pub new_shoulder_end: u64,
4885    pub new_liq_ratio: DecimalSerialized,
4886}
4887
4888#[event]
4889pub struct MarketFlagsChangeEvent {
4890    pub market_meta: Pubkey,
4891    pub new_flags: MarketPermissions,
4892}
4893
4894#[event]
4895pub struct MarketGroupAcceptNewAdminEvent {
4896    pub market_group: Pubkey,
4897    pub new_admin: Pubkey,
4898}
4899
4900#[event]
4901pub struct MarketGroupChangeFeesEvent {
4902    pub market_group: Pubkey,
4903    pub new_fees: Fees,
4904}
4905
4906#[event]
4907pub struct MarketGroupCollectRevEvent {
4908    pub market_meta: Pubkey,
4909    pub amount: u64,
4910    pub to: Pubkey,
4911}
4912
4913#[event]
4914pub struct MarketGroupInitialized {
4915    pub tenant: Pubkey,
4916    pub market_group_seed: Pubkey,
4917    pub group_admin: Pubkey,
4918    pub fees: Fees,
4919}
4920
4921#[event]
4922pub struct MarketGroupProposeAdminEvent {
4923    pub market_group: Pubkey,
4924    pub new_admin: Pubkey,
4925}
4926
4927#[event]
4928pub struct MintOptionsEvent {
4929    pub market_meta: Pubkey,
4930    pub options_dst: Pubkey,
4931    pub amount: u64,
4932}
4933
4934#[event]
4935pub struct PersonalPositionInitEvent {
4936    pub market_meta: Pubkey,
4937    pub payer: Pubkey,
4938    pub owner: Pubkey,
4939    pub personal_position: Pubkey,
4940}
4941
4942#[event]
4943pub struct TenantAcceptNewAdminEvent {
4944    pub tenant: Pubkey,
4945    pub new_admin: Pubkey,
4946}
4947
4948#[event]
4949pub struct TenantChangeFeeMbpsEvent {
4950    pub tenant: Pubkey,
4951    pub fee_micro_bps: u32,
4952}
4953
4954#[event]
4955pub struct TenantCollectRevEvent {
4956    pub market_meta: Pubkey,
4957    pub amount: u64,
4958    pub to: Pubkey,
4959}
4960
4961#[event]
4962pub struct TenantInitialized {
4963    pub tenant_seed: Pubkey,
4964    pub admin: Pubkey,
4965    pub fee_micro_bps: u32,
4966    pub permissionless_group_creation: bool,
4967}
4968
4969#[event]
4970pub struct TenantProposeAdminEvent {
4971    pub tenant: Pubkey,
4972    pub new_admin: Pubkey,
4973}
4974
4975#[event]
4976pub struct TestLogEvent {
4977    pub payer: Pubkey,
4978    pub log_account: Pubkey,
4979    pub data: u64,
4980}
4981
4982#[event]
4983pub struct MarketSnapshotEvent {
4984    pub market_state_snapshot: MarketStateSnapshot,
4985}