This commit is contained in:
2026-04-28 15:35:15 +02:00
parent e6b7b2d419
commit 467e488b36
9 changed files with 1414 additions and 83 deletions

338
kb_lib/src/dex/pump_fun.rs Normal file
View File

@@ -0,0 +1,338 @@
// file: kb_lib/src/dex/pump_fun.rs
//! Pump.fun bonding-curve transaction decoder.
/// Pump.fun program id.
pub const KB_PUMP_FUN_PROGRAM_ID: &str = "6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";
/// Decoded Pump.fun `create_v2` token event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KbPumpFunCreateV2TokenDecoded {
/// Parent transaction id.
pub transaction_id: i64,
/// Parent instruction id.
pub instruction_id: i64,
/// Transaction signature.
pub signature: std::string::String,
/// Program id.
pub program_id: std::string::String,
/// Optional created mint.
pub mint: std::option::Option<std::string::String>,
/// Optional bonding curve account.
pub bonding_curve: std::option::Option<std::string::String>,
/// Optional associated bonding curve account.
pub associated_bonding_curve: std::option::Option<std::string::String>,
/// Optional creator / user account.
pub creator: std::option::Option<std::string::String>,
/// Decoded payload.
pub payload_json: serde_json::Value,
}
/// Decoded Pump.fun event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum KbPumpFunDecodedEvent {
/// `create_v2` token creation.
CreateV2Token(KbPumpFunCreateV2TokenDecoded),
}
/// Pump.fun decoder.
#[derive(Debug, Clone, Default)]
pub struct KbPumpFunDecoder;
impl KbPumpFunDecoder {
/// Creates a new decoder.
pub fn new() -> Self {
Self
}
/// Decodes one projected transaction into zero or more Pump.fun events.
pub fn decode_transaction(
&self,
transaction: &crate::KbChainTransactionDto,
instructions: &[crate::KbChainInstructionDto],
) -> Result<std::vec::Vec<crate::KbPumpFunDecodedEvent>, crate::KbError> {
let transaction_id_option = transaction.id;
let transaction_id = match transaction_id_option {
Some(transaction_id) => transaction_id,
None => {
return Err(crate::KbError::InvalidState(format!(
"chain transaction '{}' has no internal id",
transaction.signature
)));
}
};
let transaction_json_result =
serde_json::from_str::<serde_json::Value>(transaction.transaction_json.as_str());
let transaction_json = match transaction_json_result {
Ok(transaction_json) => transaction_json,
Err(error) => {
return Err(crate::KbError::Json(format!(
"cannot parse transaction_json for signature '{}': {}",
transaction.signature, error
)));
}
};
let log_messages = kb_extract_log_messages(&transaction_json);
let has_create_v2_log = kb_log_messages_contain_keyword(&log_messages, "create_v2")
|| kb_log_messages_contain_keyword(&log_messages, "createv2");
let mut decoded_events = std::vec::Vec::new();
for instruction in instructions {
if instruction.parent_instruction_id.is_some() {
continue;
}
let program_id_option = &instruction.program_id;
let program_id = match program_id_option {
Some(program_id) => program_id,
None => continue,
};
if program_id.as_str() != crate::KB_PUMP_FUN_PROGRAM_ID {
continue;
}
if !has_create_v2_log {
continue;
}
let instruction_id_option = instruction.id;
let instruction_id = match instruction_id_option {
Some(instruction_id) => instruction_id,
None => continue,
};
let accounts_result = kb_parse_accounts_json(instruction.accounts_json.as_str());
let accounts = match accounts_result {
Ok(accounts) => accounts,
Err(error) => return Err(error),
};
if accounts.len() < 6 {
continue;
}
let mint = kb_extract_account(&accounts, 0);
let bonding_curve = kb_extract_account(&accounts, 2);
let associated_bonding_curve = kb_extract_account(&accounts, 3);
let creator = kb_extract_account(&accounts, 5);
let payload_json = serde_json::json!({
"decoder": "pump_fun",
"eventKind": "create_v2_token",
"signature": transaction.signature,
"instructionId": instruction_id,
"instructionIndex": instruction.instruction_index,
"accounts": accounts,
"logMessages": log_messages,
"mint": mint,
"bondingCurve": bonding_curve,
"associatedBondingCurve": associated_bonding_curve,
"creator": creator
});
decoded_events.push(crate::KbPumpFunDecodedEvent::CreateV2Token(
crate::KbPumpFunCreateV2TokenDecoded {
transaction_id,
instruction_id,
signature: transaction.signature.clone(),
program_id: program_id.clone(),
mint,
bonding_curve,
associated_bonding_curve,
creator,
payload_json,
},
));
}
Ok(decoded_events)
}
}
fn kb_extract_log_messages(
transaction_json: &serde_json::Value,
) -> std::vec::Vec<std::string::String> {
let mut messages = std::vec::Vec::new();
let meta_option = transaction_json.get("meta");
let meta = match meta_option {
Some(meta) => meta,
None => return messages,
};
let logs_option = meta.get("logMessages");
let logs = match logs_option {
Some(logs) => logs,
None => return messages,
};
let logs_array_option = logs.as_array();
let logs_array = match logs_array_option {
Some(logs_array) => logs_array,
None => return messages,
};
for value in logs_array {
let text_option = value.as_str();
if let Some(text) = text_option {
messages.push(text.to_string());
}
}
messages
}
fn kb_log_messages_contain_keyword(
log_messages: &[std::string::String],
keyword: &str,
) -> bool {
let keyword_normalized = kb_normalize_log_text(keyword);
for log_message in log_messages {
let log_normalized = kb_normalize_log_text(log_message.as_str());
if log_normalized.contains(keyword_normalized.as_str()) {
return true;
}
}
false
}
fn kb_parse_accounts_json(
accounts_json: &str,
) -> Result<std::vec::Vec<std::string::String>, crate::KbError> {
let values_result = serde_json::from_str::<std::vec::Vec<serde_json::Value>>(accounts_json);
let values = match values_result {
Ok(values) => values,
Err(error) => {
return Err(crate::KbError::Json(format!(
"cannot parse instruction accounts_json '{}': {}",
accounts_json, error
)));
}
};
let mut accounts = std::vec::Vec::new();
for value in values {
let text_option = value.as_str();
if let Some(text) = text_option {
accounts.push(text.to_string());
}
}
Ok(accounts)
}
fn kb_extract_account(
accounts: &[std::string::String],
index: usize,
) -> std::option::Option<std::string::String> {
if index >= accounts.len() {
return None;
}
Some(accounts[index].clone())
}
fn kb_normalize_log_text(value: &str) -> std::string::String {
let mut normalized = std::string::String::new();
for character in value.chars() {
if character.is_ascii_alphanumeric() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
#[cfg(test)]
mod tests {
fn make_transaction() -> crate::KbChainTransactionDto {
let mut dto = crate::KbChainTransactionDto::new(
"sig-pump-fun-test-1".to_string(),
Some(777001),
Some(1779200001),
Some("helius_primary_http".to_string()),
Some("0".to_string()),
None,
None,
serde_json::json!({
"slot": 777001,
"meta": {
"logMessages": [
"Program log: Instruction: CreateV2"
]
},
"transaction": {
"message": {
"instructions": []
}
}
})
.to_string(),
);
dto.id = Some(91);
dto
}
fn make_instruction() -> crate::KbChainInstructionDto {
let mut dto = crate::KbChainInstructionDto::new(
91,
None,
0,
None,
Some(crate::KB_PUMP_FUN_PROGRAM_ID.to_string()),
Some("pump".to_string()),
Some(1),
serde_json::json!([
"MintCreate111",
"MintAuthority111",
"BondingCurve111",
"AssociatedBondingCurve111",
"Global111",
"Creator111",
"System111",
"Token2022Program111",
"AtaProgram111"
])
.to_string(),
None,
None,
None,
);
dto.id = Some(17);
dto
}
#[test]
fn pump_fun_create_v2_is_detected() {
let decoder = crate::KbPumpFunDecoder::new();
let transaction = make_transaction();
let instructions = vec![make_instruction()];
let decoded_result = decoder.decode_transaction(&transaction, &instructions);
let decoded = match decoded_result {
Ok(decoded) => decoded,
Err(error) => panic!("decode must succeed: {}", error),
};
assert_eq!(decoded.len(), 1);
match &decoded[0] {
crate::KbPumpFunDecodedEvent::CreateV2Token(event) => {
assert_eq!(event.transaction_id, 91);
assert_eq!(event.instruction_id, 17);
assert_eq!(event.mint, Some("MintCreate111".to_string()));
assert_eq!(event.bonding_curve, Some("BondingCurve111".to_string()));
assert_eq!(
event.associated_bonding_curve,
Some("AssociatedBondingCurve111".to_string())
);
assert_eq!(event.creator, Some("Creator111".to_string()));
}
}
}
#[test]
fn pump_fun_create_v2_returns_none_without_expected_log() {
let decoder = crate::KbPumpFunDecoder::new();
let mut transaction = make_transaction();
transaction.transaction_json = serde_json::json!({
"slot": 777001,
"meta": {
"logMessages": [
"Program log: Instruction: Buy"
]
},
"transaction": {
"message": {
"instructions": []
}
}
})
.to_string();
let instructions = vec![make_instruction()];
let decoded_result = decoder.decode_transaction(&transaction, &instructions);
let decoded = match decoded_result {
Ok(decoded) => decoded,
Err(error) => panic!("decode must succeed: {}", error),
};
assert_eq!(decoded.len(), 0);
}
}

315
kb_lib/src/dex/pump_swap.rs Normal file
View File

@@ -0,0 +1,315 @@
// file: kb_lib/src/dex/pump_swap.rs
//! PumpSwap AMM transaction decoder.
/// PumpSwap / PumpAMM program id.
pub const KB_PUMP_SWAP_PROGRAM_ID: &str = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA";
/// Decoded PumpSwap trade event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KbPumpSwapTradeDecoded {
/// Parent transaction id.
pub transaction_id: i64,
/// Parent instruction id.
pub instruction_id: i64,
/// Transaction signature.
pub signature: std::string::String,
/// Program id.
pub program_id: std::string::String,
/// Trade side.
pub trade_side: crate::KbSwapTradeSide,
/// Optional heuristic pool account.
pub pool_account: std::option::Option<std::string::String>,
/// Decoded payload.
pub payload_json: serde_json::Value,
}
/// Decoded PumpSwap event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum KbPumpSwapDecodedEvent {
/// Buy trade.
BuyTrade(KbPumpSwapTradeDecoded),
/// Sell trade.
SellTrade(KbPumpSwapTradeDecoded),
}
/// PumpSwap decoder.
#[derive(Debug, Clone, Default)]
pub struct KbPumpSwapDecoder;
impl KbPumpSwapDecoder {
/// Creates a new decoder.
pub fn new() -> Self {
Self
}
/// Decodes one projected transaction into zero or more PumpSwap events.
pub fn decode_transaction(
&self,
transaction: &crate::KbChainTransactionDto,
instructions: &[crate::KbChainInstructionDto],
) -> Result<std::vec::Vec<crate::KbPumpSwapDecodedEvent>, crate::KbError> {
let transaction_id_option = transaction.id;
let transaction_id = match transaction_id_option {
Some(transaction_id) => transaction_id,
None => {
return Err(crate::KbError::InvalidState(format!(
"chain transaction '{}' has no internal id",
transaction.signature
)));
}
};
let transaction_json_result =
serde_json::from_str::<serde_json::Value>(transaction.transaction_json.as_str());
let transaction_json = match transaction_json_result {
Ok(transaction_json) => transaction_json,
Err(error) => {
return Err(crate::KbError::Json(format!(
"cannot parse transaction_json for signature '{}': {}",
transaction.signature, error
)));
}
};
let log_messages = kb_extract_log_messages(&transaction_json);
let mut decoded_events = std::vec::Vec::new();
for instruction in instructions {
if instruction.parent_instruction_id.is_some() {
continue;
}
let program_id_option = &instruction.program_id;
let program_id = match program_id_option {
Some(program_id) => program_id,
None => continue,
};
if program_id.as_str() != crate::KB_PUMP_SWAP_PROGRAM_ID {
continue;
}
let instruction_id_option = instruction.id;
let instruction_id = match instruction_id_option {
Some(instruction_id) => instruction_id,
None => continue,
};
let accounts_result = kb_parse_accounts_json(instruction.accounts_json.as_str());
let accounts = match accounts_result {
Ok(accounts) => accounts,
Err(error) => return Err(error),
};
let pool_account = kb_extract_account(&accounts, 0);
let is_buy = kb_log_messages_contain_keyword(&log_messages, "buy");
let is_sell = kb_log_messages_contain_keyword(&log_messages, "sell");
if !is_buy && !is_sell {
continue;
}
let payload_json = serde_json::json!({
"decoder": "pump_swap",
"signature": transaction.signature,
"instructionId": instruction_id,
"instructionIndex": instruction.instruction_index,
"accounts": accounts,
"logMessages": log_messages,
"poolAccount": pool_account
});
if is_buy {
decoded_events.push(crate::KbPumpSwapDecodedEvent::BuyTrade(
crate::KbPumpSwapTradeDecoded {
transaction_id,
instruction_id,
signature: transaction.signature.clone(),
program_id: program_id.clone(),
trade_side: crate::KbSwapTradeSide::BuyBase,
pool_account: pool_account.clone(),
payload_json: payload_json.clone(),
},
));
}
if is_sell {
decoded_events.push(crate::KbPumpSwapDecodedEvent::SellTrade(
crate::KbPumpSwapTradeDecoded {
transaction_id,
instruction_id,
signature: transaction.signature.clone(),
program_id: program_id.clone(),
trade_side: crate::KbSwapTradeSide::SellBase,
pool_account,
payload_json,
},
));
}
}
Ok(decoded_events)
}
}
fn kb_extract_log_messages(
transaction_json: &serde_json::Value,
) -> std::vec::Vec<std::string::String> {
let mut messages = std::vec::Vec::new();
let meta_option = transaction_json.get("meta");
let meta = match meta_option {
Some(meta) => meta,
None => return messages,
};
let logs_option = meta.get("logMessages");
let logs = match logs_option {
Some(logs) => logs,
None => return messages,
};
let logs_array_option = logs.as_array();
let logs_array = match logs_array_option {
Some(logs_array) => logs_array,
None => return messages,
};
for value in logs_array {
let text_option = value.as_str();
if let Some(text) = text_option {
messages.push(text.to_string());
}
}
messages
}
fn kb_log_messages_contain_keyword(log_messages: &[std::string::String], keyword: &str) -> bool {
let keyword_lower = keyword.to_ascii_lowercase();
for log_message in log_messages {
let log_lower = log_message.to_ascii_lowercase();
if log_lower.contains(keyword_lower.as_str()) {
return true;
}
}
false
}
fn kb_parse_accounts_json(
accounts_json: &str,
) -> Result<std::vec::Vec<std::string::String>, crate::KbError> {
let values_result = serde_json::from_str::<std::vec::Vec<serde_json::Value>>(accounts_json);
let values = match values_result {
Ok(values) => values,
Err(error) => {
return Err(crate::KbError::Json(format!(
"cannot parse instruction accounts_json '{}': {}",
accounts_json, error
)));
}
};
let mut accounts = std::vec::Vec::new();
for value in values {
let text_option = value.as_str();
if let Some(text) = text_option {
accounts.push(text.to_string());
}
}
Ok(accounts)
}
fn kb_extract_account(
accounts: &[std::string::String],
index: usize,
) -> std::option::Option<std::string::String> {
if index >= accounts.len() {
return None;
}
Some(accounts[index].clone())
}
#[cfg(test)]
mod tests {
fn make_transaction_with_buy_log() -> crate::KbChainTransactionDto {
let mut dto = crate::KbChainTransactionDto::new(
"sig-pump-swap-test-1".to_string(),
Some(777002),
Some(1779200002),
Some("helius_primary_http".to_string()),
Some("0".to_string()),
None,
None,
serde_json::json!({
"slot": 777002,
"meta": {
"logMessages": [
"Program log: Instruction: Buy"
]
},
"transaction": {
"message": {
"instructions": []
}
}
})
.to_string(),
);
dto.id = Some(92);
dto
}
fn make_instruction() -> crate::KbChainInstructionDto {
let mut dto = crate::KbChainInstructionDto::new(
92,
None,
0,
None,
Some(crate::KB_PUMP_SWAP_PROGRAM_ID.to_string()),
Some("pump-amm".to_string()),
Some(1),
serde_json::json!(["PumpPool111", "Other1", "Other2"]).to_string(),
None,
None,
None,
);
dto.id = Some(18);
dto
}
#[test]
fn pump_swap_buy_is_detected() {
let decoder = crate::KbPumpSwapDecoder::new();
let transaction = make_transaction_with_buy_log();
let instructions = vec![make_instruction()];
let decoded_result = decoder.decode_transaction(&transaction, &instructions);
let decoded = match decoded_result {
Ok(decoded) => decoded,
Err(error) => panic!("decode must succeed: {}", error),
};
assert_eq!(decoded.len(), 1);
match &decoded[0] {
crate::KbPumpSwapDecodedEvent::BuyTrade(event) => {
assert_eq!(event.transaction_id, 92);
assert_eq!(event.instruction_id, 18);
assert_eq!(event.pool_account, Some("PumpPool111".to_string()));
assert_eq!(event.trade_side, crate::KbSwapTradeSide::BuyBase);
}
crate::KbPumpSwapDecodedEvent::SellTrade(_) => {
panic!("unexpected sell event")
}
}
}
#[test]
fn pump_swap_returns_none_without_buy_or_sell_log() {
let decoder = crate::KbPumpSwapDecoder::new();
let mut transaction = make_transaction_with_buy_log();
transaction.transaction_json = serde_json::json!({
"slot": 777002,
"meta": {
"logMessages": [
"Program log: Instruction: Deposit"
]
},
"transaction": {
"message": {
"instructions": []
}
}
})
.to_string();
let instructions = vec![make_instruction()];
let decoded_result = decoder.decode_transaction(&transaction, &instructions);
let decoded = match decoded_result {
Ok(decoded) => decoded,
Err(error) => panic!("decode must succeed: {}", error),
};
assert_eq!(decoded.len(), 0);
}
}