Lifinity AMM v2 decoder

Decode Lifinity AMM v2 instructions and accounts in Rust with carbon-lifinity-amm-v2-decoder 2.0.0. Program ID 2wT8Yq49kHgDzXuPxZSaeLaH1qbmGXtEyPy64bL7aD3c.

On this page

carbon-lifinity-amm-v2-decoder decodes the instructions and accounts of the Lifinity AMM v2 program (2wT8Yq49kHgDzXuPxZSaeLaH1qbmGXtEyPy64bL7aD3c): 3 instructions, 1 account type. It is generated with Codama from the program's IDL; see decoders for how decoders plug into a pipeline.

Cratecarbon-lifinity-amm-v2-decoder 2.0.0
Installcargo add carbon-lifinity-amm-v2-decoder@2.0.0
Program ID2wT8Yq49kHgDzXuPxZSaeLaH1qbmGXtEyPy64bL7aD3c (carbon_lifinity_amm_v2_decoder::PROGRAM_ID)
CategoryDEX & AMM
Decodercarbon_lifinity_amm_v2_decoder::LifinityAmmV2Decoder
Instruction enuminstructions::LifinityAmmV2Instruction
Account enumaccounts::LifinityAmmV2Account
Featuresserde, postgres, graphql (none enabled by default)
API docsdocs.rs/carbon-lifinity-amm-v2-decoder/2.0.0
Sourcedecoders/lifinity-amm-v2-decoder

Other DEX and AMM decoders: BonkSwap, FluxBeam, Gavel, Heaven, Jupiter Limit Order, Jupiter Limit Order v2, Kamino Limit Order, Meteora DAMM v2, Meteora DLMM, Meteora Pools, OpenBook v2, Orca Whirlpools, PancakeSwap, Phoenix v1, PumpSwap, Raydium AMM v4, Raydium CLMM, Raydium CPMM, Raydium Stable Swap, Stabble Stable Swap, Stabble Weighted Swap. To decode several in one pipeline, see dEX and AMM decoders.

The serde feature derives Serialize/Deserialize on every type, postgres adds tables and processors for Postgres, and graphql adds a schema for the GraphQL server.

Usage#

This program crawls recent Lifinity AMM v2 transactions from the public RPC and prints every decoded Swap instruction. Add the dependencies:

Terminal
cargo add carbon-core@2.0.0 carbon-lifinity-amm-v2-decoder@2.0.0 carbon-rpc-transaction-crawler-datasource@2.0.0 carbon-log-metrics@2.0.0 env_logger tokio --features tokio/full
src/main.rs
use {
    carbon_core::{
        error::CarbonResult, instruction::InstructionProcessorInputType, pipeline::Pipeline,
        processor::Processor,
    },
    carbon_log_metrics::LogMetrics,
    carbon_lifinity_amm_v2_decoder::{
        instructions::LifinityAmmV2Instruction, LifinityAmmV2Decoder, PROGRAM_ID,
    },
    carbon_rpc_transaction_crawler_datasource::{ConnectionConfig, Filters, RpcTransactionCrawler},
    std::sync::Arc,
};

#[tokio::main]
async fn main() -> CarbonResult<()> {
    env_logger::init();

    // Fetches the program's recent transactions over JSON-RPC, newest first.
    let datasource = RpcTransactionCrawler::new(
        "https://api.mainnet-beta.solana.com".to_string(),
        PROGRAM_ID,
        ConnectionConfig::default(),
        Filters::new(None, None, None),
        None,
    );

    Pipeline::builder()
        .datasource(datasource)
        .metrics(Arc::new(LogMetrics::new()))
        .instruction(LifinityAmmV2Decoder, InstructionLogger)
        .build()?
        .run()
        .await
}

struct InstructionLogger;

impl Processor<InstructionProcessorInputType<'_, LifinityAmmV2Instruction>> for InstructionLogger {
    async fn process(
        &mut self,
        input: &InstructionProcessorInputType<'_, LifinityAmmV2Instruction>,
    ) -> CarbonResult<()> {
        let signature = input.metadata.transaction_metadata.signature;
        if let LifinityAmmV2Instruction::Swap { data, accounts, .. } = input.decoded_instruction {
            println!("swap {signature}: {data:?} authority={}", accounts.authority);
        }
        Ok(())
    }
}
Terminal
RUST_LOG=info cargo run

Each Swap instruction prints one line with the transaction signature and the decoded Swap data. The public endpoint rate-limits requests, so the first lines can take a while; use your own RPC URL for anything beyond a test. See stream with RPC for the crawler options.

Decode accounts#

