bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 36쪽
g accounts described by `TransferHookAccountsInfo`.
| Remaining account slice | Meaning |
| - | - |
| `TransferHookBase` | Extra accounts for base-token transfer-hook CPIs. |
| `TransferHookBaseReferral` | Extra accounts for base-token referral transfers when a referral account is present. |
Standard swap instructions reject `TransferHookPool` accounts, and `swap2_with_transfer_hook` rejects standard `VirtualPool` accounts with `PoolTypeMismatch`.
## Migration Instructions
| Instruction | Destination | SDK path | Purpose |
| - | - | - | - |
| `create_locker` | DAMM v1 or DAMM v2 support flow | `client.migration.createLocker` | Create the locker escrow when locked vesting is configured. |
| `withdraw_leftover` | DAMM v1 or DAMM v2 | `client.migration.withdrawLeftover` | Withdraw leftover base tokens after migration. |
| `migration_meteora_damm_create_metadata` | DAMM v1 | `client.migration.createDammV1MigrationMetadata` | Create metadata before DAMM v1 migration. |
| `migrate_meteora_damm` | DAMM v1 | `client.migration.migrateToDammV1` | Migrate a completed DBC pool to DAMM v1. |
| `migrate_meteora_damm_lock_lp_token` | DAMM v1 | `client.migration.lockDammV1LpToken` | Lock permanent LP allocation for partner or creator. |
| `migrate_meteora_damm_claim_lp_token` | DAMM v1 | `client.migration.claimDammV1LpToken` | Claim partner or creator LP allocation. |
| `migration_damm_v2_create_metadata` | DAMM v2 | Deprecated | Deprecated since program `0.1.7`; DAMM v2 migration no longer needs a separate metadata account. |
| `migration_damm_v2` | DAMM v2 | `client.migration.migrateToDammV2` | Migrate a completed DBC pool to DAMM v2. |
| `withdraw_migration_fee` | DAMM v1 or DAMM v2 | `client.partner.partnerWithdrawMigrationFee`, `client.creator.creatorWithdrawMigrationFee` | Withdraw partner or creator migration fee. Uses `flag` to select the fee side. |
DAMM v1 migration instructions remain for existing pools. New configs and new pools cannot select `MigrationOption::MeteoraDamm`. DAMM v2 migration uses a DAMM v2 config with `CreatePoolWithoutMintValidation` so a DBC-badged quote mint can still graduate. DBC still requires the quote mint transfer fee to be zero at migration time.
## Operator Instructions
| Instruction | Args | Purpose |
| - | - | - |
| `create_token_badge` | None | Operator with `CreateTokenBadge` creates a `TokenBadge` PDA for a quote mint that is not permissionless-supported. Rejects permissionless-supported mints and quote mints with a non-zero transfer fee. |
| `close_token_badge` | None | Operator with `CloseTokenBadge` closes a token badge and returns rent. Existing pools that already use the mint keep working. |
| `create_operator_account` | Permission bitmask | Admin creates an operator account with a `u128` permission bitmap. |
| `close_operator_account` | None | Admin closes an operator account. |
| `claim_protocol_fee2` | Selected mint and max amount | Protocol fee authority claims one pool token per call. Replaces the removed `claim_protocol_fee` instruction. |
| `claim_protocol_pool_creation_fee` | None | Operator with `ClaimProtocolFee` claims the protocol share of pool creation fees. |
`claim_protocol_fee` and `zap_protocol_fee` are removed. Use `claim_protocol_fee2` through the protocol fee wrapper program.
# DBC Rust Integration CPI
Source: https://docs.meteora.ag/developer-guides/dbc/rust-integration/cpi
Learn how to plan DBC Anchor CPI integrations with generated bindings, event-CPI accounts, remaining accounts, swap limits, and migration constraints.
Use CPI when your Solana program must call DBC directly, for example to swap, add or remove liquidity, claim fees or rewards, or manage a DBC position as part of a larger protocol instruction.
## Program ID
| Network | Program ID |
| - | - |
| Mainnet Beta | `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` |
| Devnet | `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN` |
## Generated Bindings
For a Rust program in the same workspace, enable the DBC program crate with the `cpi` feature:
```toml theme={"system"}
[dependencies]
dynamic-bonding-curve = { git = "https://github.com/MeteoraAg/dynamic-bonding-curve", package = "dynamic-bonding-curve", features = ["cpi"] }
```
If you are outside the repository, generate bindings from the published IDL and pin the IDL version you tested against.
## CPI Instruction Scope
| Flow | CPI suitability | Notes |
| - | - | - |
| Fee claims | Good | Account lists are smaller and signer roles are clear. |
| Swaps | Possible | Plan slippage, token accounts, token program variants, optional referral account, event authority, and optional instructions sysvar. |
| Pool creation | Possible, but heavier | Requires mint signer, metadata accounts, vault PDAs, token program variant, event authority, and payer accounts. |
| DAMM v1/v2 migration | Advanced | DBC migration instructions perform downstream CPIs into DAMM, locker, and token programs. Prefer SDK-built top-level transactions unless your program owns the keeper flow. |
| Protocol operator flows | Usually internal | Require admin-created operator accounts and protocol permissions. |
## Event CPI Accounts
Most public DBC instructions use `#[event_cpi]`. Include these accounts when constructing CPI contexts:
| Account | Purpose |
| - | - |
| `event_authority` | DBC event authority PDA derived from `__event_authority`. |
| `program` | DBC program account. |
| Destination event authorities | Migration flows may also require DAMM, DAMM v2, or locker event authority accounts. |
## Remaining Accounts
Config and pool creation may require a token badge. Swaps may require the instructions sysvar.
| Case | Remaining account |
| - | - |
| Quote mint is not permissionless-supported | Token badge PDA at remaining account index `0` on `create_config`, `create_config_with_transfer_hook`, and `initialize_virtual_pool_*`. |
| Existing rate limiter base fee is active | `SYSVAR_INSTRUCTIONS_PUBKEY` on swap instructions. |
| `enable_first_swap_with_min_fee` is enabled | `SYSVAR_INSTRUCTIONS_PUBKEY` on swap instructions. |
| Permissionless quote mint, no rate limiter, and no first-swap minimum fee | No extra remaining account is required by these rules. |
The token badge PDA is derived from `["token_badge", quote_mint]`. A DBC badge does not satisfy DAMM v2 mint validation. DAMM v2 migration uses a config with `CreatePoolWithoutMintValidation`.
The program validates single-swap behavior for existing rate limiter pools. The first-swap minimum-fee path also validates that pool initialization appears earlier in the top-level transaction; do not assume a CPI-only path is eligible for that minimum fee.
## Swap CPI Shape
Use `swap2` for new integrations because it supports exact-in, partial-fill, and exact-out modes.
| Mode | Required user limit |
| - | - |
| Exact in | Minimum output amount. |
| Partial fill | Minimum output amount and clear handling of `amount_left`. |
| Exact out | Maximum input amount. |
Before calling DBC from your program:
1. Decode and validate `VirtualPool` and `PoolConfig`.
2. Verify account ownership and data length before deserializing.
3. Use the Rust quote library or TypeScript SDK math to calculate expected amounts.
4. Pass user-controlled slippage limits into your own instruction args.
5. Recheck token mints, vaults, token program IDs, and signer authorities in your account constraints.
## Token Programs
DBC supports SPL Token and Token-2022 base mints. Migration and pool creation account lists differ by token type.
| Token side | Guidance |
| - | - |
| Base mint | Read `PoolConfig.token_type` and `VirtualPool.pool_type`; use the matching token program. |
| Quote mint | Native SOL uses wrapped SOL account handling in SDK-built transactions. CPI integrations must prepare token accounts explicitly. |
| Token-2022 | Include Token-2022 program accounts where required and validate associated token accounts carefully. |
## Common CPI Failures
Some DBC handlers wrap downstream CPIs with account invariant checks. If the downstream CPI unexpectedly changes account owner, data length, or reduces lamports, DBC can return `AccountInvariantViolation`.
| Error | Common CPI cause |
| - | - |
| `InvalidAccount` | PDA, vault, mint, owner, or token program mismatch. |
| `IncorrectATA` | Associated token account owner or mint mismatch. |
| `FailToValidateSingleSwapInstruction` | Missing instructions sysvar or invalid single-swap transaction context on an existing rate-limiter pool. |
| `InvalidTokenBadge` | Quote mint is not permissionless-supported and the token badge remaining account is missing or mismatched. |
| `QuoteMintHasNonZeroTransferFee` | Quote mint current or scheduled transfer fee is not zero. |
| `DeprecatedBaseFeeMode` | CPI attempted to create a config or pool with `BaseFeeMode::RateLimiter`. |
| `DeprecatedMigrationOption` | CPI attempted to create a config or pool with `MigrationOption::MeteoraDamm`. |
| `FirstSwapValidationFailed` | First-swap minimum-fee transaction context does not match program requirements. |
| `AccountInvariantViolation` | Downstream CPI changed protected account invariants. |
| `CpiDisabled` | Downstream protocol zap CPI disabled. |
## Best Practices
| Practice | Why it matters |
| - | - |
| Prefer SDK-built transactions for frontends and bots | The SDK keeps account order, wrapped SOL, event authorities, and remaining accounts aligned with the IDL. |
| Keep CPI account lists explicit | DBC migration and swap flows have many optional and downstream accounts. |
| Pin IDL and program versions | The local IDL is `0.2.1`; regenerate bindings when the IDL changes. |
| Simulate on devnet or localnet | Migration and swap CPI failures are easier to diagnose before mainnet. |
| Store raw event and account data in indexers | `EvtSwap2` and `VirtualPool` state are both needed for reliable charting and progress tracking. |
# DBC Rust Integration Library
Source: https://docs.meteora.ag/developer-guides/dbc/rust-integration/library
Learn how to use the DBC Rust library for exact-in, exact-out, partial-fill, account-state inputs, and tests.
The `dynamic-bonding-curve` repository includes a Rust crate at `dynamic-bonding-curve-sdk`. It depends on the on-chain `dynamic-bonding-curve` crate and reuses program state and math types.
## Install
Use the crate from the local workspace or a pinned Git revision:
```toml theme={"system"}
[dependencies]
dynamic-bonding-curve-sdk = { git = "https://github.com/MeteoraAg/dynamic-bonding-curve", package = "dynamic-bonding-curve-sdk" }
```
For local development inside the program repository:
```bash theme={"system"}
cd dynamic-bonding-curve
cargo test -p dynamic-bonding-curve-sdk
```
## What It Provides
| Module | Function | Use |
| - | - | - |
| `quote_exact_in` | `quote_exact_in` | Quote a swap for a fixed input amount. |
| `quote_exact_out` | `quote_exact_out` | Quote the required input for a fixed output amount. |
| `quote_partial_fill` | `quote_partial_fill` | Quote a partial-fill swap near the end of a bonding curve. |
The crate is useful for Rust services, quote engines, tests, and keepers that already decode `VirtualPool` and `PoolConfig` accounts.
## Quote Inputs
All three quote helpers require current pool and config state:
| Parameter | Meaning |
| - | - |
| `pool: &VirtualPool` | Current virtual pool account data. |
| `config: &PoolConfig` | Pool config account referenced by `pool.pool_state.config`. |
| `swap_base_for_quote: bool` | `true` sells base for quote; `false` buys base with quote. |
| `current_timestamp: u64` | Current cluster timestamp. Used when `config.activation_type` is timestamp. |
| `current_slot: u64` | Current cluster slot. Used when `config.activation_type` is slot. |
| `has_referral: bool` | Whether a referral fee should be included. Used by exact-in and partial-fill quotes. |
| `eligible_for_first_swap_with_min_fee: bool` | Whether the quote should use the first-swap minimum fee path. Set this only when the transaction satisfies the program validation path. |
## Exact-In Quote
```rust theme={"system"}
pub fn quote_exact_in(
pool: &VirtualPool,
config: &PoolConfig,
swap_base_for_quote: bool,
current_timestamp: u64,
current_slot: u64,
in_amount: u64,
has_referral: bool,
eligible_for_first_swap_with_min_fee: bool,
) -> anyhow::Result<SwapResult2>
```
Use this for `swap2` exact-in mode, then apply your slippage policy before building the transaction.
## Exact-Out Quote
```rust theme={"system"}
pub fn quote_exact_out(
pool: &VirtualPool,
config: &PoolConfig,
swap_base_for_quote: bool,
current_timestamp: u64,
current_slot: u64,
out_amount: u64,
eligible_for_first_swap_with_min_fee: bool,
) -> anyhow::Result<SwapResult2>
```
Exact-out quotes return the input amount required to receive `out_amount`. Apply a maximum input bound before sending the transaction.
## Partial-Fill Quote
```rust theme={"system"}
pub fn quote_partial_fill(
pool: &VirtualPool,
config: &PoolConfig,
swap_base_for_quote: bool,
current_timestamp: u64,
current_slot: u64,
in_amount: u64,
has_referral: bool,
eligible_for_first_swap_with_min_fee: bool,
) -> anyhow::Result<SwapResult2>
```
Partial fill is useful when the pool is close to `migration_quote_threshold` and a full exact-in swap might cross the migration boundary.
## Return Data
`SwapResult2` contains the values needed by quote engines and transaction builders:
| Field | Use |
| - | - |
| `included_fee_input_amount` | Input amount before excluded-fee adjustment. |
| `excluded_fee_input_amount` | Amount that moves the curve after fee handling. |
| `amount_left` | Unused amount in partial-fill flows. |
| `output_amount` | Output token amount. |
| `next_sqrt_price` | Post-swap Q64.64 sqrt price. |
| `trading_fee`, `protocol_fee`, `referral_fee` | Fee split for the swap. |
## Tests
The Rust crate includes tests for exact-out and partial-fill behavior, plus binary fixtures for configs and pools with quote-token and both-token fee modes.
| Path | Use |
| - | - |
| `dynamic-bonding-curve-sdk/src/tests/test_quote_exact_out.rs` | Exact-out quote tests. |
| `dynamic-bonding-curve-sdk/src/tests/test_quote_partial_fill.rs` | Partial-fill quote tests. |
| `dynamic-bonding-curve-sdk/fixtures/*.bin` | Serialized pool and config fixtures. |
# DBC TS SDK Examples
Source: https://docs.meteora.ag/developer-guides/dbc/typescript-sdk/examples
Explore TypeScript examples for DBC config creation, pool creation, swap quotes, swaps, fee claims, migration, and state reads.
These examples are based on the local `dynamic-bonding-curve-sdk` examples and tests. They focus on transaction construction patterns. For the full method catalog, see the [SDK Reference](/developer-guides/dbc/typescript-sdk/reference).
## Setup
```typescript theme={"system"}
import BN from "bn.js";
import { NATIVE_MINT } from "@solana/spl-token";
import { Connection, Keypair, PublicKey } from "@solana/web3.js";
import {
ActivationType,
BaseFeeMode,
buildCurveWithCustomSqrtPrices,
CollectFeeMode,
createSqrtPrices,
DammV2BaseFeeMode,
DammV2DynamicFeeMode,
deriveDbcPoolAddress,
DynamicBondingCurveClient,
MigratedCollectFeeMode,
MigrationFeeOption,
MigrationOption,
SwapMode,
TokenDecimal,
TokenType,
TokenAuthorityOption,
} from "@meteora-ag/dynamic-bonding-curve-sdk";
const connection = new Connection(process.env.RPC_URL!, "confirmed");
const client = DynamicBondingCurveClient.create(connection, "confirmed");
```
## Build A Curve Config
`buildCurveWithCustomSqrtPrices` gives explicit control over the curve checkpoints. Other supported helpers are listed in the [SDK Reference](/developer-guides/dbc/typescript-sdk/reference#curve-builders).
```typescript theme={"system"}
const sqrtPrices = createSqrtPrices(
[0.000000001, 0.00000000105, 0.000000002, 0.000001],
TokenDecimal.SIX,
TokenDecimal.NINE
);
const curveConfig = buildCurveWithCustomSqrtPrices({
token: {
tokenType: TokenType.SPLToken,
tokenBaseDecimal: TokenDecimal.SIX,
tokenQuoteDecimal: TokenDecimal.NINE,
tokenAuthorityOption: TokenAuthorityOption.PartnerUpdateAuthority,
totalTokenSupply: 1_000_000_000,
leftover: 1_000,
},
fee: {
baseFeeParams: {
baseFeeMode: BaseFeeMode.FeeSchedulerExponential,
feeSchedulerParam: {
startingFeeBps: 9000,
endingFeeBps: 120,
numberOfPeriod: 60,
totalDuration: 60,
},
},
dynamicFeeEnabled: true,
collectFeeMode: CollectFeeMode.QuoteToken,
creatorTradingFeePercentage: 0,
poolCreationFee: 1,
enableFirstSwapWithMinFee: false,
},
migration: {
migrationOption: MigrationOption.MET_DAMM_V2,
migrationFeeOption: MigrationFeeOption.Customizable,
migrationFee: {
feePercentage: 10,
creatorFeePercentage: 50,
},
migratedPoolFee: {
collectFeeMode: MigratedCollectFeeMode.QuoteToken,
dynamicFee: DammV2DynamicFeeMode.Enabled,
poolFeeBps: 120,
baseFeeMode: DammV2BaseFeeMode.FeeTimeSchedulerLinear,
},
},
liquidityDistribution: {
partnerLiquidityPercentage: 0,
partnerPermanentLockedLiquidityPercentage: 100,
creatorLiquidityPercentage: 0,
creatorPermanentLockedLiquidityPercentage: 0,
},
lockedVesting: {
totalLockedVestingAmount: 0,
numberOfVestingPeriod: 0,
cliffUnlockAmount: 0,
totalVestingDuration: 0,
cliffDurationFromMigrationTime: 0,
},
activationType: ActivationType.Timestamp,
sqrtPrices,
liquidityWeights: [2, 1, 1],
});
```
## Create A Config
```typescript theme={"system"}
const partner = Keypair.generate();
const config = Keypair.generate();
const createConfigTx = await client.partner.createConfig({
config: config.publicKey,
feeClaimer: partner.publicKey,
leftoverReceiver: partner.publicKey,
payer: partner.publicKey,
quoteMint: NATIVE_MINT,
...curveConfig,
});
createConfigTx.feePayer = partner.publicKey;
```
The transaction must be signed by the payer and the new `config` signer.
## Create A Pool
```typescript theme={"system"}
const creator = Keypair.generate();
const baseMint = Keypair.generate();
const createPoolTx = await client.creator.createPool({
baseMint: baseMint.publicKey,
config: config.publicKey,
name: "TEST",
symbol: "TEST",
uri: "https://example.com/token.json",
payer: creator.publicKey,
poolCreator: creator.publicKey,
});
createPoolTx.feePayer = creator.publicKey;
const pool = deriveDbcPoolAddress(
NATIVE_MINT,
baseMint.publicKey,
config.publicKey
);
```
## Quote And Swap
```typescript theme={"system"}
const poolState = await client.state.getPool(pool);
const configState = await client.state.getPoolConfig(poolState.poolState.config);
const currentPoint =
configState.activationType === ActivationType.Slot
? new BN(await connection.getSlot())
: new BN(Math.floor(Date.now() / 1000));
const quote = client.pool.swapQuote2({
virtualPool: poolState,
config: configState,
swapBaseForQuote: false,
swapMode: SwapMode.ExactIn,
amountIn: new BN(1_000_000_000),
slippageBps: 100,
hasReferral: false,
eligibleForFirstSwapWithMinFee: false,
currentPoint,
});
const swapTx = await client.pool.swap2({
owner: new PublicKey("USER_WALLET"),
payer: new PublicKey("FEE_PAYER"),
pool,
swapBaseForQuote: false,
swapMode: SwapMode.ExactIn,
amountIn: new BN(1_000_000_000),
minimumAmountOut: quote.minimumAmountOut,
referralTokenAccount: null,
});
```
## Partial Fill Near Completion
Use partial fill when the final buy may cross the migration threshold before consuming the full input amount.
```typescript theme={"system"}
const partialQuote = client.pool.swapQuote2({
virtualPool: poolState,
config: configState,
swapBaseForQuote: false,
swapMode: SwapMode.PartialFill,
amountIn: new BN(5_000_000_000),
slippageBps: 100,
hasReferral: false,
eligibleForFirstSwapWithMinFee: false,
currentPoint,
});
const partialFillTx = await client.pool.swap2({
owner: new PublicKey("USER_WALLET"),
pool,
swapBaseForQuote: false,
swapMode: SwapMode.PartialFill,
amountIn: new BN(5_000_000_000),
minimumAmountOut: partialQuote.minimumAmountOut,
referralTokenAccount: null,프로젝트로 돌아가기