Meteora 백서

Meteora

원문

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

wrapper | Use | | - | - | | `FeeVaultAccount::deserialize(data)` | Decode root vault state. | | `StakeEscrowAccount::deserialize(data)` | Decode a user stake escrow. | | `UnstakeAccount::deserialize(data)` | Decode a pending unstake account. | | `TopListMetadataAccount::deserialize(data)` | Decode only the top-list header. | | `FullBalanceListMetadataAccount::deserialize(data)` | Decode only the full-balance-list header. | Top and full balance list entries are appended after the account discriminator and metadata header. Use the TypeScript decoder logic as a model if you need to parse appended entries in Rust. ## Error Decoding `StakeForFeeError` implements `From<StakeForFeeError> for ProgramError`, `DecodeError`, and `PrintProgramError`. | Code range | Meaning | | - | - | | `6000` to `6022` | Stake2Earn custom errors from `stake_for_fee`. | See the [program error reference](/developer-guides/stake2earn/program/errors) for the full table. # Stake2Earn TypeScript SDK Examples Source: https://docs.meteora.ag/developer-guides/stake2earn/typescript-sdk/examples Explore Stake2Earn TypeScript examples for connecting to a vault, creating a vault, staking, reading balances, claiming fees, requesting unstake, canceling unstake, and withdrawing released stake. These examples are based on the local `stake-for-fee-sdk/ts-client/src/examples` source and the public SDK surface. ## Connect To A Vault ```typescript theme={"system"} import StakeForFee from "@meteora-ag/m3m3"; import { Connection, PublicKey } from "@solana/web3.js"; const connection = new Connection(process.env.RPC_URL!, "confirmed"); const pool = new PublicKey("G2MRSjNjCbFUmMf32Z1aXYhy6pc1ihLyYg6orKedyjJG"); const feeVault = await StakeForFee.create(connection, pool); console.log("vault", feeVault.feeVaultKey.toBase58()); console.log("stake mint", feeVault.accountStates.feeVault.stakeMint.toBase58()); ``` ## Create A Fee Vault ```typescript theme={"system"} import StakeForFee from "@meteora-ag/m3m3"; import { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; const pool = new PublicKey("..."); const stakeMint = new PublicKey("..."); const currentSlot = await connection.getSlot("confirmed"); const currentTimestamp = await connection.getBlockTime(currentSlot); const tx = await StakeForFee.createFeeVault( connection, pool, stakeMint, payer.publicKey, { topListLength: 10, unstakeLockDuration: new BN(86_400), secondsToFullUnlock: new BN(604_800), startFeeDistributeTimestamp: new BN(currentTimestamp! + 10), }, ); ``` `createFeeVault` fetches the DAMM v1 pool, infers the quote mint as the other pool mint, derives the vault/list/token accounts, creates the DAMM v1 lock escrow if missing, and returns one transaction. ## Create A Fee Vault With Explicit Mints ```typescript theme={"system"} const tx = await StakeForFee.createFeeVaultWithParams( connection, pool, payer.publicKey, stakeMint, quoteMint, { topListLength: 10, unstakeLockDuration: new BN(86_400), secondsToFullUnlock: new BN(604_800), startFeeDistributeTimestamp: new BN(currentTimestamp! + 10), }, ); ``` Use `createFeeVaultInstructions` when you need to compose the vault creation instructions into a larger transaction builder. ## Lock DAMM v1 LP To The Vault The local SDK examples lock DAMM v1 LP with `@meteora-ag/dynamic-amm-sdk` after the Stake2Earn vault is created: ```typescript theme={"system"} import AmmImpl from "@meteora-ag/dynamic-amm-sdk"; import { deriveFeeVault, STAKE_FOR_FEE_PROGRAM_ID } from "@meteora-ag/m3m3"; import Decimal from "decimal.js"; const amm = await AmmImpl.create(connection, pool); const feeVaultKey = deriveFeeVault(pool, STAKE_FOR_FEE_PROGRAM_ID); const tx = await amm.lockLiquidity(feeVaultKey, lpAmount, owner.publicKey, { stakeLiquidity: { ratio: new Decimal(1), }, }); ``` The lock escrow owner must be the Stake2Earn vault PDA. Fees from that locked LP flow into Stake2Earn distribution instead of the creator wallet. ## Stake Tokens ```typescript theme={"system"} import BN from "bn.js"; await feeVault.refreshStates(); const stakeAmount = new BN("1000000000"); const tx = await feeVault.stake(stakeAmount, owner.publicKey); ``` `stake` includes `initializeStakeEscrow` when needed. If you have just changed vault state in another transaction, call `refreshStates()` before building the stake transaction. ## Read Stake And Claimable Balance ```typescript theme={"system"} await feeVault.refreshStates(); const { stakeEscrow, unclaimFee } = await feeVault.getUserStakeAndClaimBalance(owner.publicKey); if (stakeEscrow) { console.log("active stake", stakeEscrow.stakeAmount.toString()); console.log("claimable token A", unclaimFee.feeA?.toString()); console.log("claimable token B", unclaimFee.feeB?.toString()); } ``` For a top-list staker, the SDK calculates newly released fees from current vault and lock escrow state before returning `unclaimFee`. ## Claim Fees ```typescript theme={"system"} import { U64_MAX } from "@meteora-ag/m3m3"; const tx = await feeVault.claimFee(owner.publicKey, U64_MAX); ``` `claimFee` claims quote token fees up to `maxFee`. Any base/stake token fee is automatically added back to the user's stake escrow. ## Request Unstake ```typescript theme={"system"} import { Keypair } from "@solana/web3.js"; const unstake = Keypair.generate(); const tx = await feeVault.unstake( stakeEscrow.stakeAmount, unstake.publicKey, owner.publicKey, ); tx.partialSign(unstake); ``` Store the `unstake.publicKey`. It is required for `cancelUnstake` and `withdraw`. ## Cancel Unstake ```typescript theme={"system"} const tx = await feeVault.cancelUnstake(unstake.publicKey, owner.publicKey); ``` Canceling returns the requested amount to active stake and closes the `Unstake` account. ## Withdraw Released Stake ```typescript theme={"system"} const tx = await feeVault.withdraw(unstake.publicKey, owner.publicKey); ``` The transaction fails until the current on-chain timestamp is at or after the `Unstake.release_at` value. ## Find User Vaults And Unstakes ```typescript theme={"system"} const vaults = await StakeForFee.getAllStakedVaultByUser( connection, owner.publicKey, ); const unstakeRecords = await StakeForFee.getUnstakeByUser( connection, owner.publicKey, feeVault.feeVaultKey, ); ``` ## Gotchas | Gotcha | Recommendation | | - | - | | `claimFee` returns one transaction | Send the returned transaction directly; do not iterate over it. | | `unstake` needs a new signer | Generate and partial-sign with the `Unstake` keypair. | | Cached account state | Call `refreshStates()` before building transactions after recent vault mutations. | | Top-list replacement accounts | Let the SDK build stake/claim/unstake transactions unless you are comfortable supplying replacement stake escrows manually. | | Quote-only user claim | Expect only the quote token to leave the vault on `claimFee`; the stake/base token side is restaked. | # Stake2Earn TypeScript SDK Getting Started Source: https://docs.meteora.ag/developer-guides/stake2earn/typescript-sdk/getting-started Learn how to install @meteora-ag/m3m3, create a Stake2Earn client, read vault state, build staking transactions, and handle claim and unstake flows. The Stake2Earn TypeScript SDK is published as `@meteora-ag/m3m3`. It wraps the `stake_for_fee`, DAMM v1, and Dynamic Vault account bundles needed to build Stake2Earn transactions. <Note> The SDK builds unsigned transactions. Your app is responsible for setting any wallet-specific signing flow, simulating, signing, and submitting the returned transaction. </Note> <CardGroup> <Card title="SDK Repository" icon="node-js" href="https://github.com/MeteoraAg/stake-for-fee-sdk/tree/main/ts-client"> Source for `@meteora-ag/m3m3`, examples, tests, IDLs, helpers, and build scripts. </Card> <Card title="NPM Package" icon="npm" href="https://www.npmjs.com/package/@meteora-ag/m3m3"> Published Stake2Earn TypeScript SDK package. </Card> </CardGroup> ## Installation Install the SDK and the packages you commonly import directly in app code: <Tabs> <Tab title="npm"> ```bash theme={"system"} npm install @meteora-ag/m3m3 @solana/web3.js @solana/spl-token bn.js ``` </Tab> <Tab title="pnpm"> ```bash theme={"system"} pnpm install @meteora-ag/m3m3 @solana/web3.js @solana/spl-token bn.js ``` </Tab> <Tab title="yarn"> ```bash theme={"system"} yarn add @meteora-ag/m3m3 @solana/web3.js @solana/spl-token bn.js ``` </Tab> </Tabs> ## Create A Client Create a `StakeForFee` instance from a DAMM v1 pool address. The SDK derives the Stake2Earn vault PDA, top staker list, full balance list, lock escrow, and related Dynamic Vault state. ```typescript theme={"system"} import StakeForFee from "@meteora-ag/m3m3"; import { Connection, PublicKey } from "@solana/web3.js"; const connection = new Connection(process.env.RPC_URL!, "confirmed"); const poolAddress = new PublicKey( "G2MRSjNjCbFUmMf32Z1aXYhy6pc1ihLyYg6orKedyjJG", ); const stakeForFee = await StakeForFee.create(connection, poolAddress); console.log(stakeForFee.feeVaultKey.toBase58()); console.log(stakeForFee.accountStates.feeVault.configuration); ``` ## Build Transactions ### Stake `stake` creates the stake escrow first when it does not exist, estimates compute units, and adds replacement top-list accounts from the current cached state. ```typescript theme={"system"} import BN from "bn.js"; const amount = new BN("1000000000"); const tx = await stakeForFee.stake(amount, wallet.publicKey); ``` ### Claim Fees `claimFee` transfers only the quote token side to the user. The stake/base token side is automatically restaked by the program. ```typescript theme={"system"} import { U64_MAX } from "@meteora-ag/m3m3"; const tx = await stakeForFee.claimFee(wallet.publicKey, U64_MAX); ``` ### Request Unstake `unstake` initializes a new `Unstake` account. The new keypair must sign the final transaction. ```typescript theme={"system"} import { Keypair } from "@solana/web3.js"; const unstakeKeypair = Keypair.generate(); const tx = await stakeForFee.unstake( amount, unstakeKeypair.publicKey, wallet.publicKey, ); tx.partialSign(unstakeKeypair); ``` ### Cancel Or Withdraw ```typescript theme={"system"} const cancelTx = await stakeForFee.cancelUnstake( unstakeKeypair.publicKey, wallet.publicKey, ); const withdrawTx = await stakeForFee.withdraw( unstakeKeypair.publicKey, wallet.publicKey, ); ``` `withdraw` only succeeds after the `Unstake.release_at` timestamp has passed. ## Read User State Refresh cached vault state before calculating claimable balances for a user-facing surface. ```typescript theme={"system"} await stakeForFee.refreshStates(); const userState = await stakeForFee.getUserStakeAndClaimBalance( wallet.publicKey, ); if (userState.stakeEscrow) { console.log(userState.stakeEscrow.stakeAmount.toString()); console.log(userState.unclaimFee.feeA?.toString()); console.log(userState.unclaimFee.feeB?.toString()); } ``` ## Create A Vault Vault creation is an integrator or launch workflow. The pool must be a DAMM v1 constant-product pool, the quote mint must be SOL or USDC, and the lock escrow must be owned by the derived vault PDA. ```typescript theme={"system"} import StakeForFee from "@meteora-ag/m3m3"; import { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; const tx = await StakeForFee.createFeeVault( connection, poolAddress, stakeMint, payer.publicKey, { topListLength: 10, unstakeLockDuration: new BN(86_400), secondsToFullUnlock: new BN(604_800), startFeeDistributeTimestamp: new BN(startTimestamp), }, ); ``` The SDK also exposes `createFeeVaultWithParams` and `createFeeVaultInstructions` when you already know both pool mints or need raw instructions. ## Contributor Commands If you have cloned the SDK repository and want to run the built-in tests: ```bash theme={"system"} cd stake-for-fee-sdk/ts-client pnpm install pnpm run build pnpm test ``` ## Next Pages <CardGroup> <Card title="SDK Examples" icon="code" href="/developer-guides/stake2earn/typescript-sdk/examples"> Common vault, stake, claim, unstake, and read examples. </Card> <Card title="SDK Reference" icon="book" href="/developer-guides/stake2earn/typescript-sdk/reference"> Complete function, helper, constant, and type map for `@meteora-ag/m3m3`. </Card> </CardGroup> # Stake2Earn TypeScript SDK Reference Source: https://docs.meteora.ag/developer-guides/stake2earn/typescript-sdk/reference Understand @meteora-ag/m3m3 exports, dependencies, program IDs, constants, transaction builders, state readers, PDA helpers, calculation helpers, and helper utilities. This page maps the public source surface of `@meteora-ag/m3m3`. Use the package types for exact parameter shapes when building a production integration. ```typescript theme={"system"} import StakeForFee, { STAKE_FOR_FEE_PROGRAM_ID, DYNAMIC_AMM_PROGRAM_ID, DYNAMIC_VAULT_PROGRAM_ID, U64_MAX, deriveFeeVault, deriveStakeEscrow, } from "@meteora-ag/m3m3"; ``` ## Dependencies | Package | Version in `ts-client/package.json` | | - | - | | `@coral-xyz/anchor` | `0.29.0` | | `@coral-xyz/borsh` | `^0.30.1` | | `@solana/spl-token` | `^0.4.8` | | `@solana/web3.js` | `^1.98.0` | | `bn.js` | `^5.2.1` | | `decimal.js` | `^10.4.3` | ## Program IDs | Constant | Value | | - | - | | `STAKE_FOR_FEE_PROGRAM_ID` | `FEESngU3neckdwib9X3KWqdL7Mjmqk9XNp3uh5JbP4KP` | | `DYNAMIC_AMM_PROGRAM_ID` | `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB` | | `DYNAMIC_VAULT_PROGRAM_ID` | `24Uqj9JCLxUeoC3hGfh5W3s9FM9uCHDS2SG3LYwBpyTi` | ## Constants | Constant | Value or type | Use | | - | - | - | | `MAX_COMPUTE_UNITS` | `1_400_000` | Default compute unit limit helper value. | | `FULL_BALANCE_LIST_HARD_LIMIT` | `BN(10000)` | Public full-balance list hard limit. | | `U64_MAX` | `BN("18446744073709551615")` | Common max quote-claim cap for `claimFee`. | | `VAULT_WITH_NON_PDA_BASED_LP_MINTS` | `Map<string, PublicKey>` | Overrides for legacy Dynamic Vault LP mints that are not PDA-derived. | | `MIN_LOCK_ESCROW_CLAIM_FEE_DURATION` | `BN(300)` | Minimum lock escrow claim interval in seconds. | ## Core Client | Method | Returns | Use | | - | - | - | | `StakeForFee.create(connection, pool, opt?)` | `Promise<StakeForFee>` | Preferred client factory. Derives the vault/list/lock escrow keys and fetches all account state. | | `new StakeForFee(...)` | `StakeForFee` | Internal constructor used after account state has been fetched. | | `StakeForFee.fetchAccountStates(connection, feeVaultKey, topStakerListKey, fullBalanceListKey, pool, opt?)` | `Promise<AccountStates>` | Fetch and decode `FeeVault`, list states, DAMM v1 pool, Dynamic Vault accounts, token accounts, mints, lock escrow, and clock. | | `refreshStates()` | `Promise<AccountStates>` | Re-fetch current account state and return the previous cached state. | The `opt` object supports `stakeForFeeProgramId`, `dynamicAmmProgramId`, and `dynamicVaultProgramId`. ## Transaction Builders | Method | Returns | Use | | - | - | - | | `StakeForFee.createFeeVault(connection, pool, stakeMint, payer, param?, opt?)` | `Promise<Transaction>` | Create a vault, deriving quote mint from the DAMM v1 pool. Creates the DAMM v1 lock escrow if missing. | | `StakeForFee.createFeeVaultWithParams(connection, pool, payer, stakeMint, quoteMint, param?, opt?)` | `Promise<Transaction>` | Create a vault with explicit stake and quote mints. | | `StakeForFee.createFeeVaultInstructions(connection, pool, payer, stakeMint, quoteMint, param?, opt?)` | `Promise<TransactionInstruction[]>` | Return raw vault-creation instructions for composition. | | `initializeStakeEscrow(owner)` | `Promise<Transaction>` | Create the owner's stake escrow for this vault. | | `stake(maxAmount, owner, replaceableTopStakerCount = 2)` | `Promise<Transaction>` | Build a stake transaction, adding stake escrow initialization and top-list replacement accounts when needed. | | `claimFee(owner, maxFee)` | `Promise<Transaction>` | Build a fee claim transaction. Only quote token is transferred to the user; base/stake token is restaked. | | `unstake(amount, unstakeKeypair, owner)` | `Promise<Transaction>` | Build a `request_unstake` transaction. `unstakeKeypair` is a public key for a new signer account. | | `cancelUnstake(unstakeKey, owner)` | `Promise<Transaction>` | Cancel a pending unstake and return the amount to active stake. | | `withdraw(unstakeKey, owner)` | `Promise<Transaction>` | Withdraw released stake after the cooldown. | ## Account Scanners | Method | Returns | Use | | - | - | - | | `StakeForFee.getAllStakedVaultByUser(connection, owner, opt?)` | User stake entries with vault, unstake list, unclaimed fees, and pool info | Find all stake escrows owned by a wallet. | | `StakeForFee.getUnstakeByUser(connection, owner, feeVault)` | Program account list | Find open unstake records for a user and vault. | | `StakeForFee.getAllFeeVault(connection, programId?)` | Program account list | Fetch all `FeeVault` accounts for the program. | ## Balance And Fee Helpers | Method or helper | Returns | Use | | | - | - | - | - | | `getUserStakeAndClaimBalance(user)` | Stake escrow plus `unclaimFee` | Read a user's active stake and claimable fees using current cached vault state. | | | `getStakeEscrowPendingFees(stakeEscrow)` | `[BN, BN]` | Calculate pending token A and token B fees for a stake escrow. | | | `StakeForFee.getFarmPendingClaimFees(args)` | `[BN, BN]` | Calculate pending lock escrow fees available to claim from DAMM v1. | | | `StakeForFee.getFarmReleasedFees(args)` | `[BN, BN]` | Calculate currently released fees after applying the vault's drip duration. | | | `getTopStakerListEntryStakeAmount()` | `BN` | Minimum stake amount needed to enter the current top list. | | | `findLargestStakerNotInTopListFromFullBalanceList(lookupNumber)` | `PublicKey[]` | Find candidate stake escrows outside the top list. | | | `findReplaceableTopStaker(lookupNumber)` | `PublicKey[]` | Find current top stakers that can be replaced. | | | `findSmallestStakeEscrowInFullBalanceList(skipOwner)` | \`PublicKey | null\` | Find the smallest tracked full-balance entry for reclaim handling. | ## Exported Helpers ### PDA Helpers | Helper | Seeds | | - | - | | `deriveFeeVault(pool, programId)` | `["vault", pool]` | | `deriveTopStakerList(vault, programId)` | `["list", vault]` | | `deriveFullBalanceList(vault, programId)` | `["balance", vault]` | | `deriveStakeEscrow(vault, owner, programId)` | `["escrow", vault, owner]` | | `deriveLockEscrowPda(pool, owner, ammProgram)` | DAMM v1 `["lock_escrow", pool, owner]` | | `deriveLpMint(poolAddress, programId)` | DAMM v1 `["lp_mint", poolAddress]` | ### Program And Account Helpers | Helper | Use | | - | - | | `createStakeFeeProgram(connection, programId)` | Create an Anchor program for `stake_for_fee`. | | `createDynamicAmmProgram(connection, programId)` | Create an Anchor program for DAMM v1. | | `createDynamicVaultProgram(connection, programId)` | Create an Anchor program for Dynamic Vault. | | `getOrCreateStakeEscrowInstruction(connection, feeVaultKey, ownerKey, programId)` | Return the stake escrow PDA and an initialize instruction when absent. | | `getOrCreateATAInstruction(connection, tokenMint, owner, payer?, allowOwnerOffCurve?)` | Return an ATA and optional create instruction. | | `decodeFullBalanceState(program, account)` | Decode full balance list metadata and appended `StakerBalance` entries. | | `decodeTopStakerListState(program, feeVault, account)` | Decode top list metadata and appended `StakerMetadata` entries. | ### Calculation Helpers | Helper | Use | | - | - | | `findLargestStakerNotInTopListFromFullBalanceList` | Sort and return largest non-top-list stakers from a decoded full balance list. | | `findReplaceableTopStaker` | Sort and return smallest replaceable top stakers. | | `getTopStakerListStateEntryStakeAmount` | Compute minimum top-list entry amount. | | `calculateFeeFarmPerformance` | Estimate perform
프로젝트로 돌아가기