The transaction crawler emits transactions only. To decode accounts, use a datasource that emits account updates. This program subscribes to the program's accounts with programSubscribe on the public WebSocket endpoint and prints every decoded Amm account as it changes. Add the datasource and the Solana RPC types it takes:

Terminal
cargo add carbon-rpc-program-subscribe-datasource@2.0.0 solana-client@4.2.2
src/main.rs
use {
    carbon_core::{
        account::AccountProcessorInputType, error::CarbonResult, pipeline::Pipeline,
        processor::Processor,
    },
    carbon_log_metrics::LogMetrics,
    carbon_lifinity_amm_v2_decoder::{
        accounts::LifinityAmmV2Account, LifinityAmmV2Decoder, PROGRAM_ID,
    },
    carbon_rpc_program_subscribe_datasource::{Filters, RpcProgramSubscribe},
    solana_client::rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig, UiAccountEncoding},
    std::sync::Arc,
};

#[tokio::main]
async fn main() -> CarbonResult<()> {
    env_logger::init();

    // Streams every change to an account owned by the program (programSubscribe).
    let config = RpcProgramAccountsConfig {
        account_config: RpcAccountInfoConfig {
            encoding: Some(UiAccountEncoding::Base64),
            ..Default::default()
        },
        ..Default::default()
    };
    let datasource = RpcProgramSubscribe::new(
        "wss://api.mainnet-beta.solana.com".to_string(),
        Filters::new(PROGRAM_ID, Some(config)),
    );

    Pipeline::builder()
        .datasource(datasource)
        .metrics(Arc::new(LogMetrics::new()))
        .account(LifinityAmmV2Decoder, AccountLogger)
        .build()?
        .run()
        .await
}

struct AccountLogger;

impl Processor<AccountProcessorInputType<'_, LifinityAmmV2Account>> for AccountLogger {
    async fn process(
        &mut self,
        input: &AccountProcessorInputType<'_, LifinityAmmV2Account>,
    ) -> CarbonResult<()> {
        let LifinityAmmV2Account::Amm(amm) = &input.decoded_account.data;
        println!("amm {}: {amm:?}", input.metadata.pubkey);
        Ok(())
    }
}
Terminal
RUST_LOG=info cargo run

Each update to a Amm account prints its address and decoded fields; the program runs until you stop it. Cargo resolves solana-client to 4.2.2, the exact version the datasource pins, so both use the same RpcProgramAccountsConfig type. To load every existing account once instead of streaming changes, see load account state.

Instructions#

Variants of LifinityAmmV2Instruction. Each is LifinityAmmV2Instruction::<Variant> { program_id, data, accounts }, where data and accounts are the types listed under the variant, exported from carbon_lifinity_amm_v2_decoder::instructions. Discriminators are the leading bytes of the instruction data, in hex.

How an instruction decodes. The decoder returns a variant only when all of these hold; otherwise the instruction is skipped and no processor is called:

  1. The instruction's program ID is 2wT8Yq49kHgDzXuPxZSaeLaH1qbmGXtEyPy64bL7aD3c.
  2. The data starts with the variant's discriminator, and the rest deserializes into its data type.
  3. The instruction has at least as many accounts as the variant requires (the "Required accounts" count under each variant).

Accounts. They are matched by position, in the order listed. An account marked optional is None only when the instruction ends before it; Anchor programs pass the program ID as a placeholder for an omitted optional account, so check for Some(PROGRAM_ID) too. Accounts after the listed ones are in accounts.remaining as AccountMetas. The decoder doesn't record whether an account signed or was writable: read that from input.raw_instruction.accounts[i].is_signer and .is_writable, which follow the same order. It doesn't check signer, writable, owner or PDA constraints either; the program enforced those when the transaction executed, so a decoded instruction from a successful transaction already satisfied them.

DepositAllTokenTypes#

Discriminator 205f453c4b4fcdee · data DepositAllTokenTypes · accounts DepositAllTokenTypesInstructionAccounts.

FieldType
pool_token_amountu64
maximum_token_a_amountu64
maximum_token_b_amountu64

Required accounts: 10; extras go to remaining.

Fields of DepositAllTokenTypesInstructionAccounts, in account order:

#FieldType
0ammPubkey
1authorityPubkey
2user_transfer_authority_infoPubkey
3source_a_infoPubkey
4source_b_infoPubkey
5token_aPubkey
6token_bPubkey
7pool_mintPubkey
8destinationPubkey
9token_programPubkey
10…remainingVec<AccountMeta>

Swap#

Discriminator f8c69e91e17587c8 · data Swap · accounts SwapInstructionAccounts.

FieldType
amount_inu64
minimum_amount_outu64

Required accounts: 13; extras go to remaining.

Fields of SwapInstructionAccounts, in account order:

