> ## Documentation Index
> Fetch the complete documentation index at: https://docs.meteora.ag/llms.txt
> Use this file to discover all available pages before exploring further.

# Dynamic Fee Sharing CPI Integration

> Learn how to call Dynamic Fee Sharing instructions through Rust CPI, pass required accounts, handle event-CPI accounts, and plan source-program funding.

Use CPI when your Solana program must call Dynamic Fee Sharing directly, for example to create a vault, fund a vault from program-controlled token accounts, or claim fees as part of a larger protocol instruction.

## Program ID

| Network      | Program ID                                    |
| ------------ | --------------------------------------------- |
| Mainnet Beta | `dfsdo2UqvwfN8DuUVrMRNfQe11VaiNoKcMqLHVvDPzh` |
| Devnet       | `dfsdo2UqvwfN8DuUVrMRNfQe11VaiNoKcMqLHVvDPzh` |

## Generated Bindings

For a Rust program in the same workspace, enable the Dynamic Fee Sharing program crate with the `cpi` feature:

```toml theme={"system"}
[dependencies]
dynamic-fee-sharing = { git = "https://github.com/MeteoraAg/dynamic-fee-sharing", package = "dynamic-fee-sharing", features = ["cpi"] }
```

For local development inside the program repository:

```toml theme={"system"}
[dependencies]
dynamic-fee-sharing = { path = "../dynamic-fee-sharing/programs/dynamic-fee-sharing", features = ["cpi"] }
```

The crate name in Rust code is `dynamic_fee_sharing`.

## CPI Pattern

Anchor generates CPI helpers for the program instructions. Account structs use the same names as the instruction contexts in the Dynamic Fee Sharing source.

```rust theme={"system"}
use anchor_lang::prelude::*;
use dynamic_fee_sharing::cpi;
use dynamic_fee_sharing::cpi::accounts::FundFeeCtx;

pub fn fund_fee_via_cpi<'info>(
    ctx: Context<'_, '_, '_, 'info, YourFundCtx<'info>>,
    max_amount: u64,
) -> Result<()> {
    let cpi_program = ctx.accounts.dynamic_fee_sharing_program.to_account_info();
    let cpi_accounts = FundFeeCtx {
        fee_vault: ctx.accounts.fee_vault.to_account_info(),
        token_vault: ctx.accounts.token_vault.to_account_info(),
        token_mint: ctx.accounts.token_mint.to_account_info(),
        fund_token_vault: ctx.accounts.fund_token_vault.to_account_info(),
        funder: ctx.accounts.funder.to_account_info(),
        token_program: ctx.accounts.token_program.to_account_info(),
    };

    cpi::fund_fee(CpiContext::new(cpi_program, cpi_accounts), max_amount)
}
```

<Note>
  Instructions marked with `#[event_cpi]` require the event-CPI accounts generated by Anchor. If you construct CPI calls manually, include the Dynamic Fee Sharing event authority and program accounts expected by the IDL.
</Note>

## Common CPI Calls

| CPI call                        | Account context            | Parameters                     | Notes                                                                               |
| ------------------------------- | -------------------------- | ------------------------------ | ----------------------------------------------------------------------------------- |
| `cpi::initialize_fee_vault`     | `InitializeFeeVaultCtx`    | `InitializeFeeVaultParameters` | Creates a keypair-based fee vault. The fee vault account signs.                     |
| `cpi::initialize_fee_vault_pda` | `InitializeFeeVaultPdaCtx` | `InitializeFeeVaultParameters` | Creates a PDA fee vault from `base` and `token_mint`. The base account signs.       |
| `cpi::fund_fee`                 | `FundFeeCtx`               | `max_amount`                   | Transfers from `fund_token_vault` and updates fee-per-share accounting.             |
| `cpi::fund_by_claiming_fee`     | `FundByClaimingFeeCtx`     | `payload`                      | Invokes a whitelisted DAMM v2 or DBC instruction using the PDA fee vault as signer. |
| `cpi::claim_fee`                | `ClaimFeeCtx`              | `index`                        | Transfers the user's claimable amount from the token vault.                         |

