Meteora 백서

Meteora

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 52쪽

strategy` plus advance-payment token accounts | `max_admin_pay_amount` | Admin | Remove a strategy using vault/admin advance payment instead of a normal strategy withdrawal, then mark it disabled. | `initialize_strategy` requires `vault.fee_vault` to be set. The handler validates the strategy bump layout and fails with `InvalidBump` if `other_bumps[0]` or `other_bumps[1]` do not match the expected strategy index and PDA bump. ## Rebalancing And Rewards | Instruction | Accounts | Args | Authority | Use | | - | - | - | - | - | | `deposit_strategy` | `vault`, `strategy`, `token_vault`, `fee_vault`, `lp_mint`, `strategy_program`, `collateral_vault`, `reserve`, `token_program`, `operator` | `amount` | Admin or operator | Move vault reserve liquidity into a strategy. | | `withdraw_strategy` | Same as `deposit_strategy` | `amount` | Admin or operator | Move liquidity from a strategy back into the vault reserve. | | `claim_rewards` | `vault`, `strategy`, `token_program`, `token_reward_acc`, `operator` | none | Admin or operator | Claim strategy rewards to a treasury-owned reward token account. | Strategy instructions pass protocol-specific remaining accounts to the active strategy handler. The current source-backed external handler is `JupLend`. ## Rebalance Wrapper Behavior `deposit_strategy`, `withdraw_strategy`, `remove_strategy`, `remove_strategy2`, and `withdraw_directly_from_strategy` run through shared rebalance accounting. | Step | Behavior | | - | - | | Validate strategy | Fails with `StrategyIsNotExisted` if the strategy is not registered in the vault. | | Snapshot liquidity | Reads vault reserve amount and `strategy.current_liquidity` before the strategy call. | | Execute handler | Calls the strategy-specific deposit, withdraw, reward, or compatibility path. | | Reload accounts | Reloads token and collateral vaults after CPI. | | Update total | Updates `vault.total_amount` from reserve and strategy liquidity changes. | | Report loss | Emits `ReportLoss` when total amount decreases. | | Lock profit | Updates `locked_profit_tracker` when total amount changes. | | Mint fee | On profit, mints performance-fee LP tokens to `fee_vault` and emits `PerformanceFee`. | ## Admin And Operator Controls | Instruction | Accounts | Args | Authority | Use | | - | - | - | - | - | | `enable_vault` | `vault`, `admin` | `enabled` | Admin | Set `vault.enabled`. | | `set_operator` | `vault`, `operator`, `admin` | none | Admin | Replace the vault operator. | | `update_locked_profit_degradation` | `vault`, `admin` | `locked_profit_degradation` | Admin | Update locked-profit release rate after refreshing current locked profit. | | `transfer_admin` | `vault`, `admin`, `new_admin` | none | Current admin and new admin signer | Transfer vault admin authority. | | `transfer_fee_vault` | `vault`, `admin`, `new_fee_vault` | none | Admin | Set a treasury-owned LP token account as the fee vault. | | `get_unlocked_amount` | `vault` | none | none | Simulate or invoke to emit `TotalAmount` with current unlocked amount. | All admin and operator controls except `get_unlocked_amount` require a rebalance vault. ## TypeScript SDK Mapping | SDK method | Program behavior | | - | - | | `VaultImpl.createPermissionlessVaultInstruction(...)` | Builds `initialize`. | | `VaultImpl.create(...)` | Derives the vault PDA from token mint and fetches vault, token mint, and LP mint state. | | `vault.deposit(...)` | Builds `deposit`, or affiliate wrapper `deposit` when `affiliateId` is configured. | | `vault.withdraw(...)` | Builds reserve `withdraw` or strategy-backed withdrawal depending on vault reserve liquidity. | | `vault.getWithdrawableAmount()` | Computes the same locked-profit unlock formula client-side from vault state and on-chain time. | | `vault.getStrategiesState()` | Fetches strategy accounts from non-default `vault.strategies` entries. | ## Low-Level Gotchas | Gotcha | Detail | | - | - | | LP amount names | `withdraw` takes LP tokens to burn as `unmint_amount`, not an underlying-token amount. The SDK parameter is named `baseTokenAmount`, but the source uses it as the LP amount to burn. | | Strategy remaining accounts | Strategy handlers validate downstream accounts. Account metas vary by strategy type and must match the handler. | | Fee vault setup | Rebalance and strategy flows with `has_one = fee_vault` require the vault's fee vault to be configured. | | Disabled strategies | `remove_strategy2` calls `strategy.disable()`. A disabled strategy cannot be re-added. | | Precision loss | Direct strategy withdrawal fails with `InvalidPrecisionLoss` if the precision loss is greater than one underlying unit. | | Older IDL entries | The public TS IDL includes older entries such as `collectDust` and `withdraw2`. They are not present in the current `mercurial-vault` program source handlers and are not documented as current handlers here. | # Dynamic Vault Rust Integration CPI Source: https://docs.meteora.ag/developer-guides/dynamic-vault/rust-integration/cpi Learn how to plan Dynamic Vault Anchor CPI integrations with vault accounts, signer seeds, strategy accounts, and failure modes. Use CPI when your Solana program must call Dynamic Vault directly, for example to deposit user funds into a vault, withdraw vault LP, or compose vault withdrawals as part of a larger protocol instruction. <Warning> Prefer generated Anchor bindings from the IDL and compare account metas against SDK-built instructions. Most CPI failures come from wrong PDA seeds, a stale LP mint, a missing fee vault, or strategy-specific remaining accounts in the wrong order. </Warning> ## Program ID ```rust theme={"system"} pub const VAULT_PROGRAM_ID: Pubkey = pubkey!("24Uqj9JCLxUeoC3hGfh5W3s9FM9uCHDS2SG3LYwBpyTi"); ``` The public program ID is the same on mainnet and devnet. ## CPI Scope | Flow | CPI suitability | | - | - | | `deposit` | Suitable for simple integrations that hold or receive user tokens and mint vault LP. | | `withdraw` | Suitable when the vault reserve can satisfy the withdrawal. Burns LP and transfers underlying tokens. | | `withdraw_directly_from_strategy` | Advanced. Requires selecting a strategy and forwarding strategy-specific remaining accounts. | | Strategy rebalance instructions | Keeper/admin style only. Requires admin/operator authorization and strategy handler accounts. | | Admin controls | Usually not part of public partner CPI. Requires vault admin signer. | For off-chain apps, use the TypeScript SDK. For on-chain CPI, your program owns the outer validation, signer seeds, and slippage thresholds. ## Deposit CPI Accounts `deposit` uses `DepositWithdrawLiquidity`. | Account | Mutability | Signer | Notes | | - | - | - | - | | `vault` | writable | no | Must match `token_vault` and `lp_mint`. | | `token_vault` | writable | no | Vault reserve token account. | | `lp_mint` | writable | no | Vault LP mint. | | `user_token` | writable | no | Source underlying token account. | | `user_lp` | writable | no | Destination LP token account. | | `user` | readonly | yes | Authority for `user_token`. | | `token_program` | readonly | no | SPL Token program. | Arguments: | Arg | Type | Meaning | | - | - | - | | `token_amount` | `u64` | Underlying token amount to deposit. Must be greater than zero. | | `minimum_lp_token_amount` | `u64` | Minimum LP tokens to receive. | ## Withdraw CPI Accounts `withdraw` uses the same `DepositWithdrawLiquidity` accounts. | Arg | Type | Meaning | | - | - | - | | `unmint_amount` | `u64` | LP token amount to burn. | | `min_out_amount` | `u64` | Minimum underlying tokens to receive. | Your program should calculate or validate `unmint_amount` in LP units. To withdraw a target underlying amount, convert using current unlocked amount and LP supply. ## Direct Strategy Withdrawal CPI `withdraw_directly_from_strategy` is used when vault reserve liquidity is not enough and the transaction should pull from a strategy first. | Account | Notes | | - | - | | `vault` | Writable rebalance vault with `token_vault`, `lp_mint`, and `fee_vault` relationships. | | `strategy` | Writable strategy account registered in `vault.strategies`. | | `reserve` | Writable strategy reserve, must match `strategy.reserve`. | | `strategy_program` | Downstream strategy program. | | `collateral_vault` | Writable strategy collateral account, must match `strategy.collateral_vault`. | | `token_vault` | Writable vault reserve account. | | `lp_mint` | Writable vault LP mint. | | `fee_vault` | Writable fee vault account. | | `user_token` | Writable destination underlying token account. | | `user_lp` | Writable source LP token account. | | `user` | LP token owner signer. | | `token_program` | SPL Token program. | | Remaining accounts | Strategy-handler-specific accounts, currently relevant for `JupLend`. | Direct strategy withdrawal can refine the LP burn amount if the strategy cannot return the full desired amount. It rejects precision loss greater than one underlying unit. ## Vault Signer Seeds The vault signs token transfers and LP minting with: ```rust theme={"system"} let vault_seeds: &[&[u8]] = &[ b"vault", vault_state.token_mint.as_ref(), vault_state.base.as_ref(), &[vault_state.bumps.vault_bump], ]; ``` If your program signs for a PDA-owned user token account in the outer CPI, pass your own signer seeds to the outer token account authority as well. The vault program only signs for vault-owned accounts. ## Account Planning | Check | Detail | | - | - | | Derive from state | Read `vault.token_vault` and `vault.lp_mint` from vault state instead of recomputing them from user input alone. | | Use fresh LP supply | Withdrawal math depends on current LP supply and unlocked amount. | | Validate ATAs | User token and LP accounts must match the expected mint and authority for your integration. | | Pass slippage thresholds | Do not pass zero thresholds in production CPI unless the outer program has its own protection. | | Detect disabled deposits | Deposits fail when `vault.enabled == 0`; withdrawals remain available. | | Plan compute | Strategy-backed withdrawals and rebalance flows can require more compute than reserve-only withdrawals. | ## Rebalance CPI Notes Strategy rebalance instructions are admin/operator flows and require `vault.admin == operator` or `vault.operator == operator`. | Instruction | Extra planning | | - | - | | `deposit_strategy` | Strategy handler deposit accounts, writable collateral vault, reserve, fee vault, LP mint, and operator signer. | | `withdraw_strategy` | Same account set, plus sufficient collateral and strategy liquidity. | | `claim_rewards` | Treasury-owned reward token account and strategy-specific remaining accounts. | | `initialize_strategy` | Fee vault must already be set, and `StrategyBumps` must match the derived strategy PDA. | | `remove_strategy` | Withdraws all strategy liquidity and fails if residual lending liquidity is greater than the allowed precision residue. | ## Common CPI Failures | Error | Likely cause | | - | - | | `ConstraintHasOne` | `token_vault`, `lp_mint`, `fee_vault`, `admin`, or strategy fields do not match vault or strategy state. | | `ConstraintSeeds` | Vault, LP mint, token vault, strategy, or collateral vault PDA was derived with the wrong base or index. | | `AccountNotSigner` | `user`, `admin`, or `operator` was not a signer, or PDA signer seeds were not forwarded by the outer program. | | `VaultIsDisabled` | Deposit attempted while the vault is disabled. | | `ExceededSlippage` | LP minted or underlying output was below threshold. | | `StrategyIsNotExisted` | Strategy account is not present in `vault.strategies`. | | `InvalidAccountsForStrategy` | Fee vault or strategy remaining accounts do not match expected state. | | `FeeVaultIsNotSet` | Strategy initialization attempted before `transfer_fee_vault`. | | `InvalidBump` | `StrategyBumps` does not match the strategy PDA. | | `InvalidPrecisionLoss` | Direct strategy withdrawal precision loss exceeded one underlying unit. | ## Testing | Layer | Recommendation | | - | - | | Unit and account tests | Use Anchor or `solana-program-test` with local vault fixtures. | | Transaction construction | Compare account metas against `@meteora-ag/vault-sdk` built transactions. | | Strategy paths | Test with the exact downstream program fixtures and remaining accounts used by the target strategy. | | Devnet rehearsal | Simulate and send small devnet transactions before mainnet CPI rollout. | For public partner integrations, keep the CPI surface narrow: deposit, reserve withdrawal, and carefully audited direct strategy withdrawal only when your protocol truly needs it. # Dynamic Vault Rust Integration Library Source: https://docs.meteora.ag/developer-guides/dynamic-vault/rust-integration/library Learn how to read Dynamic Vault state, derive vault accounts, calculate unlocked amount, and use the Rust client helper. Use Rust when your backend, keeper, or test harness needs direct account reads, transaction simulation, or Anchor instruction construction for Dynamic Vault. <Note> `vault-sdk/rust-client` is a CLI-style helper, not a broad high-level SDK. It demonstrates PDA derivation, account reads, simulation, deposits, and withdrawals with `anchor-client`. </Note> ## Install For the current program source, depend on the `mercurial-vault` crate from the same workspace or pin the matching repository revision: ```toml theme={"system"} [dependencies] anchor-client = "0.28" anchor-lang = "0.28" anchor-spl = "0.28" anyhow = "1" mercurial-vault = { path = "../programs/vault", features = ["cpi"] } spl-associated-token-account = { version = "2.1.0", features = ["no-entrypoint"] } ``` The local `vault-sdk/rust-client` depends on the vendored `vault-sdk/programs/vault` crate by path. The newer `mercurial-vault/programs/vault` source uses Anchor `0.31.1` and has a newer handler surface. Keep your crate, IDL, and deployed program target aligned. ## Program ID ```rust theme={"system"} pub const VAULT_PROGRAM_ID: &str = "24Uqj9JCLxUeoC3hGfh5W3s9FM9uCHDS2SG3LYwBpyTi"; ``` The public program ID is the same on mainnet and devnet. ## PDA Derivation ```rust theme={"system"} use anchor_lang::prelude::*; let program_id = mercurial_vault::id(); let base = Pubkey::from_str("HWzXGcGHy4tcpYfaRDCyLNzXqBTv3E6BttpCH2vJxArv")?; let (vault, _vault_bump) = Pubkey::find_program_address( &[b"vault".as_ref(), token_mint.as_ref(), base.as_ref()], &program_id, ); let (token_vault, _token_vault_bump) = Pubkey::find_program_address( &[b"token_vault".as_ref(), vault.as_ref()], &program_id, ); let (lp_mint, _lp_mint_bump) = Pubkey::find_program_address( &[b"lp_mint".as_ref(), vault.as_ref()], &program_id, ); ``` For idle vaults, use the default pubkey as the base seed instead of `VAULT_BASE_KEY`. ## Read Vault State ```rust theme={"system"} let vault_state: mercurial_vault::state::Vault = program_client.account(vault)?; let token_data: anchor_spl::token::TokenAccount = program_client.account(vault_state.token_vault)?; let lp_mint_data: anchor_spl::token::Mint = program_client.account(vault_state.lp_mint)?; println!("total amount {}", vault_state.total_amount); println!("reserve amount {}", token_data.amount); println!("lp supply {}", lp_mint_data.supply); ``` ## Calculate Unlocked Amount ```rust theme={"system"} use anchor_lang::solana_program::{clock::Clock, sysvar}; use bincode::deserialize; use std::convert::TryFrom; let clock_account = program_client.rpc().get_account(&sysvar::clock::id())?; let clock = deserialize::<Clock>(&clock_account.data)?; let current_time = u64::try_from(clock.unix_timestamp)?; let unlocked_amount = vault_state .get_unlocked_amount(current_time) .ok_or_else(|| anyhow::anyhow!("failed to calculate unlocked amount"))?; println!("unlocked amount {}", unlocked_amount); ``` The Rust client also demonstrates an instruction simulation path: simulate `get_unlocked_amount`, parse Anchor `Program data:` logs, and deserialize the `TotalAmount` event. ## Deposit The Rust client creates or reuses the user's token and LP ATAs, then builds `DepositWithdrawLiquidity`. ```rust theme={"system"} let user_token = get_or_create_ata(program_client, token_mint, program_client.payer())?; let user_lp = get_or_create_ata(program_client, vault_state.lp_mint, program_client.payer())?; let signature = program_client .request() .accounts(mercurial_vault::accounts::DepositWithdrawLiquidity { vault, token_vault, lp_mint: vault_state.lp_mint, user_token, user_lp, user: program_client.payer(), token_program: anchor_spl::token::spl_token::id(), }) .args(mercurial_vault::instruction::Deposit { token_amount, minimum_lp_token_amount: 0, }) .send()?; println!("{}", signature); ``` ## Withdraw Withdraw burns vault LP tokens. Pass the LP amount as `unmint_amount`. ```rust theme={"system"} let signature = program_client .request() .accounts(mercurial_vault::accounts::DepositWithdrawLiquidity { vault, token_vault, lp_mint: vault_state.lp_mint, user_token, user_lp, user: program_client.payer(), token_program: anchor_spl::token::spl_token::id(), }) .args(mercurial_vault::instruction::Withdraw { unmint_amount, min_out_amount: 0, }) .send()?; println!("{}", signature); ``` ## Rust Client Commands From `vault-sdk/rust-client`: ```bash theme={"system"} cargo build ../target/debug/rust-client --help ``` | Command | Use | | - | - | | `show` | Prints vault state, unlocked amount, LP supply, token vault amount, and strategy states. | | `get-unlocked-amount` | Simulates the read instruction and parses `TotalAmount` from logs. | | `deposit <token_amount>` | Deposits underlying tokens through `DepositWithdrawLiquidity`. | | `withdraw <unmint_amount>` | Burns LP tokens through `DepositWithdrawLiquidity`. | Common provider overrides: ```bash theme={"system"} ../target/debug/rust-client show \ --provider.cluster mainnet \ --provider.token_mint So11111111111111111111111111111111111111112 ``` ## Rust Or TypeScript | Need | Use | | - | - | | App or backend transaction construction | [TypeScript SDK](/developer-guides/dynamic-vault/typescript-sdk/getting-started) | | Rust state reads or local CLI scripts | Rust client helper | | On-chain program composition | [Rust CPI](/developer-guides/dynamic-vault/rust-integration/cpi) | | API dashboards and discovery | [Data API](/developer-guides/dynamic-vault/api-reference/overview) | # Dynamic Vault TypeScript SDK Examples Source: https://docs.meteora.ag/developer-guides/dynamic-vault/typescript-sdk/examples Explore TypeScript examples for Dynamic Vault state reads, deposits, withdrawals, LP conversions, batch loading, vault creation, and affiliate flows. These examples are based on the local `vault-sdk/ts-client` source and tests. They focus on transaction construction and state reads. For the full method catalog, see the [SDK Reference](/developer-guides/dynamic-vault/typescript-sdk/reference). ## Setup ```typescript theme={"system"} import VaultImpl, { getAmountByShare, getUnmintAmount, getVaultPdas, } from "@meteora-ag/vault-sdk"; import { AnchorProvider, BN, Wallet } from "@coral-xyz/anchor"; import { NATIVE_MINT } from "@solana/spl-token"; import { Connection, Keypair, PublicKey, Transaction, } from "@solana/web3.js"; const connection = new Connection(process.env.RPC_URL!, "confirmed"); const wallet = new Wallet(Keypair.generate()); const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed", }); const tokenMint = NATIVE_MINT; const vault = await VaultImpl.create(connection, tokenMint, { cluster: "mainnet-beta", }); ``` Use a real wallet adapter in browser apps. The generated keypair pattern is only suitable for local scripts and tests. ## Fetch Vault State ```typescript theme={"system"} await vault.refreshVaultState(); const lpSupply = await vault.getVaultSupply(); const withdrawableAmount = await vault.getWithdrawableAmount(); const strategies = await
프로젝트로 돌아가기