### Example Liquidity Configuration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md An example of a 2-segment bonding curve configuration with specific liquidity distribution percentages for partners and creators. This demonstrates how to set the starting price, curve segments, and LP split percentages. ```rust sqrt_start_price: 100_000_000_000_000_000 curve: [ { sqrt_price: 100_000_000_000_000_000, liquidity: 1000 }, { sqrt_price: 141_421_356_237_309_505, liquidity: 2000 }, ] partner_liquidity_percentage: 25 partner_permanent_locked_liquidity_percentage: 25 creator_liquidity_percentage: 50 creator_permanent_locked_liquidity_percentage: 0 ``` -------------------------------- ### Rust Swap Example Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Example of how to execute a swap using the `swap` instruction. This example swaps 1000 base tokens for a minimum of 800 quote tokens. ```rust // Swap 1000 base tokens for minimum 800 quote tokens let params = SwapParameters { amount_in: 1000, minimum_amount_out: 800, }; invoke( &dynamic_bonding_curve::swap(accounts, params), signers )?; ``` -------------------------------- ### Install Dependencies and Build Local Test Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/README.md Commands to install project dependencies using Bun and then build the local test environment. Ensure Bun is installed before running these commands. ```bash bun install bun run build-local-test ``` -------------------------------- ### Token Configuration Example Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md Shows how to configure a Token2022 token with specific decimal places and creator-controlled metadata and minting authority. This is suitable for new token deployments requiring flexibility. ```rust token_type: 1 token_decimal: 9 token_update_authority: 3 // creator can update metadata and mint ``` -------------------------------- ### Example Vesting Schedule Configuration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md An example of a 2-year vesting schedule with a 6-month cliff, configured using timestamp-based activation. This shows how to set the cliff duration, period frequency, total periods, and unlock amounts. ```rust activation_type: 1 locked_vesting: { cliff_duration_from_migration_time: 15_768_000, frequency: 15_768_000, number_of_period: 4, cliff_unlock_amount: 250_000, amount_per_period: 187_500, } ``` -------------------------------- ### Example Fee and Incentive Configuration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md Configure protocol fees and incentives, including the pool creation fee, whether to enable a reduced fee for the creator's first swap, and the compounding fee in basis points. Ensure compounding fee is within 0-10000. ```rust pool_creation_fee: 500_000_000 enable_first_swap_with_min_fee: true compounding_fee_bps: 100 ``` -------------------------------- ### Migration Configuration Example Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md Demonstrates migrating to DAMM v2 with a specified quote threshold and a 2% migration fee, where the creator receives 50% of the migration fee. Use this for migrating existing pools to the newer DAMM version. ```rust migration_option: 1 migration_quote_threshold: 1000_000_000 // 1000 USDC (assuming 6 decimals) migration_fee_option: 3 // 2% fee tier migration_fee: { fee_percentage: 2, creator_fee_percentage: 50 // creator gets 50% of 2% fee } ``` -------------------------------- ### Example Pool Fee Configuration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md Illustrates a pool fee configuration with a 0.5% base fee and linear reduction. Use this when setting up a pool with a predictable fee reduction schedule. ```rust base_fee_mode: 0 cliff_fee_numerator: 50 reduction_factor: 5 // reduce by 5 basis points per period activation_timestamp: ``` -------------------------------- ### Usage Example for PoolMetrics Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/state-accounts.md Demonstrates how to access and use the PoolMetrics account to calculate the average swap size in base tokens. Ensures division by zero is avoided by using `.max(1)`. ```rust // Get pool metrics let metrics = &pool.metrics; let avg_swap_size = metrics.total_base_swap_amount / metrics.swap_count.max(1); println!("Average swap: {} base tokens", avg_swap_size); ``` -------------------------------- ### Rust Function Signature Example Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Illustrates a typical Rust function signature used for instructions within the program. Pay attention to the context and parameter types. ```rust pub fn instruction_name( ctx: Context, param_name: ParamType, ) -> Result<()> ``` -------------------------------- ### Get Best Price using Quote Exact In Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Fetches on-chain pool and config data, then uses `quote_exact_in` to determine the output amount for a given input amount. Requires Solana RPC client and SDK imports. The `is_base_for_quote` parameter determines the direction of the quote. ```rust use dynamic_bonding_curve_sdk::{quote_exact_in, quote_exact_out, quote_partial_fill}; use dynamic_bonding_curve::state::{PoolState, PoolConfig}; use solana_client::rpc_client::RpcClient; use std::str::FromStr; async fn get_best_price( client: &RpcClient, pool_pubkey: &Pubkey, config_pubkey: &Pubkey, swap_amount: u64, is_base_for_quote: bool, ) -> Result> { // Fetch on-chain accounts let pool_account = client.get_account(pool_pubkey)?; let config_account = client.get_account(config_pubkey)?; let pool: PoolState = PoolState::try_deserialize(&mut &pool_account.data[..])?; let config: PoolConfig = PoolConfig::try_deserialize(&mut &config_account.data[..])?; // Get current time let clock = client.get_clock()?; let slot = client.get_slot()?; // Quote swap let result = quote_exact_in( &pool, &config, is_base_for_quote, clock.unix_timestamp as u64, slot, swap_amount, false, false, )?; Ok(result.amount_1_delta.abs() as u64) } ``` -------------------------------- ### Instruction Dependencies for Pool Creation, Fee Claiming, and Migration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Maps out the sequential steps and dependencies for core operations including pool creation, fee claiming, and asset migration. ```text Pool Creation Flow: 1. create_config ↓ 2. initialize_virtual_pool_with_spl_token ↓ 3. create_virtual_pool_metadata (optional) Fee Claiming Flow: 1. swap (accumulates fees) ↓ 2. claim_trading_fee2 / claim_creator_trading_fee2 ↓ 3. partner_withdraw_surplus / creator_withdraw_surplus Migration Flow: 1. quote_reserve reaches migration_quote_threshold ↓ 2. create_locker ↓ 3. migration_damm_v2 ↓ 4. migrate_*_lock_lp_token ↓ 5. migrate_*_claim_lp_token (after vesting) ``` -------------------------------- ### Create Pool Configuration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md This snippet demonstrates how to create a comprehensive pool configuration object for a dynamic bonding curve. It includes settings for fees, tokens, migration, liquidity, vesting, and other parameters. Use this when initializing a new pool. ```rust let config_params = ConfigParameters { // Fee configuration (0.5% base fee, linear reduction) pool_fees: PoolFeeParameters { base_fee: BaseFeeParameters { base_fee_mode: 0, // linear cliff_fee_numerator: 50, // 0.5% reduction_factor: 5, // 5 bps/period activation_timestamp: clock.unix_timestamp as u64, }, dynamic_fee: DynamicFeeConfig { dynamic_fee_enabled: 0, // disabled max_dynamic_fee_numerator: 0, sqrt_price_change_volatility_threshold: 0, }, }, // Token configuration token_type: 0, // SPL Token token_decimal: 9, token_update_authority: 0, // creator can update token_supply: None, // Migration configuration migration_option: 1, // DAMM v2 migration_quote_threshold: 1000_000_000_000, // 1T USDC migration_fee_option: 3, // 2% migration_fee: MigrationFee { fee_percentage: 2, creator_fee_percentage: 50, }, // Liquidity configuration sqrt_start_price: 1_000_000_000_000_000_000, curve: vec![ LiquidityDistributionParameters { sqrt_price: 1_000_000_000_000_000_000, liquidity: 1000, }, LiquidityDistributionParameters { sqrt_price: 1_414_213_562_373_095_048, // 2x liquidity: 2000, }, ], partner_liquidity_percentage: 30, partner_permanent_locked_liquidity_percentage: 20, creator_liquidity_percentage: 50, creator_permanent_locked_liquidity_percentage: 0, // Time and vesting activation_type: 1, // timestamp-based locked_vesting: LockedVestingParams { cliff_duration_from_migration_time: 7_776_000, // 90 days frequency: 7_776_000, number_of_period: 4, cliff_unlock_amount: 250_000_000_000, amount_per_period: 187_500_000_000, }, // Fees and incentives pool_creation_fee: 500_000_000, // 0.5 SOL enable_first_swap_with_min_fee: true, compounding_fee_bps: 100, // 1% creator_trading_fee_percentage: 30, // Other collect_fee_mode: 0, // quote token migrated_pool_fee: MigratedPoolFee { collect_fee_mode: 0, dynamic_fee: 0, pool_fee_bps: 300, // 3% for migrated pool }, migrated_pool_base_fee_mode: 1, // exponential scheduler migrated_pool_market_cap_fee_scheduler_params: Default::default(), }; // Call instruction invoke( &dynamic_bonding_curve::create_config( ctx.accounts, config_params, ), &[signer], )?; ``` -------------------------------- ### Build Dynamic Bonding Curve Program Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/README.md Command to build the dynamic bonding curve program using Anchor. Use the --ignore-keys flag to avoid issues with keypair files during the build process. ```bash anchor build -p dynamic_bonding_curve --ignore-keys ``` -------------------------------- ### Program Instructions Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/MANIFEST.txt Documentation for the 27 program instructions, covering admin operations, fee management, pool operations, trading, and migration. ```APIDOC ## Program Instructions Reference This section details the available program instructions for interacting with the Dynamic Bonding Curve protocol. ### Overview - **Total Instructions Documented**: 27 - **Categories**: Admin operations (3), Protocol fee operations (4), Partner configuration (3), Partner fee operations (4), Pool creation (3), Pool creator operations (5), Trading operations (3), Migration operations (7). ### Accessing Instruction Details Detailed signatures, parameters, and examples for each instruction can be found in `api-reference/program-instructions.md`. ``` -------------------------------- ### Calculate and Display Fees for a Swap Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Demonstrates how to call `quote_exact_in` and then break down the resulting total fee into protocol, referral, and partner portions. Use this to understand fee distribution after a swap. ```rust // 1000 base tokens swap let result = quote_exact_in(&pool, &config, true, time, slot, 1000, false, false)?; // Fees breakdown let total_fee = result.actual_fee; let protocol_portion = result.protocol_fee; let referral_portion = result.referral_fee; let partner_portion = total_fee - protocol_portion; println!("Total fee: {} ({}%)", total_fee, total_fee as f64 / result.amount_1_delta as f64 * 100.0); println!(" Protocol: {}", protocol_portion); println!(" Referral: {}", referral_portion); println!(" Partner: {}", partner_portion); ``` -------------------------------- ### Create Partner Metadata Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Use this function to create partner metadata for configuring launch pool parameters. It takes context and metadata parameters as input. ```rust pub fn create_partner_metadata( ctx: Context, metadata: CreatePartnerMetadataParameters, ) -> Result<()> ``` -------------------------------- ### SDK Dependencies Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Lists the necessary dependencies for using the dynamic bonding curve SDK, including the SDK itself, the core library for state types, `anyhow` for error handling, and `ruint` for arbitrary-precision arithmetic. ```toml [dependencies] dynamic-bonding-curve-sdk = "0.1.0" dynamic-bonding-curve = "0.2.0" # For PoolState, PoolConfig types anyhow = "1.0" ruint = "1.14" # For U256 price math ``` -------------------------------- ### Quote Before Swap Pattern Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Illustrates the steps for quoting a swap before execution, including calculating acceptable amounts with slippage tolerance and executing the swap instruction with slippage limits. ```plaintext 1. Call SDK quote function - quote_exact_in for known input - quote_exact_out for known output - quote_partial_fill for impact analysis 2. Calculate minimum/maximum acceptable amount - Apply 0.5-5% slippage tolerance - Use for swap instruction parameters 3. Execute swap instruction - Use minimum_amount_out to enforce slippage limit - Handle potential errors ``` -------------------------------- ### Price Discovery with Quote Functions Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Fetches pool and configuration data to determine the current spot price for a given amount. Assumes 1 base unit input. ```rust let pool_state = fetch_pool_account(pool_pubkey).await?; let pool_config = fetch_config_account(config_pubkey).await?; // Quote 1 base token (or 1e6 in smallest unit) let quote = quote_exact_in( &pool_state, &pool_config, true, current_time(), current_slot(), 1_000_000, // 1 base unit false, false, )?; let price = quote.amount_1_delta as f64 / 1_000_000.0; println!("Spot price: {} quote per base", price); ``` -------------------------------- ### create_partner_metadata Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates partner metadata for configuring launch pool parameters. ```APIDOC ## create_partner_metadata ### Description Creates partner metadata for configuring launch pool parameters. ### Parameters #### Request Body - **metadata** (CreatePartnerMetadataParameters) - Required - Partner metadata configuration ``` -------------------------------- ### swap Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Executes a token swap with exact input amount on a VirtualPool. ```APIDOC ## swap ### Description Executes a token swap with exact input amount on a VirtualPool. ### Method Not applicable (Rust function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params.amount_in** (u64) - Yes - Exact amount of input token - **params.minimum_amount_out** (u64) - Yes - Minimum amount of output token ### Request Example ```rust // Swap 1000 base tokens for minimum 800 quote tokens let params = SwapParameters { amount_in: 1000, minimum_amount_out: 800, }; invoke( &dynamic_bonding_curve::swap(accounts, params), signers )?; ``` ### Response #### Success Response Ok on success #### Response Example None provided #### Errors - `ExceededSlippage` - if output less than minimum - `NotEnoughLiquidity` - if pool doesn't have liquidity - `PoolIsCompleted` - if pool has migrated ``` -------------------------------- ### Create Metadata for Meteora DAMM v1 Migration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates metadata for Meteora DAMM v1 migration. Accepts only VirtualPool. ```rust pub fn migration_meteora_damm_create_metadata<'info>( ctx: Context<'info, MigrationMeteoraDammCreateMetadataCtx<'info>>, ) -> Result<()> ``` -------------------------------- ### create_locker Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates a locker account for locked liquidity provider tokens after migration. Accepts VirtualPool or TransferHookPool and returns Ok on success, emitting a Migration event. ```APIDOC ## create_locker ### Description Creates a locker account for locked liquidity provider tokens after migration. ### Method (Not specified, likely a program instruction call) ### Parameters (No explicit parameters documented beyond context) ### Accepts VirtualPool or TransferHookPool ### Returns Ok on success ### Emits Migration event ``` -------------------------------- ### Create Locker Account Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates a locker account for locked liquidity provider tokens after migration. Accepts VirtualPool or TransferHookPool. ```rust pub fn create_locker<'info>( ctx: Context<'info, CreateLockerCtx<'info>> ) -> Result<()> ``` -------------------------------- ### migration_meteora_damm_create_metadata Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates metadata for Meteora DAMM v1 migration. Accepts only VirtualPool and returns Ok on success. ```APIDOC ## migration_meteora_damm_create_metadata ### Description Creates metadata for Meteora DAMM v1 migration. ### Method (Not specified, likely a program instruction call) ### Parameters (No explicit parameters documented beyond context) ### Accepts VirtualPool only ### Returns Ok on success ``` -------------------------------- ### SwapParameters Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Input parameters for the `swap` instruction. Specifies the exact amount of input token and the minimum acceptable output amount. ```APIDOC ## SwapParameters Input parameters for `swap` instruction. ### Description Specifies the exact amount of input token and the minimum acceptable output amount to protect against slippage. ### Fields #### `amount_in` (u64) Exact input amount. #### `minimum_amount_out` (u64) Slippage protection threshold. ``` -------------------------------- ### initialize_virtual_pool_with_token2022 Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Initializes a new virtual bonding curve pool with a Token2022. This function takes pool initialization parameters and returns Ok on success. It is designed for Token2022 pools and accepts VirtualPool. ```APIDOC ## initialize_virtual_pool_with_token2022 ### Description Initializes a new virtual bonding curve pool with a Token2022. ### Method Rust function call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (InitializePoolParameters) - Required - Pool initialization parameters ### Request Example ```rust initialize_virtual_pool_with_token2022(ctx, params) ``` ### Response #### Success Response Ok on success #### Response Example Ok(()) ### Accepts VirtualPool only ``` -------------------------------- ### Initialize Virtual Pool with Token2022 Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Initializes a new virtual bonding curve pool with a Token2022. This function takes `InitializePoolParameters` and returns `Ok` on success. ```rust pub fn initialize_virtual_pool_with_token2022<'info>( ctx: Context<'info, InitializeVirtualPoolWithToken2022Ctx<'info>>, params: InitializePoolParameters, ) -> Result<()> ``` -------------------------------- ### swap2 Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Executes a token swap on a VirtualPool with flexible swap mode. ```APIDOC ## swap2 ### Description Executes a token swap on a VirtualPool with flexible swap mode. ### Method Not applicable (Rust function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params.amount_0** (u64) - Yes - Amount for first token (input for ExactIn, output for ExactOut) - **params.amount_1** (u64) - Yes - Amount for second token (output for ExactIn, input for ExactOut) - **params.swap_mode** (u8) - Yes - Swap mode: 0 = ExactIn, 1 = ExactOut ### Request Example None provided ### Response #### Success Response Ok on success #### Response Example None provided #### Errors None explicitly listed ``` -------------------------------- ### Initialize Pool Parameters for SPL Token Pools Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md Defines the parameters required to initialize an SPL Token liquidity pool. Ensure all amounts are positive and adhere to the specified constraints. ```rust InitializePoolParameters { initial_quote_amount: u64, // Total quote to deposit initial_base_amount: u64, // Total base to mint creator_input_quote_amount: u64, // Creator's contribution swap_curve_base_amount: u64, // Base for curve } ``` -------------------------------- ### Pool Monitoring Pattern Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Explains how to monitor pool activity, including subscribing to account updates, calculating key metrics, and detecting migration triggers based on reserve thresholds. ```plaintext 1. Subscribe to pool account updates - Listen to base_reserve and quote_reserve changes - Monitor migration_progress field 2. Calculate metrics - Current price from sqrt_price - Fee accumulation rates - Liquidity available at price ranges 3. Detect migration trigger - When quote_reserve ≥ migration_quote_threshold - Pool is ready for migration ``` -------------------------------- ### Reading VirtualPool Account Data Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/state-accounts.md Demonstrates how to deserialize and read data from a VirtualPool account. This includes accessing reserves, migration status, and fee accumulation. Ensure the account info is valid and the program has read access. ```rust use anchor_lang::Account; use dynamic_bonding_curve::state::VirtualPool; let pool: Account = Account::try_from(&account_info)?; // Read reserves println!("Base reserve: {}", pool.base_reserve); println!("Quote reserve: {}", pool.quote_reserve); // Check migration status match pool.migration_progress { 0 => println!("Status: Pre-bonding"), 1 => println!("Status: Post-bonding"), 2 => println!("Status: Locked vesting"), 3 => println!("Status: Created on AMM"), _ => println!("Unknown status"), } // Check fee accumulation let total_protocol_fee = pool.protocol_base_fee + pool.protocol_quote_fee; println!("Protocol fees: {}", total_protocol_fee); ``` -------------------------------- ### Run Compatible Test Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/COMPATIBLE_TEST.md Executes the compatible test using pnpm. This step attempts to run previously generated instruction data with the current program version. ```bash pnpm ctest ``` -------------------------------- ### Type Dependencies in Dynamic Bonding Curve Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Illustrates the hierarchical relationships between configuration parameters, pool state components, and swap result data structures. ```text ConfigParameters ├── PoolFeeParameters (fees) ├── LiquidityDistributionParameters (curve) ├── LockedVestingParams (vesting) ├── MigrationFee ├── TokenSupplyParams ├── MigratedPoolFee └── MigratedPoolMarketCapFeeSchedulerParams PoolState ├── VolatilityTracker (dynamic fees) ├── PoolMetrics (statistics) └── All fee accumulators (protocol, partner, creator) SwapResult2 ├── amount_0_delta (input/output) ├── amount_1_delta (output/input) ├── actual_fee (total) ├── protocol_fee (split) └── referral_fee (split) ``` -------------------------------- ### InitializePoolParameters Struct Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Specifies parameters required for initializing a virtual pool. This includes initial token amounts for both quote and base currencies, as well as contributions from the creator and for the swap curve. ```rust pub struct InitializePoolParameters { pub initial_quote_amount: u64, // Initial quote token to deposit pub initial_base_amount: u64, // Initial base token minted pub creator_input_quote_amount: u64, // Creator's quote contribution pub swap_curve_base_amount: u64, // Base tokens for curve activation } ``` -------------------------------- ### BaseFeeConfig Struct Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Defines the configuration for base fee calculation, including mode, initial fee, reduction factor, and activation timestamp. Used to determine fees over time. ```rust #[zero_copy] pub struct BaseFeeConfig { pub base_fee_mode: u8, // BaseFeeMode enum value pub cliff_fee_numerator: u64, // Initial fee as basis points pub reduction_factor: u64, // Fee reduction per period pub activation_timestamp: u64, // Time when fee scheduler began } ``` -------------------------------- ### Create Pool Configuration Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Use this function to create a pool configuration for SPL Token pools. It allows partners to specify fees, migration options, curve parameters, and token settings. It may emit `EvtCreateConfig` and `EvtCreateConfigV2` events and can throw errors related to invalid configurations. ```rust pub fn create_config( ctx: Context, config_parameters: ConfigParameters, ) -> Result<()> ``` -------------------------------- ### create_config Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates a pool configuration for SPL Token pools. Partner specifies fees, migration options, curve parameters, and token settings. ```APIDOC ## create_config ### Description Creates a pool configuration for SPL Token pools. Partner specifies fees, migration options, curve parameters, and token settings. ### Parameters #### Request Body - **config_parameters** (ConfigParameters) - Required - Full pool configuration parameters ### Errors - **InvalidFee** - if fee configuration is invalid - **InvalidCurve** - if curve parameters are invalid - **InvalidQuoteThreshold** - if migration quote threshold is invalid - **InvalidTokenDecimals** - if token decimal is not 6-9 ``` -------------------------------- ### migration_damm_v2_create_metadata (Deprecated) Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates metadata for DAMM v2 migration. Deprecated; use `migration_damm_v2` directly. Accepts VirtualPool or TransferHookPool and returns Ok on success. ```APIDOC ## migration_damm_v2_create_metadata (Deprecated) ### Description Creates metadata for DAMM v2 migration. Deprecated; use `migration_damm_v2` directly. ### Method (Not specified, likely a program instruction call) ### Parameters (No explicit parameters documented beyond context) ### Accepts VirtualPool or TransferHookPool ### Returns Ok on success ``` -------------------------------- ### Initialize Virtual Pool with Token2022 Transfer Hook Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Initializes a virtual pool with Token2022 and enables the transfer hook. This function accepts `InitializePoolParameters` and returns `Ok` on success. ```rust pub fn initialize_virtual_pool_with_token2022_transfer_hook( ctx: Context, params: InitializePoolParameters, ) -> Result<()> ``` -------------------------------- ### initialize_virtual_pool_with_token2022_transfer_hook Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Initializes a virtual pool with Token2022 and transfer hook enabled. This function accepts pool initialization parameters and returns Ok on success. It is designed for Token2022 pools with transfer hooks and accepts TransferHookPool. ```APIDOC ## initialize_virtual_pool_with_token2022_transfer_hook ### Description Initializes a virtual pool with Token2022 and transfer hook enabled. ### Method Rust function call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (InitializePoolParameters) - Required - Pool initialization parameters ### Request Example ```rust initialize_virtual_pool_with_token2022_transfer_hook(ctx, params) ``` ### Response #### Success Response Ok on success #### Response Example Ok(()) ### Accepts TransferHookPool only ``` -------------------------------- ### Liquidity Impact Analysis with Quote Functions Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Compares the price impact of a small order versus a large order to assess liquidity. Calculates the percentage difference in price. ```rust // Test large order impact let small_order = quote_exact_in( &pool, &config, true, time, slot, 1_000_000, false, false, )?; let large_order = quote_exact_in( &pool, &config, true, time, slot, 100_000_000, false, false, )?; let small_price = small_order.amount_1_delta as f64 / 1_000_000.0; let large_price = large_order.amount_1_delta as f64 / 100_000_000.0; println!("Price impact: {:.2}%", (1.0 - large_price/small_price) * 100.0); ``` -------------------------------- ### ConfigParameters Struct Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Specifies the complete configuration for creating a new pool, encompassing fee structures, migration options, token details, liquidity percentages, vesting schedules, and liquidity curve segments. Used in pool creation instructions. ```rust #[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone)] pub struct ConfigParameters { pub pool_fees: PoolFeeParameters, pub collect_fee_mode: u8, pub migration_option: u8, pub activation_type: u8, pub token_type: u8, pub token_decimal: u8, pub partner_liquidity_percentage: u8, pub partner_permanent_locked_liquidity_percentage: u8, pub creator_liquidity_percentage: u8, pub creator_permanent_locked_liquidity_percentage: u8, pub migration_quote_threshold: u64, pub sqrt_start_price: u128, pub locked_vesting: LockedVestingParams, pub migration_fee_option: u8, pub token_supply: Option, pub creator_trading_fee_percentage: u8, pub token_update_authority: u8, pub migration_fee: MigrationFee, pub migrated_pool_fee: MigratedPoolFee, pub pool_creation_fee: u64, pub partner_liquidity_vesting_info: LiquidityVestingInfoParams, pub creator_liquidity_vesting_info: LiquidityVestingInfoParams, pub migrated_pool_base_fee_mode: u8, pub migrated_pool_market_cap_fee_scheduler_params: MigratedPoolMarketCapFeeSchedulerParams, pub enable_first_swap_with_min_fee: bool, pub compounding_fee_bps: u16, pub padding: [u8; 2], pub curve: Vec, } ``` -------------------------------- ### Define Liquidity Distribution Parameters Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/configuration.md Use this to define segments of the bonding curve, specifying the square root price and the liquidity at that price point. Ensure `sqrt_price` values are monotonically increasing and the number of segments does not exceed 20. ```rust curve: vec![ LiquidityDistributionParameters { sqrt_price: 1, liquidity: 100, }, LiquidityDistributionParameters { sqrt_price: 2, liquidity: 500, }, ] ``` -------------------------------- ### migrate_meteora_damm Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Migrates a virtual pool to Meteora DAMM v1 AMM. Accepts only VirtualPool and returns Ok on success. Throws InsufficientLiquidityForMigration. ```APIDOC ## migrate_meteora_damm ### Description Migrates a virtual pool to Meteora DAMM v1 AMM. ### Method (Not specified, likely a program instruction call) ### Parameters (No explicit parameters documented beyond context) ### Accepts VirtualPool only ### Returns Ok on success ### Throws - `InsufficientLiquidityForMigration` - if pool doesn't meet migration threshold ``` -------------------------------- ### Migrate to Meteora DAMM v1 Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Migrates a virtual pool to Meteora DAMM v1 AMM. Accepts only VirtualPool. Throws InsufficientLiquidityForMigration. ```rust pub fn migrate_meteora_damm<'info>( ctx: Context<'info, MigrateMeteoraDammCtx<'info>>, ) -> Result<()> ``` -------------------------------- ### Create Metadata for DAMM v2 Migration (Deprecated) Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates metadata for DAMM v2 migration. Deprecated; use `migration_damm_v2` directly. Accepts VirtualPool or TransferHookPool. ```rust pub fn migration_damm_v2_create_metadata<'info>( ctx: Context<'info, MigrationDammV2CreateMetadataCtx<'info>>, ) -> Result<()> ``` -------------------------------- ### Generate Instruction Data Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/COMPATIBLE_TEST.md Generates instruction data using a specified IDL file path. This is the first step in preparing for compatible testing. ```bash anchor run ixdata -- path_to_idl_file ``` ```bash anchor run ixdata -- release_0.1.2.json ``` -------------------------------- ### Configuration Instruction Error Checks Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Validates fee parameters, curve points, token decimals, and quote thresholds for configuration instructions. ```text Configuration Instructions: - `InvalidFee` - check fee parameters - `InvalidCurve` - validate curve points - `InvalidTokenDecimals` - ensure 6-9 decimals - `InvalidQuoteThreshold` - must be > 0 ``` -------------------------------- ### SDK Quote Functions Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/MANIFEST.txt Reference for the Rust SDK quote functions used for calculating swap amounts. ```APIDOC ## SDK Quote Functions This section provides reference for the Rust SDK functions used for quoting swap amounts. ### Documented Functions (3) - `quote_exact_in`: Calculates the amount of output tokens received for a given amount of input tokens. - `quote_exact_out`: Calculates the amount of input tokens required to receive a given amount of output tokens. - `quote_partial_fill`: Calculates swap amounts for partial fills, considering slippage and other factors. ### Accessing Function Details Detailed signatures, parameters, return types, and usage examples for these functions are available in `api-reference/sdk-quote-functions.md`. ``` -------------------------------- ### Create Operator Account Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates an operator account with specified permissions for managing protocol operations. Requires admin privileges. ```rust pub fn create_operator_account( ctx: Context, permission: u128, ) -> Result<()> ``` -------------------------------- ### Curve and Price Constants for Dynamic Bonding Curve Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Sets constants for the minimum and maximum square root prices, the maximum number of curve segments, and the swap buffer percentage. ```rust pub const MAX_SQRT_PRICE: u128 = 18446744073709551616; // Max price (2^64) pub const MIN_SQRT_PRICE: u128 = 1; // Min price (1) pub const MAX_CURVE_POINT: usize = 20; // Max curve segments pub const SWAP_BUFFER_PERCENTAGE: u8 = 1; // Swap buffer (1%) ``` -------------------------------- ### DynamicFeeConfig Struct Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Defines configuration for dynamic, volatility-based fees. Use this to enable/disable dynamic fees and set their maximum additional amount and volatility trigger threshold. ```rust #[zero_copy] pub struct DynamicFeeConfig { pub dynamic_fee_enabled: u8, // 0 = disabled, 1 = enabled pub max_dynamic_fee_numerator: u64, // Maximum additional fee (basis points) pub sqrt_price_change_volatility_threshold: u128, // Volatility trigger } ``` -------------------------------- ### Create Pool Configuration with Transfer Hook Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Use this function to create a pool configuration specifically for Token2022 pools with transfer hooks enabled. It takes context and configuration parameters as input. ```rust pub fn create_config_with_transfer_hook( ctx: Context, config_parameters: ConfigParameters, ) -> Result<()> ``` -------------------------------- ### Pool Lifecycle Stages Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Details the distinct stages a pool goes through from configuration to cleanup. This includes on-chain and off-chain processes. ```text 1. CONFIGURATION (on-chain) └─ Partner creates PoolConfig with parameters └─ Specifies fees, liquidity curve, migration target 2. POOL CREATION (on-chain) └─ Creator initializes VirtualPool with quote/base amounts └─ Pool enters bonding curve phase └─ Users can start trading 3. TRADING (on-chain) └─ Users execute swaps └─ Reserves update, fees accumulate └─ Pool price follows configured curve 4. MIGRATION TRIGGER (off-chain detection) └─ Monitor quote reserve └─ When threshold reached, pool is ready to graduate 5. MIGRATION (on-chain) └─ create_locker - prepare LP tokens └─ migration_damm_v2 / migrate_meteora_damm - create AMM pool └─ migrate_*_lock_lp_token - lock LP for vesting └─ Pool transitions to migrated state 6. LP VESTING (time-based) └─ locked_vesting schedule unlocks LP tokens over time └─ Creator/partner can claim fees from locked LP 7. CLEANUP (permissionless) └─ withdraw_migration_fee - claim migration fees └─ withdraw_leftover - claim leftover tokens └─ creator_withdraw_surplus - claim extra quote tokens ``` -------------------------------- ### Calculate Input for Exact Output Amount Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Use this function to determine the exact input amount required to receive a specific output amount of tokens. It handles both base-to-quote and quote-to-base swaps. Ensure you have the pool state, configuration, and relevant swap details. ```rust use dynamic_bonding_curve_sdk::quote_exact_out; // Quote to receive exactly 5000 quote tokens let result = quote_exact_out( &pool, &config, false, // swap quote for base 1721000000, 245000000, 5000_000_000_000, // 5000 quote tokens false, )?; println!("Input amount: {}", result.amount_0_delta.abs()); println!("Fees included: {}", result.actual_fee); ``` -------------------------------- ### Migration Instruction Error Handling Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/README.md Outlines error handling for migration instructions, addressing liquidity, vesting parameters, and migrated pool fee validation. ```text Migration Instructions: - `InsufficientLiquidityForMigration` - wait for threshold - `InvalidVestingParameters` - validate vesting config - `InvalidMigratedPoolFee` - check fee tier support ``` -------------------------------- ### create_operator_account Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates an operator account with specified permissions for managing protocol operations. This instruction is admin-only. ```APIDOC ## create_operator_account ### Description Creates an operator account with specified permissions for managing protocol operations. ### Parameters #### Path Parameters - **permission** (u128) - Required - Bitmask of permissions to grant the operator account ### Access Control Admin-only ### Returns Ok on success ``` -------------------------------- ### Swap Routing Decision with Quote Functions Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/sdk-quote-functions.md Iterates through multiple available pools, using quote functions to find the pool offering the best price for a given swap amount. Skips pools that return an error. ```rust // Choose between multiple pools based on best price for pool_address in available_pools { match quote_exact_in( &pool_states[pool_address], &configs[pool_address], swap_base_for_quote, time, slot, amount_in, false, false, ) { Ok(result) => { let price = result.amount_1_delta as f64 / amount_in as f64; best_price = best_price.max(price); best_pool = pool_address; } Err(_) => continue, // Skip pools that error } } ``` -------------------------------- ### Create Virtual Pool Metadata Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Creates metadata for a virtual pool. This instruction accepts either a VirtualPool or a TransferHookPool and requires the caller to be the pool creator. ```rust pub fn create_virtual_pool_metadata( ctx: Context, metadata: CreateVirtualPoolMetadataParameters, ) -> Result<()> ``` -------------------------------- ### Migration Constants for Dynamic Bonding Curve Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/types.md Defines constants related to liquidity migration, including migration fees in basis points and percentage limits. ```rust pub const PROTOCOL_LIQUIDITY_MIGRATION_FEE_BPS: u16 = 100; // 1% migration fee pub const MIN_MIGRATED_POOL_FEE_BPS: u16 = 25; // Min fee (0.25%) pub const MAX_MIGRATED_POOL_FEE_BPS: u16 = 600; // Max fee (6%) pub const MIN_MIGRATION_FEE_PERCENTAGE: u8 = 0; pub const MAX_MIGRATION_FEE_PERCENTAGE: u8 = 50; // Max migration fee ``` -------------------------------- ### initialize_virtual_pool_with_spl_token Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/program-instructions.md Initializes a new virtual bonding curve pool with an SPL Token. This function accepts pool initialization parameters and returns Ok on success. It may throw errors related to invalid token types or decimals, or if the pool is already completed. ```APIDOC ## initialize_virtual_pool_with_spl_token ### Description Initializes a new virtual bonding curve pool with an SPL Token. ### Method Rust function call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (InitializePoolParameters) - Required - Pool initialization parameters ### Request Example ```rust initialize_virtual_pool_with_spl_token(ctx, params) ``` ### Response #### Success Response Ok on success #### Response Example Ok(()) ### Throws - InvalidTokenType - if token is not SPL Token - InvalidTokenDecimals - if decimals don't match config - PoolIsCompleted - if trying to initialize completed pool ``` -------------------------------- ### Deriving VirtualPoolMetadata PDA Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/state-accounts.md Shows how to find the Program Derived Address (PDA) for the VirtualPoolMetadata account. This is used to ensure the account is owned by the correct program and can be deterministically derived. ```rust let (metadata_pda, bump) = Pubkey::find_program_address( &[b"virtual_pool_metadata", pool_pubkey.as_ref()], &dynamic_bonding_curve::ID, ); ``` -------------------------------- ### AccountLoader for PoolConfig Source: https://github.com/meteoraag/dynamic-bonding-curve/blob/main/_autodocs/api-reference/state-accounts.md Illustrates using `AccountLoader` for accounts that are too large to be directly deserialized into memory, such as `PoolConfig`. This allows for loading and accessing data from these larger accounts. ```rust // AccountLoader for PoolConfig (too large for direct account) let config = ctx.accounts.config.load()?; let fee_mode = config.collect_fee_mode; ```