#FieldType
0authorityPubkey
1ammPubkey
2user_transfer_authorityPubkey
3source_infoPubkey
4destination_infoPubkey
5swap_sourcePubkey
6swap_destinationPubkey
7pool_mintPubkey
8fee_accountPubkey
9token_programPubkey
10oracle_main_accountPubkey
11oracle_sub_accountPubkey
12oracle_pc_accountPubkey
13…remainingVec<AccountMeta>

WithdrawAllTokenTypes#

Discriminator bdfe9caed209a4d8 · data WithdrawAllTokenTypes · accounts WithdrawAllTokenTypesInstructionAccounts.

FieldType
pool_token_amountu64
minimum_token_a_amountu64
minimum_token_b_amountu64

Required accounts: 10; extras go to remaining.

Fields of WithdrawAllTokenTypesInstructionAccounts, in account order:

#FieldType
0ammPubkey
1authorityPubkey
2user_transfer_authority_infoPubkey
3source_infoPubkey
4token_aPubkey
5token_bPubkey
6pool_mintPubkey
7dest_token_a_infoPubkey
8dest_token_b_infoPubkey
9token_programPubkey
10…remainingVec<AccountMeta>

Accounts#

Variants of LifinityAmmV2Account. Each wraps a boxed struct from carbon_lifinity_amm_v2_decoder::accounts::<module>. decode_account only considers accounts owned by PROGRAM_ID and returns the first variant that matches.

Amm#

Discriminator 8ff5c8114ad6c487 · accounts::amm::Amm.

FieldTypeDescription
initializer_keyPubkey
initializer_deposit_token_accountPubkey
initializer_receive_token_accountPubkey
initializer_amountu64
taker_amountu64
is_initializedboolIs the swap initialized, with data written to it
bump_seedu8Bump seed used to generate the program address / authority
freeze_tradeu8Freeze swap
freeze_depositu8Freeze deposit
freeze_withdrawu8Freeze withdraw
base_decimalsu8Base decimals account
token_program_idPubkeyToken program ID associated with the swap
token_a_accountPubkeyAddress of token A liquidity account
token_b_accountPubkeyAddress of token B liquidity account
pool_mintPubkeyAddress of pool token mint
token_a_mintPubkeyAddress of token A mint
token_b_mintPubkeyAddress of token B mint
fee_accountPubkeyAddress of pool fee account
oracle_main_accountPubkeyOracle Main account
oracle_sub_accountPubkeyOracle Sub account
oracle_pc_accountPubkeyoracle Pc account
feesAmmFeesFees associated with swap
curveAmmCurveCurve associated with swap
configAmmConfigCurve associated with swap
amm_p_temp1PubkeyTemp area
amm_p_temp2PubkeyTemp area
amm_p_temp3PubkeyTemp area
amm_p_temp4PubkeyTemp area
amm_p_temp5PubkeyTemp area

Types#

Types used by the instructions, accounts and events above, exported from carbon_lifinity_amm_v2_decoder::types.

AmmConfig#

Struct types::AmmConfig.

FieldType
last_priceu64
last_balanced_priceu64
config_denominatoru64
volume_xu64
volume_yu64
volume_x_in_yu64
deposit_capu64
regression_targetu64
oracle_typeu64
oracle_statusu64
oracle_main_slot_limitu64
oracle_sub_confidence_limitu64
oracle_sub_slot_limitu64
oracle_pc_confidence_limitu64
oracle_pc_slot_limitu64
std_spreadu64
std_spread_bufferu64
spread_coefficientu64
price_buffer_coini64
price_buffer_pci64
rebalance_ratiou64
fee_tradeu64
fee_platformu64
oracle_main_slot_bufferu64
config_temp4u64
config_temp5u64
config_temp6u64
config_temp7u64
config_temp8u64

AmmCurve#

Struct types::AmmCurve.

FieldType
curve_typeu8
curve_parametersu64

AmmFees#

From the program's IDL:

Encapsulates all fee information and calculations for swap operations

Struct types::AmmFees.

FieldType
trade_fee_numeratoru64
trade_fee_denominatoru64
owner_trade_fee_numeratoru64
owner_trade_fee_denominatoru64
owner_withdraw_fee_numeratoru64
owner_withdraw_fee_denominatoru64
host_fee_numeratoru64
host_fee_denominatoru64

CurveType#

From the program's IDL:

Curve types supported by the token-swap program.

Enum types::CurveType.

Variant
Standard
ConstantProduct

Generated from the crate’s source at Carbon v2.0.0, so it always matches the published code. Spotted a problem? Report it; edits to this page itself are overwritten on the next release.

Your endpoints

Code samples use these instead of the placeholders, so you can copy and run them as they are. They’re stored only in this browser and never sent anywhere.