Meteora 백서

Meteora

원문

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

vault.getStrategiesState(); console.log({ vault: vault.vaultPda.toBase58(), tokenVault: vault.tokenVaultPda.toBase58(), tokenMint: vault.tokenMint.address.toBase58(), lpMint: vault.vaultState.lpMint.toBase58(), totalAmount: vault.vaultState.totalAmount.toString(), withdrawableAmount: withdrawableAmount.toString(), lpSupply: lpSupply.toString(), strategies: strategies.length, }); ``` ## Convert LP To Underlying ```typescript theme={"system"} const userLpBalance = await vault.getUserBalance(wallet.publicKey); const withdrawableAmount = await vault.getWithdrawableAmount(); const lpSupply = await vault.getVaultSupply(); const underlyingShare = getAmountByShare( userLpBalance, withdrawableAmount, lpSupply, ); console.log("Underlying share", underlyingShare.toString()); ``` ## Convert Desired Output To LP Burn ```typescript theme={"system"} const desiredUnderlyingAmount = new BN(500_000_000); // 0.5 SOL const lpToBurn = getUnmintAmount( desiredUnderlyingAmount, await vault.getWithdrawableAmount(), await vault.getVaultSupply(), ); console.log("LP to burn", lpToBurn.toString()); ``` ## Deposit ```typescript theme={"system"} const depositAmount = new BN(1_000_000_000); // 1 SOL const tx = await vault.deposit(wallet.publicKey, depositAmount); tx.feePayer = wallet.publicKey; const simulation = await connection.simulateTransaction(tx); console.log(simulation.value.err); if (!simulation.value.err) { const signature = await provider.sendAndConfirm(tx); console.log("Deposit signature", signature); } ``` For a native SOL vault, the SDK wraps SOL into the user's wrapped SOL ATA before the deposit instruction. ## Withdraw ```typescript theme={"system"} const lpToBurn = await vault.getUserBalance(wallet.publicKey); const tx = await vault.withdraw(wallet.publicKey, lpToBurn); tx.feePayer = wallet.publicKey; const simulation = await connection.simulateTransaction(tx); console.log(simulation.value.err); if (!simulation.value.err) { const signature = await provider.sendAndConfirm(tx); console.log("Withdraw signature", signature); } ``` For a native SOL vault, the SDK adds a post-instruction to close the wrapped SOL ATA. ## Batch Load Vaults ```typescript theme={"system"} const tokenMints = [ new PublicKey("So11111111111111111111111111111111111111112"), new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), ]; const vaults = await VaultImpl.createMultiple(connection, tokenMints, { cluster: "mainnet-beta", }); for (const item of vaults) { console.log({ vault: item.vaultPda.toBase58(), tokenMint: item.tokenMint.address.toBase58(), lpMint: item.vaultState.lpMint.toBase58(), }); } ``` ## Batch Load User LP Balances ```typescript theme={"system"} const lpMints = vaults.map((item) => item.vaultState.lpMint); const balances = await VaultImpl.fetchMultipleUserBalance( connection, lpMints, wallet.publicKey, ); balances.forEach((balance, index) => { console.log(lpMints[index].toBase58(), balance.toString()); }); ``` ## Derive Vault PDAs ```typescript theme={"system"} import { PROGRAM_ID } from "@meteora-ag/vault-sdk"; const pdas = getVaultPdas( tokenMint, new PublicKey(PROGRAM_ID), ); console.log({ vault: pdas.vaultPda.toBase58(), tokenVault: pdas.tokenVaultPda.toBase58(), lpMint: pdas.lpMintPda.toBase58(), }); ``` ## Create A Permissionless Vault Instruction ```typescript theme={"system"} const createVaultIx = await VaultImpl.createPermissionlessVaultInstruction( connection, wallet.publicKey, tokenMint, { cluster: "mainnet-beta", }, ); const tx = new Transaction().add(createVaultIx); tx.feePayer = wallet.publicKey; tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash; console.log(await connection.simulateTransaction(tx)); ``` This helper builds the program `initialize` instruction and derives the vault, token vault, and LP mint PDAs. ## Affiliate Flow ```typescript theme={"system"} const affiliateVault = await VaultImpl.create(connection, tokenMint, { cluster: "mainnet-beta", affiliateId: new PublicKey("YOUR_PARTNER_PUBLIC_KEY"), }); const partnerInfo = await affiliateVault.getAffiliateInfo(); const userLpBalance = await affiliateVault.getUserBalance(wallet.publicKey); console.log({ partnerToken: partnerInfo.partnerToken.toBase58(), userLpBalance: userLpBalance.toString(), }); ``` With `affiliateId`, `deposit` and `withdraw` use the affiliate program wrapper and derive affiliate user LP token accounts internally. # Dynamic Vault TypeScript SDK Getting Started Source: https://docs.meteora.ag/developer-guides/dynamic-vault/typescript-sdk/getting-started Learn how to install @meteora-ag/vault-sdk, create a vault client, read vault state, deposit, withdraw, and test locally. Use `@meteora-ag/vault-sdk` when building an off-chain app, backend service, or script that needs to read Dynamic Vault state or build deposit and withdrawal transactions. <CardGroup> <Card title="Vault SDK Repository" icon="github" href="https://github.com/MeteoraAg/vault-sdk"> Public TypeScript SDK source, tests, IDL, and Rust client helper. </Card> <Card title="NPM Package" icon="npm" href="https://www.npmjs.com/package/@meteora-ag/vault-sdk"> Published `@meteora-ag/vault-sdk` package. </Card> </CardGroup> ## Install <Tabs> <Tab title="npm"> ```bash theme={"system"} npm install @meteora-ag/vault-sdk @coral-xyz/anchor @solana/web3.js@1 @solana/spl-token bn.js ``` </Tab> <Tab title="pnpm"> ```bash theme={"system"} pnpm install @meteora-ag/vault-sdk @coral-xyz/anchor @solana/web3.js@1 @solana/spl-token bn.js ``` </Tab> <Tab title="yarn"> ```bash theme={"system"} yarn add @meteora-ag/vault-sdk @coral-xyz/anchor @solana/web3.js@1 @solana/spl-token bn.js ``` </Tab> </Tabs> The package currently targets the `@solana/web3.js` v1 transaction model. ## Create A Client `VaultImpl.create` takes a token mint public key. For SOL, use `NATIVE_MINT` from `@solana/spl-token`. ```typescript theme={"system"} import VaultImpl from "@meteora-ag/vault-sdk"; import { AnchorProvider, BN, Wallet } from "@coral-xyz/anchor"; import { NATIVE_MINT } from "@solana/spl-token"; import { Connection, Keypair } from "@solana/web3.js"; const connection = new Connection(process.env.RPC_URL!, "confirmed"); // Server-side scripts can use a Keypair-backed Anchor wallet. // Browser apps should use the connected wallet's signing adapter instead. const signer = Keypair.generate(); const wallet = new Wallet(signer); const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed", }); const vault = await VaultImpl.create(connection, NATIVE_MINT, { cluster: "mainnet-beta", }); console.log({ vault: vault.vaultPda.toBase58(), tokenVault: vault.tokenVaultPda.toBase58(), lpMint: vault.vaultState.lpMint.toBase58(), }); ``` ## Read Vault State ```typescript theme={"system"} await vault.refreshVaultState(); const lpSupply = await vault.getVaultSupply(); const withdrawableAmount = await vault.getWithdrawableAmount(); const userLpBalance = await vault.getUserBalance(wallet.publicKey); console.log({ totalAmount: vault.vaultState.totalAmount.toString(), withdrawableAmount: withdrawableAmount.toString(), lpSupply: lpSupply.toString(), userLpBalance: userLpBalance.toString(), }); ``` `getWithdrawableAmount()` computes the unlocked vault amount from on-chain time and `vaultState.lockedProfitTracker`. It is the client-side equivalent of the program's `get_unlocked_amount` simulation flow. ## Deposit `deposit` returns an unsigned `Transaction` with ATA setup and SOL wrapping instructions when needed. ```typescript theme={"system"} const amountInLamports = new BN(1_000_000_000); // 1 SOL const depositTx = await vault.deposit(wallet.publicKey, amountInLamports); depositTx.feePayer = wallet.publicKey; console.log(await connection.simulateTransaction(depositTx)); const depositSignature = await provider.sendAndConfirm(depositTx); console.log("Deposit", depositSignature); ``` ## Withdraw `withdraw` expects the LP token amount to burn. Use `getUserBalance` or `getUnmintAmount` to choose the LP amount. ```typescript theme={"system"} const userLpBalance = await vault.getUserBalance(wallet.publicKey); const withdrawTx = await vault.withdraw(wallet.publicKey, userLpBalance); withdrawTx.feePayer = wallet.publicKey; console.log(await connection.simulateTransaction(withdrawTx)); const withdrawSignature = await provider.sendAndConfirm(withdrawTx); console.log("Withdraw", withdrawSignature); ``` <Warning> The SDK method parameter is named `baseTokenAmount`, but the withdrawal path passes it to the program as LP `unmint_amount`. Treat the value as vault LP tokens to burn. </Warning> ## Affiliate Initialization Affiliate partners pass `affiliateId` when creating the vault client. Deposits and withdrawals then route through the affiliate program wrapper. ```typescript theme={"system"} import { PublicKey } from "@solana/web3.js"; const affiliateVault = await VaultImpl.create(connection, NATIVE_MINT, { cluster: "mainnet-beta", affiliateId: new PublicKey("YOUR_PARTNER_PUBLIC_KEY"), }); const partnerInfo = await affiliateVault.getAffiliateInfo(); console.log({ partnerToken: partnerInfo.partnerToken.toBase58(), feeRatio: partnerInfo.feeRatio.toString(), cumulativeFee: partnerInfo.cummulativeFee.toString(), }); ``` ## Local SDK Tests ```bash theme={"system"} cd vault-sdk/ts-client pnpm install pnpm test pnpm run test-affiliate ``` Some tests and examples expect live RPC access, deployed vault accounts, or local validator fixtures. For production integrations, simulate transactions and test on devnet before sending mainnet transactions. # Dynamic Vault TS SDK Reference Source: https://docs.meteora.ag/developer-guides/dynamic-vault/typescript-sdk/reference Understand @meteora-ag/vault-sdk exports, constants, VaultImpl methods, helper functions, utilities, affiliate support, and integration notes. This page is based on the local `vault-sdk/ts-client` source for `@meteora-ag/vault-sdk`. ```typescript theme={"system"} import VaultImpl, { AFFILIATE_PROGRAM_ID, IDL, KEEPER_URL, PROGRAM_ID, calculateWithdrawableAmount, getAmountByShare, getLpSupply, getOnchainTime, getUnmintAmount, getVaultPdas, } from "@meteora-ag/vault-sdk"; ``` ## Dependencies | Package | Use | | - | - | | `@coral-xyz/anchor` | Anchor `Program`, `AnchorProvider`, and `BN`. | | `@solana/web3.js` | Connections, transactions, instructions, public keys, and system program helpers. | | `@solana/spl-token` | ATA helpers, SPL Token program ID, native mint, mint reads, and token account decoding. | | `bn.js` | Integer arithmetic for token amounts and LP balances. | | `cross-fetch` | Fetch support used by package consumers that query APIs. | | `decimal.js`, `jsbi` | Numeric helpers included by the package. | ## Program IDs And URLs | Export | Value | | - | - | | `PROGRAM_ID` | `24Uqj9JCLxUeoC3hGfh5W3s9FM9uCHDS2SG3LYwBpyTi` | | `AFFILIATE_PROGRAM_ID` | `GacY9YuN16HNRTy7ZWwULPccwvfFSBeNLuAQP7y38Du3` | | `KEEPER_URL["mainnet-beta"]` | `https://merv2-api.mercurial.finance` | | `KEEPER_URL["devnet"]` | `https://dev-keeper.raccoons.dev` | | `KEEPER_URL["testnet"]` | `https://staging-keeper.raccoons.dev` | ## Important Constants | Constant | Meaning | | - | - | | `VAULT_BASE_KEY` | Base key used for standard vault PDA derivation. | | `USDC_MINT`, `USDT_MINT` | Mainnet stablecoin mint constants. | | `VAULT_STRATEGY_ADDRESS` | Default pubkey sentinel used when filtering empty strategy slots. | | `LOCKED_PROFIT_DEGRADATION_DENOMINATOR` | Locked-profit denominator as `BN(1_000_000_000_000)`. | | `SEEDS` | Seed strings used by vault and historical strategy PDA derivations. | ## `VaultImpl.create` ```typescript theme={"system"} static create( connection: Connection, tokenAddress: PublicKey, opt?: { seedBaseKey?: PublicKey; allowOwnerOffCurve?: boolean; cluster?: Cluster; programId?: string; affiliateId?: PublicKey; affiliateProgramId?: string; }, ): Promise<VaultImpl> ``` Creates one hydrated vault client from an underlying token mint. It derives the vault PDA, fetches vault state, fetches the LP mint, and fetches the underlying token mint. ## Static Methods | Method | Signature | Description | | - | - | - | | `createPermissionlessVaultInstruction` | `(connection, payer, tokenMint, opt?) =&gt; Promise&lt;TransactionInstruction&gt;` | Builds the program `initialize` instruction for a token mint. | | `fetchMultipleUserBalance` | `(connection, lpMintList, owner) =&gt; Promise&lt;BN[]&gt;` | Batch fetches a user's ATA balances for multiple vault LP mints. | | `createMultiple` | `(connection, tokenMints, opt?) =&gt; Promise&lt;VaultImpl[]&gt;` | Batch creates hydrated vault clients from token mint addresses. | | `createMultipleWithPda` | `(connection, vaultsPda, opt?) =&gt; Promise&lt;VaultImpl[]&gt;` | Batch creates hydrated vault clients from vault PDA addresses. | ## Instance Properties | Property | Type | Description | | | - | - | - | - | | `tokenMint` | `Mint` | Decoded underlying token mint. | | | `tokenLpMint` | `Mint` | Decoded vault LP mint. | | | `vaultPda` | `PublicKey` | Vault account PDA. | | | `tokenVaultPda` | `PublicKey` | Vault-owned reserve token account PDA. | | | `vaultState` | `VaultState` | Decoded Anchor vault account state. | | | `seedBaseKey` | \`PublicKey | undefined\` | Optional base key override stored on the client. | ## Instance Methods | Method | Signature | Description | | - | - | - | | `getUserBalance` | `(owner: PublicKey) =&gt; Promise&lt;BN&gt;` | Reads the user's vault LP balance. With affiliate enabled, reads the affiliate user PDA's LP token account. | | `getVaultSupply` | `() =&gt; Promise&lt;BN&gt;` | Refetches the LP mint and returns current LP supply. | | `getWithdrawableAmount` | `() =&gt; Promise&lt;BN&gt;` | Reads on-chain time and computes unlocked vault amount from `vaultState`. | | `refreshVaultState` | `() =&gt; Promise&lt;void&gt;` | Refetches vault state and the underlying token mint. | | `deposit` | `(owner: PublicKey, baseTokenAmount: BN) =&gt; Promise&lt;Transaction&gt;` | Builds a transaction to deposit underlying tokens and receive LP tokens. | | `getStrategiesState` | `() =&gt; Promise&lt;StrategyState[]&gt;` | Fetches strategy accounts for non-default strategy slots. | | `withdraw` | `(owner: PublicKey, baseTokenAmount: BN) =&gt; Promise&lt;Transaction&gt;` | Builds a transaction to burn LP tokens and withdraw underlying tokens. | | `getAffiliateInfo` | `() =&gt; Promise&lt;AffiliateInfo&gt;` | Fetches affiliate partner account state when `affiliateId` is configured. | <Warning> `withdraw` passes its `baseTokenAmount` parameter as the program's LP `unmint_amount`. Use LP token units, not underlying token units. </Warning> ## Helper Exports | Function | Signature | Description | | - | - | - | | `getAmountByShare` | `(share, withdrawableAmount, totalSupply) =&gt; BN` | Converts LP token share to underlying token amount. | | `getUnmintAmount` | `(amount, withdrawableAmount, totalSupply) =&gt; BN` | Converts desired underlying amount to LP tokens to burn. | | `calculateWithdrawableAmount` | `(onChainTime, vaultState) =&gt; BN` | Calculates unlocked amount after locked profit degradation. | ## Utility Exports | Function | Description | | - | - | | `getVaultPdas(tokenMint, programId, seedBaseKey?)` | Derives `vaultPda`, `tokenVaultPda`, and `lpMintPda`. | | `getOnchainTime(connection)` | Reads the clock sysvar and returns `unixTimestamp`. | | `getLpSupply(connection, tokenMint)` | Reads token supply for a mint and returns a `BN`. | | `deserializeAccount(data)` | Decodes SPL token account bytes. | | `deserializeMint(data)` | Decodes SPL mint bytes. | `deserializeAccount` and `deserializeMint` are defined in the source utilities but are not exported from the package root in the current `ts-client/index.ts`. ## SOL Handling | Flow | SDK behavior | | - | - | | Deposit into SOL vault | Creates the user's wrapped SOL ATA if needed, transfers lamports into it, and syncs native token state before `deposit`. | | Withdraw from SOL vault | Adds a close-account post-instruction for the user's wrapped SOL ATA. | ## Affiliate Support When `affiliateId` is passed to `create`, the SDK initializes an affiliate program client and changes user balance, deposit, and withdraw account planning. | Item | Behavior | | - | - | | Partner token account | ATA for the underlying token mint and partner public key. | | Partner PDA | Derived from vault PDA and partner token account under the affiliate program. | | User PDA | Derived from partner PDA and user wallet under the affiliate program. | | User LP token account | ATA for the vault LP mint owned by the affiliate user PDA. | ## Integration Notes | Topic | Detail | | - | - | | Transaction return values | `deposit` and `withdraw` return unsigned `Transaction` objects. The caller signs, simulates, and sends. | | State freshness | `deposit` and `withdraw` call `refreshVaultState()` internally. For displayed balances, refresh before showing final amounts. | | RPC batching | `createMultiple`, `createMultipleWithPda`, and `fetchMultipleUserBalance` use chunked batch reads for dashboards and portfolios. | | Strategy withdrawals | `withdraw` chooses reserve withdrawal when reserve liquidity is enough. Otherwise it selects the strategy with the highest `currentLiquidity`. | | Source and IDL drift | Use the SDK reference for public client behavior. For low-level instruction behavior, compare against the current program source. | # Presale Vault Changelog Source: https://docs.meteora.ag/developer-guides/presale-vault/changelog Track Presale Vault program and TypeScript SDK release notes, integration changes, and known source-material gaps. <Tip> Track Presale Vault releases here. </Tip> <Update label="presale 0.1.1" description="Improvement in Calculation and Security"> ## Release summary | Component | Version | PR | | - | - | - | | Program | `0.1.1` | [presale #31](https://github.com/MeteoraAg/presale/pull/33) | | TypeScript SDK | `0.0.6` | [presale-sdk #9](https://github.com/MeteoraAg/presale-sdk/pull/9) | ## What We Shipped * Improvement in Calculation * Improvement in Security ## What To Do <div> <table> <thead> <tr> <th>Integrators</th> <th>What Changed</th> <th>What To Do</th> </tr> </thead> <tbody> <tr> <td><strong>Partners</strong></td> <td> <ul> <li>Calculation Updates</li> </ul> </td> <td> <ul> <li>Bump your SDK version to <code>@meteora-ag/presale-sdk\@0.0.6</code> to start testing.</li> </ul> </td> </tr> </tbody> </table> </div> ## Program: `presale` `0.1.1` Program ID (mainnet and devnet): `presSVxnf9UU8jMxhgSMqaRwNiT36qeBdNeTRKjTdbj` [Program PR #33](https://github.com/MeteoraAg/presale/pull/33) ### Fixed * Calculation of `vesting_start_time`, `vesting_end_time`, `lock_start_time`, and `lock_end_time` now correctly handled * Added missing `params.validate()` call in `handle_initialize_fixed_price_presale_args` * Fixed issue where fixed price presale could not complete if `minimum_cap` and `maximum_cap` were configured to unreachable values * Fixed bug where presale registry could consume supply from another registry's presale ### Added * Added option to allow fixed price presale to disable withdraw * Added option to allow both fixed price and FCFS presales to prevent ending presale early when cap is reached * Added closure of `MerkleRoofConfig` account * Added support for the `security_txt!` macro ### Changed * Presale mode now reserves `presale_mode_raw_data: [u128; 3]`, used for storing mode-specific data (e.g. price in fixed mode) * Removed `lock_start_time` and `lock_end_time` fields as they can be represented by `presale_end_time` and `vesting_start_time` and were unused * For permissioned mode: * In dynamic price presale, `buyer_minimum_cap` must be 1 and `buyer_maximum_cap` must be `presale_maximum_cap` * I
프로젝트로 돌아가기