## Account Requirements

| Flow                   | Required signer      | Important accounts                                                                                             |
| ---------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------- |
| Non-PDA initialization | `fee_vault`, `payer` | Fee vault account, fee vault authority PDA, token vault PDA, token mint, owner, token program, system program. |
| PDA initialization     | `base`, `payer`      | Fee vault PDA, fee vault authority PDA, token vault PDA, token mint, owner, token program, system program.     |
| Direct funding         | `funder`             | Fee vault, token vault, token mint, funder's token account, token program.                                     |
| Source-program funding | `signer` shareholder | PDA fee vault, token vault, source program, downstream remaining accounts.                                     |
| User claim             | `user`               | Fee vault, fee vault authority PDA, token vault, token mint, user token destination, token program.            |

## Source-Program Funding

`fund_by_claiming_fee` is the most account-order-sensitive CPI path. The handler validates:

| Check              | Requirement                                                                                             |
| ------------------ | ------------------------------------------------------------------------------------------------------- |
| Fee vault type     | `fee_vault_type` must be PDA account (`1`).                                                             |
| Signer             | The `signer` must be one of the configured shareholders.                                                |
| Payload            | First 8 bytes must match a whitelisted downstream instruction discriminator.                            |
| Remaining accounts | The configured remaining-account index for that downstream action must equal the fee vault token vault. |
| Credited amount    | The program credits the token vault balance increase after the downstream CPI.                          |

Whitelisted actions are DAMM v2 `claim_position_fee`, DAMM v2 `claim_reward`, and DBC creator/partner trading fee, surplus, and migration fee withdrawals.

## Token Programs

| Token behavior     | Guidance                                                                                                                                                    |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SPL Token          | Pass the SPL Token program for `token_program`.                                                                                                             |
| Token 2022         | Pass Token 2022 when the fee vault mint is Token 2022. Only transfer-fee, metadata-pointer, and token-metadata extensions are supported by mint validation. |
| Transfer-fee mints | Direct funding credits the transfer-fee excluded amount. Claim transfers use checked transfers from the vault.                                              |
| Native SOL         | CPI callers must prepare wrapped SOL token accounts explicitly. The TypeScript SDK wraps and unwraps SOL for top-level transactions.                        |

## Common CPI Failures

| Error area                        | CPI-side fix                                                                                                                |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Missing event accounts            | Include generated `event_authority` and `program` accounts for `#[event_cpi]` instructions.                                 |
| Invalid user index                | Read `FeeVault.users` and pass the index for the signer address.                                                            |
| Source funding with non-PDA vault | Create the vault with `initialize_fee_vault_pda`.                                                                           |
| Invalid source action             | Match the source program, discriminator, and remaining-account order from the whitelist.                                    |
| Token vault mismatch              | Derive `token_vault` from `["token_vault", fee_vault]` and pass that same account in the downstream remaining-account slot. |
| Token 2022 mint rejection         | Use only supported Token 2022 extensions for the fee vault mint.                                                            |

## Best Practices

| Practice                         | Why it matters                                                                                                                          |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| Prefer generated bindings        | Use the Anchor crate with the `cpi` feature or generated IDL bindings instead of hand-typing account order.                             |
| Read fee vault state first       | Validate `token_mint`, `token_vault`, `fee_vault_type`, `base`, `total_share`, and user indexes before building CPI.                    |
| Keep PDA derivation explicit     | Use `fee_vault` seeds from `base` and `token_mint`, and token vault seeds from the fee vault.                                           |
| Treat source funding as advanced | Downstream DAMM v2 and DBC account lists must match the whitelisted instruction exactly.                                                |
| Simulate before sending          | Source-program funding performs a downstream CPI and then credits the balance delta, so simulation catches most account-order mistakes. |
| Test each token program variant  | SPL Token and Token 2022 paths differ in mint validation and transfer-fee behavior.                                                     |
