0.7.2
This commit is contained in:
361
kb_lib/src/dex_decode.rs
Normal file
361
kb_lib/src/dex_decode.rs
Normal file
@@ -0,0 +1,361 @@
|
||||
// file: kb_lib/src/dex_decode.rs
|
||||
|
||||
//! Persistence-oriented DEX decoding service.
|
||||
|
||||
/// DEX decode service.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KbDexDecodeService {
|
||||
database: std::sync::Arc<crate::KbDatabase>,
|
||||
persistence: crate::KbDetectionPersistenceService,
|
||||
raydium_amm_v4_decoder: crate::KbRaydiumAmmV4Decoder,
|
||||
}
|
||||
|
||||
impl KbDexDecodeService {
|
||||
/// Creates a new DEX decode service.
|
||||
pub fn new(database: std::sync::Arc<crate::KbDatabase>) -> Self {
|
||||
let persistence = crate::KbDetectionPersistenceService::new(database.clone());
|
||||
Self {
|
||||
database,
|
||||
persistence,
|
||||
raydium_amm_v4_decoder: crate::KbRaydiumAmmV4Decoder::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes one projected transaction and persists the decoded events.
|
||||
pub async fn decode_transaction_by_signature(
|
||||
&self,
|
||||
signature: &str,
|
||||
) -> Result<std::vec::Vec<crate::KbDexDecodedEventDto>, crate::KbError> {
|
||||
let transaction_result =
|
||||
crate::get_chain_transaction_by_signature(self.database.as_ref(), signature).await;
|
||||
let transaction_option = match transaction_result {
|
||||
Ok(transaction_option) => transaction_option,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let transaction = match transaction_option {
|
||||
Some(transaction) => transaction,
|
||||
None => {
|
||||
return Err(crate::KbError::InvalidState(format!(
|
||||
"cannot decode unknown chain transaction '{}'",
|
||||
signature
|
||||
)));
|
||||
}
|
||||
};
|
||||
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",
|
||||
signature
|
||||
)));
|
||||
}
|
||||
};
|
||||
let instructions_result = crate::list_chain_instructions_by_transaction_id(
|
||||
self.database.as_ref(),
|
||||
transaction_id,
|
||||
)
|
||||
.await;
|
||||
let instructions = match instructions_result {
|
||||
Ok(instructions) => instructions,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let decoded_result = self
|
||||
.raydium_amm_v4_decoder
|
||||
.decode_transaction(&transaction, &instructions);
|
||||
let decoded = match decoded_result {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut persisted = std::vec::Vec::new();
|
||||
for decoded_event in &decoded {
|
||||
let persist_result = self
|
||||
.persist_raydium_event(&transaction, decoded_event)
|
||||
.await;
|
||||
let persisted_event = match persist_result {
|
||||
Ok(persisted_event) => persisted_event,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
persisted.push(persisted_event);
|
||||
}
|
||||
Ok(persisted)
|
||||
}
|
||||
|
||||
async fn persist_raydium_event(
|
||||
&self,
|
||||
transaction: &crate::KbChainTransactionDto,
|
||||
decoded_event: &crate::KbRaydiumAmmV4DecodedEvent,
|
||||
) -> Result<crate::KbDexDecodedEventDto, crate::KbError> {
|
||||
match decoded_event {
|
||||
crate::KbRaydiumAmmV4DecodedEvent::Initialize2Pool(event) => {
|
||||
let payload_json_result = serde_json::to_string(&event.payload_json);
|
||||
let payload_json = match payload_json_result {
|
||||
Ok(payload_json) => payload_json,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Json(format!(
|
||||
"cannot serialize decoded raydium payload: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let existing_result = crate::get_dex_decoded_event_by_key(
|
||||
self.database.as_ref(),
|
||||
event.transaction_id,
|
||||
Some(event.instruction_id),
|
||||
"raydium_amm_v4.initialize2_pool",
|
||||
)
|
||||
.await;
|
||||
let existing_option = match existing_result {
|
||||
Ok(existing_option) => existing_option,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let already_present = existing_option.is_some();
|
||||
let dto = crate::KbDexDecodedEventDto::new(
|
||||
event.transaction_id,
|
||||
Some(event.instruction_id),
|
||||
"raydium_amm_v4".to_string(),
|
||||
event.program_id.clone(),
|
||||
"raydium_amm_v4.initialize2_pool".to_string(),
|
||||
event.pool_account.clone(),
|
||||
event.lp_mint.clone(),
|
||||
event.token_a_mint.clone(),
|
||||
event.token_b_mint.clone(),
|
||||
event.market_account.clone(),
|
||||
payload_json,
|
||||
);
|
||||
let upsert_result =
|
||||
crate::upsert_dex_decoded_event(self.database.as_ref(), &dto).await;
|
||||
if let Err(error) = upsert_result {
|
||||
return Err(error);
|
||||
}
|
||||
let fetched_result = crate::get_dex_decoded_event_by_key(
|
||||
self.database.as_ref(),
|
||||
event.transaction_id,
|
||||
Some(event.instruction_id),
|
||||
"raydium_amm_v4.initialize2_pool",
|
||||
)
|
||||
.await;
|
||||
let fetched_option = match fetched_result {
|
||||
Ok(fetched_option) => fetched_option,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let fetched = match fetched_option {
|
||||
Some(fetched) => fetched,
|
||||
None => {
|
||||
return Err(crate::KbError::InvalidState(
|
||||
"decoded event disappeared after upsert".to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
if !already_present {
|
||||
let payload_value = event.payload_json.clone();
|
||||
let observation_result = self
|
||||
.persistence
|
||||
.record_observation(&crate::KbDetectionObservationInput::new(
|
||||
"dex.raydium_amm_v4.initialize2_pool".to_string(),
|
||||
crate::KbObservationSourceKind::HttpRpc,
|
||||
transaction.source_endpoint_name.clone(),
|
||||
transaction.signature.clone(),
|
||||
transaction.slot,
|
||||
payload_value.clone(),
|
||||
))
|
||||
.await;
|
||||
let observation_id = match observation_result {
|
||||
Ok(observation_id) => observation_id,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let signal_result = self
|
||||
.persistence
|
||||
.record_signal(&crate::KbDetectionSignalInput::new(
|
||||
"signal.dex.raydium_amm_v4.initialize2_pool".to_string(),
|
||||
crate::KbAnalysisSignalSeverity::Low,
|
||||
transaction.signature.clone(),
|
||||
Some(observation_id),
|
||||
None,
|
||||
payload_value,
|
||||
))
|
||||
.await;
|
||||
if let Err(error) = signal_result {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(fetched)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
async fn make_database() -> std::sync::Arc<crate::KbDatabase> {
|
||||
let tempdir_result = tempfile::tempdir();
|
||||
let tempdir = match tempdir_result {
|
||||
Ok(tempdir) => tempdir,
|
||||
Err(error) => panic!("tempdir must succeed: {}", error),
|
||||
};
|
||||
let database_path = tempdir.path().join("dex_decode.sqlite3");
|
||||
let config = crate::KbDatabaseConfig {
|
||||
enabled: true,
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
sqlite: crate::KbSqliteDatabaseConfig {
|
||||
path: database_path.to_string_lossy().to_string(),
|
||||
create_if_missing: true,
|
||||
busy_timeout_ms: 5000,
|
||||
max_connections: 1,
|
||||
auto_initialize_schema: true,
|
||||
use_wal: true,
|
||||
},
|
||||
};
|
||||
let database_result = crate::KbDatabase::connect_and_initialize(&config).await;
|
||||
let database = match database_result {
|
||||
Ok(database) => database,
|
||||
Err(error) => panic!("database init must succeed: {}", error),
|
||||
};
|
||||
std::sync::Arc::new(database)
|
||||
}
|
||||
|
||||
async fn seed_projected_transaction(
|
||||
database: std::sync::Arc<crate::KbDatabase>,
|
||||
signature: &str,
|
||||
) {
|
||||
let service = crate::KbTransactionModelService::new(database);
|
||||
let resolved_transaction = serde_json::json!({
|
||||
"slot": 999001,
|
||||
"blockTime": 1779000001,
|
||||
"version": 0,
|
||||
"transaction": {
|
||||
"message": {
|
||||
"instructions": [
|
||||
{
|
||||
"programId": crate::KB_RAYDIUM_AMM_V4_PROGRAM_ID,
|
||||
"program": "raydium-amm-v4",
|
||||
"stackHeight": 1,
|
||||
"accounts": [
|
||||
"Account0",
|
||||
"Account1",
|
||||
"Account2",
|
||||
"Account3",
|
||||
"PoolXYZ",
|
||||
"Account5",
|
||||
"Account6",
|
||||
"LpMintXYZ",
|
||||
"TokenAXYZ",
|
||||
"TokenBXYZ",
|
||||
"Account10",
|
||||
"Account11",
|
||||
"Account12",
|
||||
"Account13",
|
||||
"Account14",
|
||||
"Account15",
|
||||
"MarketXYZ"
|
||||
],
|
||||
"data": "opaque"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"meta": {
|
||||
"err": null,
|
||||
"logMessages": [
|
||||
"Program log: initialize2"
|
||||
]
|
||||
}
|
||||
});
|
||||
let persist_result = service
|
||||
.persist_resolved_transaction(
|
||||
signature,
|
||||
Some("helius_primary_http".to_string()),
|
||||
&resolved_transaction,
|
||||
)
|
||||
.await;
|
||||
if let Err(error) = persist_result {
|
||||
panic!("projection must succeed: {}", error);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decode_transaction_by_signature_persists_decoded_event() {
|
||||
let database = make_database().await;
|
||||
seed_projected_transaction(database.clone(), "sig-dex-decode-1").await;
|
||||
let service = crate::KbDexDecodeService::new(database.clone());
|
||||
let decoded_result = service
|
||||
.decode_transaction_by_signature("sig-dex-decode-1")
|
||||
.await;
|
||||
let decoded = match decoded_result {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => panic!("decode must succeed: {}", error),
|
||||
};
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(decoded[0].protocol_name, "raydium_amm_v4");
|
||||
assert_eq!(decoded[0].event_kind, "raydium_amm_v4.initialize2_pool");
|
||||
assert_eq!(decoded[0].pool_account, Some("PoolXYZ".to_string()));
|
||||
let transaction_result =
|
||||
crate::get_chain_transaction_by_signature(database.as_ref(), "sig-dex-decode-1").await;
|
||||
let transaction_option = match transaction_result {
|
||||
Ok(transaction_option) => transaction_option,
|
||||
Err(error) => panic!("transaction fetch must succeed: {}", error),
|
||||
};
|
||||
let transaction = match transaction_option {
|
||||
Some(transaction) => transaction,
|
||||
None => panic!("transaction must exist"),
|
||||
};
|
||||
let transaction_id_option = transaction.id;
|
||||
let transaction_id = match transaction_id_option {
|
||||
Some(transaction_id) => transaction_id,
|
||||
None => panic!("transaction id must exist"),
|
||||
};
|
||||
let listed_result =
|
||||
crate::list_dex_decoded_events_by_transaction_id(database.as_ref(), transaction_id)
|
||||
.await;
|
||||
let listed = match listed_result {
|
||||
Ok(listed) => listed,
|
||||
Err(error) => panic!("dex event list must succeed: {}", error),
|
||||
};
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].lp_mint, Some("LpMintXYZ".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decode_transaction_by_signature_is_idempotent_on_same_transaction() {
|
||||
let database = make_database().await;
|
||||
seed_projected_transaction(database.clone(), "sig-dex-decode-2").await;
|
||||
let service = crate::KbDexDecodeService::new(database.clone());
|
||||
let first_result = service
|
||||
.decode_transaction_by_signature("sig-dex-decode-2")
|
||||
.await;
|
||||
if let Err(error) = first_result {
|
||||
panic!("first decode must succeed: {}", error);
|
||||
}
|
||||
let second_result = service
|
||||
.decode_transaction_by_signature("sig-dex-decode-2")
|
||||
.await;
|
||||
let second = match second_result {
|
||||
Ok(second) => second,
|
||||
Err(error) => panic!("second decode must succeed: {}", error),
|
||||
};
|
||||
assert_eq!(second.len(), 1);
|
||||
let transaction_result =
|
||||
crate::get_chain_transaction_by_signature(database.as_ref(), "sig-dex-decode-2").await;
|
||||
let transaction_option = match transaction_result {
|
||||
Ok(transaction_option) => transaction_option,
|
||||
Err(error) => panic!("transaction fetch must succeed: {}", error),
|
||||
};
|
||||
let transaction = match transaction_option {
|
||||
Some(transaction) => transaction,
|
||||
None => panic!("transaction must exist"),
|
||||
};
|
||||
let transaction_id_option = transaction.id;
|
||||
let transaction_id = match transaction_id_option {
|
||||
Some(transaction_id) => transaction_id,
|
||||
None => panic!("transaction id must exist"),
|
||||
};
|
||||
let listed_result =
|
||||
crate::list_dex_decoded_events_by_transaction_id(database.as_ref(), transaction_id)
|
||||
.await;
|
||||
let listed = match listed_result {
|
||||
Ok(listed) => listed,
|
||||
Err(error) => panic!("dex event list must succeed: {}", error),
|
||||
};
|
||||
assert_eq!(listed.len(), 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user