-- file: validation_sql/SQL_TRACE_RAYDIUM_CPMM_AUDIT_40F_0_7_50_PRE_R2.sql
-- Purpose: locate the Raydium CPMM audit-only discriminator 40f4bc78a7e9690a
-- so the instruction can be inspected manually on Solscan or decoded from local meta_json.

SELECT
    tx.signature,
    tx.slot,
    de.id AS decoded_event_id,
    de.pool_account,
    de.token_a_mint,
    de.token_b_mint,
    json_extract(de.payload_json, '$.instructionIndex') AS instruction_index,
    json_extract(de.payload_json, '$.innerInstructionIndex') AS inner_instruction_index,
    json_extract(de.payload_json, '$.programId') AS program_id,
    json_extract(de.payload_json, '$.discriminatorHex') AS discriminator_hex,
    json_extract(de.payload_json, '$.accountCount') AS account_count,
    json_extract(de.payload_json, '$.accounts') AS accounts_json,
    json_extract(de.payload_json, '$.data') AS instruction_data,
    de.payload_json
FROM k_sol_dex_decoded_events de
JOIN k_sol_chain_transactions tx
    ON tx.id = de.transaction_id
WHERE de.protocol_name = 'raydium_cpmm'
  AND de.event_kind = 'raydium_cpmm.instruction_audit'
  AND json_extract(de.payload_json, '$.discriminatorHex') = '40f4bc78a7e9690a'
ORDER BY tx.slot, tx.signature, instruction_index, inner_instruction_index;

-- Optional: include the raw projected instruction row if decoded_event.instruction_id is populated.
SELECT
    tx.signature,
    tx.slot,
    de.id AS decoded_event_id,
    ci.id AS chain_instruction_id,
    ci.instruction_index,
    ci.inner_instruction_index,
    ci.program_id,
    ci.accounts_json,
    ci.data_json,
    de.payload_json
FROM k_sol_dex_decoded_events de
JOIN k_sol_chain_transactions tx
    ON tx.id = de.transaction_id
LEFT JOIN k_sol_chain_instructions ci
    ON ci.id = de.instruction_id
WHERE de.protocol_name = 'raydium_cpmm'
  AND de.event_kind = 'raydium_cpmm.instruction_audit'
  AND json_extract(de.payload_json, '$.discriminatorHex') = '40f4bc78a7e9690a'
ORDER BY tx.slot, tx.signature, ci.instruction_index, ci.inner_instruction_index;
