0.7.27 +Refactor

This commit is contained in:
2026-05-10 00:33:01 +02:00
parent cb2e8e7096
commit 1f0137b9de
261 changed files with 12308 additions and 8928 deletions

View File

@@ -2,12 +2,9 @@
//! DexLab Swap/Pool transaction decoder.
/// DexLab Swap/Pool program id.
pub const KB_DEXLAB_PROGRAM_ID: &str = "DSwpgjMvXhtGn6BsbqmacdBZyfLj6jSWf3HJpdJtmg6N";
/// Decoded DexLab create-pool event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KbDexlabCreatePoolDecoded {
pub struct DexlabCreatePoolDecoded {
/// Parent transaction id.
pub transaction_id: i64,
/// Parent instruction id.
@@ -32,7 +29,7 @@ pub struct KbDexlabCreatePoolDecoded {
/// Decoded DexLab swap event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KbDexlabSwapDecoded {
pub struct DexlabSwapDecoded {
/// Parent transaction id.
pub transaction_id: i64,
/// Parent instruction id.
@@ -42,7 +39,7 @@ pub struct KbDexlabSwapDecoded {
/// Program id.
pub program_id: std::string::String,
/// Trade side relative to normalized base.
pub trade_side: crate::KbSwapTradeSide,
pub trade_side: crate::SwapTradeSide,
/// Optional pool account.
pub pool_account: std::option::Option<std::string::String>,
/// Optional token A mint.
@@ -55,25 +52,25 @@ pub struct KbDexlabSwapDecoded {
/// Decoded DexLab event.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum KbDexlabDecodedEvent {
pub enum DexlabDecodedEvent {
/// Pool creation.
CreatePool(KbDexlabCreatePoolDecoded),
CreatePool(DexlabCreatePoolDecoded),
/// Swap.
Swap(KbDexlabSwapDecoded),
Swap(DexlabSwapDecoded),
}
/// DexLab decoder.
#[derive(Debug, Clone, Default)]
pub struct KbDexlabDecoder;
pub struct DexlabDecoder;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum KbDexlabInstructionKind {
enum DexlabInstructionKind {
CreatePool,
Swap,
Unknown,
}
impl KbDexlabDecoder {
impl DexlabDecoder {
/// Creates a new decoder.
pub fn new() -> Self {
return Self;
@@ -82,14 +79,14 @@ impl KbDexlabDecoder {
/// Decodes one projected transaction into zero or more DexLab events.
pub fn decode_transaction(
&self,
transaction: &crate::KbChainTransactionDto,
instructions: &[crate::KbChainInstructionDto],
) -> Result<std::vec::Vec<crate::KbDexlabDecodedEvent>, crate::KbError> {
transaction: &crate::ChainTransactionDto,
instructions: &[crate::ChainInstructionDto],
) -> Result<std::vec::Vec<crate::DexlabDecodedEvent>, crate::Error> {
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!(
return Err(crate::Error::InvalidState(format!(
"chain transaction '{}' has no internal id",
transaction.signature
)));
@@ -100,13 +97,13 @@ impl KbDexlabDecoder {
let transaction_json = match transaction_json_result {
Ok(transaction_json) => transaction_json,
Err(error) => {
return Err(crate::KbError::Json(format!(
return Err(crate::Error::Json(format!(
"cannot parse transaction_json for signature '{}': {}",
transaction.signature, error
)));
},
};
let log_messages = kb_extract_log_messages(&transaction_json);
let log_messages = extract_log_messages(&transaction_json);
let mut decoded_events = std::vec::Vec::new();
for instruction in instructions {
if instruction.parent_instruction_id.is_some() {
@@ -117,7 +114,7 @@ impl KbDexlabDecoder {
Some(program_id) => program_id,
None => continue,
};
if program_id.as_str() != crate::KB_DEXLAB_PROGRAM_ID {
if program_id.as_str() != crate::DEXLAB_PROGRAM_ID {
continue;
}
let instruction_id_option = instruction.id;
@@ -125,44 +122,42 @@ impl KbDexlabDecoder {
Some(instruction_id) => instruction_id,
None => continue,
};
let accounts_result = kb_parse_accounts_json(instruction.accounts_json.as_str());
let accounts_result = parse_accounts_json(instruction.accounts_json.as_str());
let accounts = match accounts_result {
Ok(accounts) => accounts,
Err(error) => return Err(error),
};
let parsed_json_result =
kb_parse_optional_parsed_json(instruction.parsed_json.as_ref());
let parsed_json_result = parse_optional_parsed_json(instruction.parsed_json.as_ref());
let parsed_json = match parsed_json_result {
Ok(parsed_json) => parsed_json,
Err(error) => return Err(error),
};
let instruction_kind =
kb_classify_instruction_kind(parsed_json.as_ref(), &log_messages);
let pool_account = kb_extract_string_by_candidate_keys(
let instruction_kind = classify_instruction_kind(parsed_json.as_ref(), &log_messages);
let pool_account = extract_string_by_candidate_keys(
parsed_json.as_ref(),
&["pool", "poolAddress", "poolAccount", "amm", "ammPool", "poolState"],
)
.or_else(|| return kb_extract_account(&accounts, 0));
let token_a_mint = kb_extract_string_by_candidate_keys(
.or_else(|| return extract_account(&accounts, 0));
let token_a_mint = extract_string_by_candidate_keys(
parsed_json.as_ref(),
&["tokenA", "tokenAMint", "mintA", "baseMint", "token0Mint", "mint0"],
)
.or_else(|| return kb_extract_account(&accounts, 1));
let token_b_mint = kb_extract_string_by_candidate_keys(
.or_else(|| return extract_account(&accounts, 1));
let token_b_mint = extract_string_by_candidate_keys(
parsed_json.as_ref(),
&["tokenB", "tokenBMint", "mintB", "quoteMint", "token1Mint", "mint1"],
)
.or_else(|| return kb_extract_account(&accounts, 2));
let creator = kb_extract_string_by_candidate_keys(
.or_else(|| return extract_account(&accounts, 2));
let creator = extract_string_by_candidate_keys(
parsed_json.as_ref(),
&["payer", "creator", "user", "owner"],
)
.or_else(|| return kb_extract_account(&accounts, 3));
let fee_tier = kb_extract_string_by_candidate_keys(
.or_else(|| return extract_account(&accounts, 3));
let fee_tier = extract_string_by_candidate_keys(
parsed_json.as_ref(),
&["feeTier", "fee_tier", "tradeFeeTier", "feeRate"],
);
if instruction_kind == KbDexlabInstructionKind::CreatePool {
if instruction_kind == DexlabInstructionKind::CreatePool {
let payload_json = serde_json::json!({
"decoder": "dexlab",
"eventKind": "create_pool",
@@ -178,8 +173,8 @@ impl KbDexlabDecoder {
"creator": creator,
"feeTier": fee_tier
});
decoded_events.push(crate::KbDexlabDecodedEvent::CreatePool(
crate::KbDexlabCreatePoolDecoded {
decoded_events.push(crate::DexlabDecodedEvent::CreatePool(
crate::DexlabCreatePoolDecoded {
transaction_id,
instruction_id,
signature: transaction.signature.clone(),
@@ -194,8 +189,8 @@ impl KbDexlabDecoder {
));
continue;
}
if instruction_kind == KbDexlabInstructionKind::Swap {
let trade_side = kb_infer_trade_side(&log_messages);
if instruction_kind == DexlabInstructionKind::Swap {
let trade_side = infer_trade_side(&log_messages);
let payload_json = serde_json::json!({
"decoder": "dexlab",
"eventKind": "swap",
@@ -210,57 +205,55 @@ impl KbDexlabDecoder {
"tokenBMint": token_b_mint,
"tradeSide": format!("{:?}", trade_side)
});
decoded_events.push(crate::KbDexlabDecodedEvent::Swap(
crate::KbDexlabSwapDecoded {
transaction_id,
instruction_id,
signature: transaction.signature.clone(),
program_id: program_id.clone(),
trade_side,
pool_account,
token_a_mint,
token_b_mint,
payload_json,
},
));
decoded_events.push(crate::DexlabDecodedEvent::Swap(crate::DexlabSwapDecoded {
transaction_id,
instruction_id,
signature: transaction.signature.clone(),
program_id: program_id.clone(),
trade_side,
pool_account,
token_a_mint,
token_b_mint,
payload_json,
}));
}
}
return Ok(decoded_events);
}
}
fn kb_classify_instruction_kind(
fn classify_instruction_kind(
parsed_json: std::option::Option<&serde_json::Value>,
log_messages: &[std::string::String],
) -> KbDexlabInstructionKind {
let parsed_instruction_name = kb_extract_string_by_candidate_keys(
) -> DexlabInstructionKind {
let parsed_instruction_name = extract_string_by_candidate_keys(
parsed_json,
&["instruction", "instructionName", "type", "name"],
);
if let Some(parsed_instruction_name) = parsed_instruction_name {
let normalized = kb_normalize_text(parsed_instruction_name.as_str());
let normalized = normalize_text(parsed_instruction_name.as_str());
if normalized.contains("createpool") || normalized.contains("initializepool") {
return KbDexlabInstructionKind::CreatePool;
return DexlabInstructionKind::CreatePool;
}
if normalized == "swap" {
return KbDexlabInstructionKind::Swap;
return DexlabInstructionKind::Swap;
}
}
if kb_log_messages_contain_keyword(log_messages, "create_pool")
|| kb_log_messages_contain_keyword(log_messages, "createpool")
|| kb_log_messages_contain_keyword(log_messages, "initialize_pool")
|| kb_log_messages_contain_keyword(log_messages, "initializepool")
if log_messages_contain_keyword(log_messages, "create_pool")
|| log_messages_contain_keyword(log_messages, "createpool")
|| log_messages_contain_keyword(log_messages, "initialize_pool")
|| log_messages_contain_keyword(log_messages, "initializepool")
{
return KbDexlabInstructionKind::CreatePool;
return DexlabInstructionKind::CreatePool;
}
if kb_log_messages_contain_keyword(log_messages, "swap") {
return KbDexlabInstructionKind::Swap;
if log_messages_contain_keyword(log_messages, "swap") {
return DexlabInstructionKind::Swap;
}
return KbDexlabInstructionKind::Unknown;
return DexlabInstructionKind::Unknown;
}
fn kb_extract_log_messages(
fn extract_log_messages(
transaction_json: &serde_json::Value,
) -> std::vec::Vec<std::string::String> {
let mut messages = std::vec::Vec::new();
@@ -287,10 +280,13 @@ fn kb_extract_log_messages(
return messages;
}
fn kb_log_messages_contain_keyword(log_messages: &[std::string::String], keyword: &str) -> bool {
let keyword_normalized = kb_normalize_text(keyword);
for log_message in log_messages {
let log_normalized = kb_normalize_text(log_message.as_str());
fn log_messages_contain_keyword(
log_messages_contain_keyword: &[std::string::String],
keyword: &str,
) -> bool {
let keyword_normalized = normalize_text(keyword);
for log_message in log_messages_contain_keyword {
let log_normalized = normalize_text(log_message.as_str());
if log_normalized.contains(keyword_normalized.as_str()) {
return true;
}
@@ -298,9 +294,9 @@ fn kb_log_messages_contain_keyword(log_messages: &[std::string::String], keyword
return false;
}
fn kb_normalize_text(value: &str) -> std::string::String {
fn normalize_text(normalize_text: &str) -> std::string::String {
let mut normalized = std::string::String::new();
for character in value.chars() {
for character in normalize_text.chars() {
if character.is_ascii_alphanumeric() {
normalized.push(character.to_ascii_lowercase());
}
@@ -308,14 +304,14 @@ fn kb_normalize_text(value: &str) -> std::string::String {
return normalized;
}
fn kb_parse_accounts_json(
fn parse_accounts_json(
accounts_json: &str,
) -> Result<std::vec::Vec<std::string::String>, crate::KbError> {
) -> Result<std::vec::Vec<std::string::String>, crate::Error> {
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!(
return Err(crate::Error::Json(format!(
"cannot parse instruction accounts_json '{}': {}",
accounts_json, error
)));
@@ -331,9 +327,9 @@ fn kb_parse_accounts_json(
return Ok(accounts);
}
fn kb_parse_optional_parsed_json(
fn parse_optional_parsed_json(
parsed_json: std::option::Option<&std::string::String>,
) -> Result<std::option::Option<serde_json::Value>, crate::KbError> {
) -> Result<std::option::Option<serde_json::Value>, crate::Error> {
let parsed_json = match parsed_json {
Some(parsed_json) => parsed_json,
None => return Ok(None),
@@ -342,7 +338,7 @@ fn kb_parse_optional_parsed_json(
match value_result {
Ok(value) => return Ok(Some(value)),
Err(error) => {
return Err(crate::KbError::Json(format!(
return Err(crate::Error::Json(format!(
"cannot parse instruction parsed_json '{}': {}",
parsed_json, error
)));
@@ -350,7 +346,7 @@ fn kb_parse_optional_parsed_json(
}
}
fn kb_extract_string_by_candidate_keys(
fn extract_string_by_candidate_keys(
value: std::option::Option<&serde_json::Value>,
candidate_keys: &[&str],
) -> std::option::Option<std::string::String> {
@@ -358,10 +354,10 @@ fn kb_extract_string_by_candidate_keys(
Some(value) => value,
None => return None,
};
return kb_extract_string_by_candidate_keys_inner(value, candidate_keys);
return extract_string_by_candidate_keys_inner(value, candidate_keys);
}
fn kb_extract_string_by_candidate_keys_inner(
fn extract_string_by_candidate_keys_inner(
value: &serde_json::Value,
candidate_keys: &[&str],
) -> std::option::Option<std::string::String> {
@@ -377,7 +373,7 @@ fn kb_extract_string_by_candidate_keys_inner(
}
for nested_value in object.values() {
let nested_result =
kb_extract_string_by_candidate_keys_inner(nested_value, candidate_keys);
extract_string_by_candidate_keys_inner(nested_value, candidate_keys);
if nested_result.is_some() {
return nested_result;
}
@@ -387,7 +383,7 @@ fn kb_extract_string_by_candidate_keys_inner(
if let Some(array) = value.as_array() {
for nested_value in array {
let nested_result =
kb_extract_string_by_candidate_keys_inner(nested_value, candidate_keys);
extract_string_by_candidate_keys_inner(nested_value, candidate_keys);
if nested_result.is_some() {
return nested_result;
}
@@ -396,30 +392,30 @@ fn kb_extract_string_by_candidate_keys_inner(
return None;
}
fn kb_extract_account(
accounts: &[std::string::String],
fn extract_account(
extract_account: &[std::string::String],
index: usize,
) -> std::option::Option<std::string::String> {
if index >= accounts.len() {
if index >= extract_account.len() {
return None;
}
return Some(accounts[index].clone());
return Some(extract_account[index].clone());
}
fn kb_infer_trade_side(log_messages: &[std::string::String]) -> crate::KbSwapTradeSide {
if kb_log_messages_contain_keyword(log_messages, "buy") {
return crate::KbSwapTradeSide::BuyBase;
fn infer_trade_side(log_messages: &[std::string::String]) -> crate::SwapTradeSide {
if log_messages_contain_keyword(log_messages, "buy") {
return crate::SwapTradeSide::BuyBase;
}
if kb_log_messages_contain_keyword(log_messages, "sell") {
return crate::KbSwapTradeSide::SellBase;
if log_messages_contain_keyword(log_messages, "sell") {
return crate::SwapTradeSide::SellBase;
}
return crate::KbSwapTradeSide::Unknown;
return crate::SwapTradeSide::Unknown;
}
#[cfg(test)]
mod tests {
fn make_create_transaction() -> crate::KbChainTransactionDto {
let mut dto = crate::KbChainTransactionDto::new(
fn make_create_transaction() -> crate::ChainTransactionDto {
let mut dto = crate::ChainTransactionDto::new(
"sig-dexlab-create-1".to_string(),
Some(893001),
Some(1779800001),
@@ -446,19 +442,19 @@ mod tests {
return dto;
}
fn make_create_instruction() -> crate::KbChainInstructionDto {
let mut dto = crate::KbChainInstructionDto::new(
fn make_create_instruction() -> crate::ChainInstructionDto {
let mut dto = crate::ChainInstructionDto::new(
801,
None,
0,
None,
Some(crate::KB_DEXLAB_PROGRAM_ID.to_string()),
Some(crate::DEXLAB_PROGRAM_ID.to_string()),
Some("dexlab".to_string()),
Some(1),
serde_json::json!([
"DexlabPool111",
"DexlabTokenA111",
"So11111111111111111111111111111111111111112",
crate::WSOL_MINT_ID,
"DexlabCreator111"
])
.to_string(),
@@ -470,7 +466,7 @@ mod tests {
"instruction": "create_pool",
"pool": "DexlabPool111",
"tokenA": "DexlabTokenA111",
"tokenB": "So11111111111111111111111111111111111111112",
"tokenB": crate::WSOL_MINT_ID,
"payer": "DexlabCreator111",
"feeTier": "0.3%"
}
@@ -482,8 +478,8 @@ mod tests {
return dto;
}
fn make_swap_transaction() -> crate::KbChainTransactionDto {
let mut dto = crate::KbChainTransactionDto::new(
fn make_swap_transaction() -> crate::ChainTransactionDto {
let mut dto = crate::ChainTransactionDto::new(
"sig-dexlab-swap-1".to_string(),
Some(893002),
Some(1779800002),
@@ -510,21 +506,17 @@ mod tests {
return dto;
}
fn make_swap_instruction() -> crate::KbChainInstructionDto {
let mut dto = crate::KbChainInstructionDto::new(
fn make_swap_instruction() -> crate::ChainInstructionDto {
let mut dto = crate::ChainInstructionDto::new(
803,
None,
0,
None,
Some(crate::KB_DEXLAB_PROGRAM_ID.to_string()),
Some(crate::DEXLAB_PROGRAM_ID.to_string()),
Some("dexlab".to_string()),
Some(1),
serde_json::json!([
"DexlabSwapPool111",
"DexlabSwapTokenA111",
"So11111111111111111111111111111111111111112"
])
.to_string(),
serde_json::json!(["DexlabSwapPool111", "DexlabSwapTokenA111", crate::WSOL_MINT_ID])
.to_string(),
None,
None,
Some(
@@ -533,7 +525,7 @@ mod tests {
"instruction": "swap",
"pool": "DexlabSwapPool111",
"tokenA": "DexlabSwapTokenA111",
"tokenB": "So11111111111111111111111111111111111111112"
"tokenB": crate::WSOL_MINT_ID
}
})
.to_string(),
@@ -545,7 +537,7 @@ mod tests {
#[test]
fn dexlab_create_pool_is_detected() {
let decoder = crate::KbDexlabDecoder::new();
let decoder = crate::DexlabDecoder::new();
let transaction = make_create_transaction();
let instructions = vec![make_create_instruction()];
let decoded_result = decoder.decode_transaction(&transaction, &instructions);
@@ -555,18 +547,15 @@ mod tests {
};
assert_eq!(decoded.len(), 1);
match &decoded[0] {
crate::KbDexlabDecodedEvent::CreatePool(event) => {
crate::DexlabDecodedEvent::CreatePool(event) => {
assert_eq!(event.transaction_id, 801);
assert_eq!(event.instruction_id, 802);
assert_eq!(event.pool_account, Some("DexlabPool111".to_string()));
assert_eq!(event.token_a_mint, Some("DexlabTokenA111".to_string()));
assert_eq!(
event.token_b_mint,
Some("So11111111111111111111111111111111111111112".to_string())
);
assert_eq!(event.token_b_mint, Some(crate::WSOL_MINT_ID.to_string()));
assert_eq!(event.fee_tier, Some("0.3%".to_string()));
},
crate::KbDexlabDecodedEvent::Swap(_) => {
crate::DexlabDecodedEvent::Swap(_) => {
panic!("unexpected swap event")
},
}
@@ -574,7 +563,7 @@ mod tests {
#[test]
fn dexlab_swap_is_detected() {
let decoder = crate::KbDexlabDecoder::new();
let decoder = crate::DexlabDecoder::new();
let transaction = make_swap_transaction();
let instructions = vec![make_swap_instruction()];
let decoded_result = decoder.decode_transaction(&transaction, &instructions);
@@ -584,17 +573,14 @@ mod tests {
};
assert_eq!(decoded.len(), 1);
match &decoded[0] {
crate::KbDexlabDecodedEvent::Swap(event) => {
crate::DexlabDecodedEvent::Swap(event) => {
assert_eq!(event.transaction_id, 803);
assert_eq!(event.instruction_id, 804);
assert_eq!(event.pool_account, Some("DexlabSwapPool111".to_string()));
assert_eq!(event.token_a_mint, Some("DexlabSwapTokenA111".to_string()));
assert_eq!(
event.token_b_mint,
Some("So11111111111111111111111111111111111111112".to_string())
);
assert_eq!(event.token_b_mint, Some(crate::WSOL_MINT_ID.to_string()));
},
crate::KbDexlabDecodedEvent::CreatePool(_) => {
crate::DexlabDecodedEvent::CreatePool(_) => {
panic!("unexpected create event")
},
}