arete-idl 0.1.0

IDL parsing and type system for Arete
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Search utilities for IDL specs with fuzzy matching

use crate::error::IdlSearchError;
use crate::types::IdlSpec;
use crate::types::{IdlAccount, IdlEvent, IdlInstruction, IdlTypeDef};
use strsim::levenshtein;

/// A fuzzy match suggestion with candidate name and edit distance.
#[derive(Debug, Clone)]
pub struct Suggestion {
    pub candidate: String,
    pub distance: usize,
}

/// Which section of the IDL a search result came from.
#[derive(Debug, Clone)]
pub enum IdlSection {
    Instruction,
    Account,
    Type,
    Error,
    Event,
    Constant,
}

/// How a search result was matched.
#[derive(Debug, Clone)]
pub enum MatchType {
    Exact,
    CaseInsensitive,
    Contains,
    Fuzzy(usize),
}

/// A single search result from `search_idl`.
#[derive(Debug, Clone)]
pub struct SearchResult {
    pub name: String,
    pub section: IdlSection,
    pub match_type: MatchType,
    pub path: Option<String>,
    pub parent_name: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstructionFieldKind {
    Account,
    Arg,
}

#[derive(Debug, Clone, Copy)]
pub struct InstructionFieldLookup<'a> {
    pub instruction: &'a IdlInstruction,
    pub kind: InstructionFieldKind,
}

fn build_not_found_error(input: &str, section: String, available: Vec<String>) -> IdlSearchError {
    let candidate_refs: Vec<&str> = available.iter().map(String::as_str).collect();
    let suggestions = suggest_similar(input, &candidate_refs, 3);
    IdlSearchError::NotFound {
        input: input.to_string(),
        section,
        suggestions,
        available,
    }
}

pub fn lookup_instruction<'a>(
    idl: &'a IdlSpec,
    instruction_name: &str,
) -> Result<&'a IdlInstruction, IdlSearchError> {
    // Anchor IDLs use snake_case instruction names while Rust SDK paths use
    // PascalCase; case-insensitive matching bridges the two conventions.
    let available: Vec<String> = idl.instructions.iter().map(|ix| ix.name.clone()).collect();
    idl.instructions
        .iter()
        .find(|ix| ix.name.eq_ignore_ascii_case(instruction_name))
        .ok_or_else(|| {
            build_not_found_error(instruction_name, "instructions".to_string(), available)
        })
}

pub fn lookup_account<'a>(
    idl: &'a IdlSpec,
    account_name: &str,
) -> Result<&'a IdlAccount, IdlSearchError> {
    // Account names are PascalCase in both Rust and IDLs, so case-insensitive
    // matching bridges minor casing differences across IDL versions.
    let available: Vec<String> = idl
        .accounts
        .iter()
        .map(|account| account.name.clone())
        .collect();
    idl.accounts
        .iter()
        .find(|account| account.name.eq_ignore_ascii_case(account_name))
        .ok_or_else(|| build_not_found_error(account_name, "accounts".to_string(), available))
}

pub fn lookup_type<'a>(
    idl: &'a IdlSpec,
    type_name: &str,
) -> Result<&'a IdlTypeDef, IdlSearchError> {
    let available: Vec<String> = idl.types.iter().map(|ty| ty.name.clone()).collect();
    idl.types
        .iter()
        .find(|ty| ty.name.eq_ignore_ascii_case(type_name))
        .ok_or_else(|| build_not_found_error(type_name, "types".to_string(), available))
}

pub fn lookup_event<'a>(
    idl: &'a IdlSpec,
    event_name: &str,
) -> Result<&'a IdlEvent, IdlSearchError> {
    let available: Vec<String> = idl.events.iter().map(|event| event.name.clone()).collect();
    idl.events
        .iter()
        .find(|event| event.name.eq_ignore_ascii_case(event_name))
        .ok_or_else(|| build_not_found_error(event_name, "events".to_string(), available))
}

pub fn lookup_event_field(
    idl: &IdlSpec,
    event_name: &str,
    field_name: &str,
) -> Result<(), IdlSearchError> {
    let _event = lookup_event(idl, event_name)?;
    let fields = idl
        .resolve_event_fields(event_name)
        .map(|resolved| resolved.fields)
        .unwrap_or_default();

    // Some IDLs expose event names but omit field metadata in the `events`
    // section. When there is also no matching struct type, keep validation
    // permissive rather than rejecting otherwise valid event mappings.
    if fields.is_empty() {
        return Ok(());
    }

    if fields
        .iter()
        .any(|field| field.name.eq_ignore_ascii_case(field_name))
    {
        return Ok(());
    }

    let available: Vec<String> = fields.iter().map(|field| field.name.clone()).collect();
    Err(build_not_found_error(
        field_name,
        format!("event fields for '{}'", event_name),
        available,
    ))
}

pub fn lookup_instruction_field<'a>(
    idl: &'a IdlSpec,
    instruction_name: &str,
    field_name: &str,
) -> Result<InstructionFieldLookup<'a>, IdlSearchError> {
    let instruction = lookup_instruction(idl, instruction_name)?;
    // Use case-insensitive matching to stay consistent with lookup_instruction.
    if instruction
        .accounts
        .iter()
        .any(|account| account.name.eq_ignore_ascii_case(field_name))
    {
        return Ok(InstructionFieldLookup {
            instruction,
            kind: InstructionFieldKind::Account,
        });
    }

    if instruction
        .args
        .iter()
        .any(|arg| arg.name.eq_ignore_ascii_case(field_name))
    {
        return Ok(InstructionFieldLookup {
            instruction,
            kind: InstructionFieldKind::Arg,
        });
    }

    let mut available: Vec<String> = instruction
        .accounts
        .iter()
        .map(|acc| acc.name.clone())
        .collect();
    available.extend(instruction.args.iter().map(|arg| arg.name.clone()));
    Err(build_not_found_error(
        field_name,
        format!("instruction fields for '{}'", instruction.name),
        available,
    ))
}

/// Suggest similar names from a list of candidates using fuzzy matching.
///
/// Returns candidates sorted by edit distance (closest first).
/// Exact matches are excluded. Case-insensitive matches get distance 0,
/// substring matches get distance 1, and Levenshtein matches use their
/// actual edit distance.
pub fn suggest_similar(name: &str, candidates: &[&str], max_distance: usize) -> Vec<Suggestion> {
    let name_lower = name.to_lowercase();
    let mut suggestions: Vec<Suggestion> = candidates
        .iter()
        .filter_map(|&candidate| {
            // Skip exact matches
            if candidate == name {
                return None;
            }
            let candidate_lower = candidate.to_lowercase();
            // Case-insensitive match
            if candidate_lower == name_lower {
                return Some(Suggestion {
                    candidate: candidate.to_string(),
                    distance: 0,
                });
            }
            // Substring match
            if candidate_lower.contains(&name_lower) || name_lower.contains(&candidate_lower) {
                return Some(Suggestion {
                    candidate: candidate.to_string(),
                    distance: 1,
                });
            }
            // Levenshtein distance
            let dist = levenshtein(name, candidate);
            if dist <= max_distance {
                Some(Suggestion {
                    candidate: candidate.to_string(),
                    distance: dist,
                })
            } else {
                None
            }
        })
        .collect();
    suggestions.sort_by_key(|s| s.distance);
    suggestions
}

/// Search across all sections of an IDL spec for names matching the query.
///
/// Performs case-insensitive substring matching against instruction names,
/// account names, type names, error names, event names, and constant names.
pub fn search_idl(idl: &IdlSpec, query: &str) -> Vec<SearchResult> {
    let mut results = Vec::new();
    let q = query.to_lowercase();

    for ix in &idl.instructions {
        if ix.name.to_lowercase().contains(&q) {
            results.push(SearchResult {
                name: ix.name.clone(),
                section: IdlSection::Instruction,
                match_type: MatchType::Contains,
                path: None,
                parent_name: None,
            });
        }
    }
    for acc in &idl.accounts {
        if acc.name.to_lowercase().contains(&q) {
            results.push(SearchResult {
                name: acc.name.clone(),
                section: IdlSection::Account,
                match_type: MatchType::Contains,
                path: None,
                parent_name: None,
            });
        }
    }
    for ty in &idl.types {
        if ty.name.to_lowercase().contains(&q) {
            results.push(SearchResult {
                name: ty.name.clone(),
                section: IdlSection::Type,
                match_type: MatchType::Contains,
                path: None,
                parent_name: None,
            });
        }
    }
    for err in &idl.errors {
        if err.name.to_lowercase().contains(&q) {
            results.push(SearchResult {
                name: err.name.clone(),
                section: IdlSection::Error,
                match_type: MatchType::Contains,
                path: None,
                parent_name: None,
            });
        }
    }
    for ev in &idl.events {
        let name_match = ev.name.to_lowercase().contains(&q);
        let docs_match = ev.docs.iter().any(|doc| doc.to_lowercase().contains(&q));
        if name_match || docs_match {
            results.push(SearchResult {
                name: ev.name.clone(),
                section: IdlSection::Event,
                match_type: MatchType::Contains,
                path: None,
                parent_name: None,
            });
        }

        let resolved = idl.resolve_event_fields_for(ev);
        for field in resolved.fields {
            if field.name.to_lowercase().contains(&q) {
                results.push(SearchResult {
                    name: field.name.clone(),
                    section: IdlSection::Event,
                    match_type: MatchType::Contains,
                    path: Some(format!("{}.{}", ev.name, field.name)),
                    parent_name: Some(ev.name.clone()),
                });
            }
        }
    }
    for c in &idl.constants {
        if c.name.to_lowercase().contains(&q) {
            results.push(SearchResult {
                name: c.name.clone(),
                section: IdlSection::Constant,
                match_type: MatchType::Contains,
                path: None,
                parent_name: None,
            });
        }
    }
    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fuzzy_suggestions() {
        let candidates = ["initialize", "close", "deposit"];
        let suggestions = suggest_similar("initlize", &candidates, 3);
        assert!(!suggestions.is_empty());
        assert_eq!(suggestions[0].candidate, "initialize");
    }

    #[test]
    fn test_fuzzy_case_insensitive() {
        let candidates = ["Initialize", "close"];
        let suggestions = suggest_similar("initialize", &candidates, 3);
        assert!(!suggestions.is_empty());
        assert_eq!(suggestions[0].candidate, "Initialize");
        assert_eq!(suggestions[0].distance, 0);
    }

    #[test]
    fn test_fuzzy_no_exact_match() {
        let candidates = ["initialize"];
        let suggestions = suggest_similar("initialize", &candidates, 3);
        assert!(suggestions.is_empty(), "exact matches should be excluded");
    }

    #[test]
    fn test_fuzzy_substring() {
        let candidates = ["swap_exact_in", "close"];
        let suggestions = suggest_similar("swap", &candidates, 3);
        assert!(!suggestions.is_empty());
        assert_eq!(suggestions[0].candidate, "swap_exact_in");
    }

    #[test]
    fn test_search_idl() {
        use crate::parse::parse_idl_file;
        use std::path::PathBuf;
        let path =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/meteora_dlmm.json");
        let idl = parse_idl_file(&path).expect("should parse");
        let results = search_idl(&idl, "swap");
        assert!(!results.is_empty(), "should find results for 'swap'");
    }

    #[test]
    fn test_search_idl_finds_event_fields() {
        use crate::parse::parse_idl_content;

        let idl = parse_idl_content(
            r#"{
                "name": "fake",
                "instructions": [],
                "accounts": [],
                "types": [
                    {
                        "name": "TradeExecuted",
                        "type": {
                            "kind": "struct",
                            "fields": [
                                { "name": "periodStartTs", "type": "i64" },
                                { "name": "amount", "type": "u64" }
                            ]
                        }
                    }
                ],
                "events": [
                    {
                        "name": "TradeExecuted",
                        "discriminator": [1],
                        "data": { "name": "TradeExecuted" }
                    }
                ],
                "errors": [],
                "constants": []
            }"#,
        )
        .expect("test IDL should parse");

        let results = search_idl(&idl, "periodStartTs");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "periodStartTs");
        assert_eq!(results[0].parent_name.as_deref(), Some("TradeExecuted"));
        assert_eq!(
            results[0].path.as_deref(),
            Some("TradeExecuted.periodStartTs")
        );
    }

    #[test]
    fn test_lookup_instruction_with_suggestion() {
        use crate::parse::parse_idl_file;
        use std::path::PathBuf;

        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pump.json");
        let idl = parse_idl_file(&path).expect("should parse");

        let error = lookup_instruction(&idl, "initialise").expect_err("lookup should fail");
        match error {
            IdlSearchError::NotFound { suggestions, .. } => {
                assert_eq!(suggestions[0].candidate, "initialize");
            }
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[test]
    fn test_lookup_instruction_field_with_suggestion() {
        use crate::parse::parse_idl_file;
        use std::path::PathBuf;

        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pump.json");
        let idl = parse_idl_file(&path).expect("should parse");

        let error = lookup_instruction_field(&idl, "buy", "usr").expect_err("lookup should fail");
        match error {
            IdlSearchError::NotFound { suggestions, .. } => {
                assert_eq!(suggestions[0].candidate, "user");
            }
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[test]
    fn test_lookup_event_field_uses_matching_type_definition() {
        use crate::parse::parse_idl_content;

        let idl = parse_idl_content(
            r#"{
                "name": "fake",
                "instructions": [],
                "accounts": [],
                "types": [
                    {
                        "name": "TradeExecuted",
                        "type": {
                            "kind": "struct",
                            "fields": [
                                { "name": "user", "type": "string" },
                                { "name": "amount", "type": "u64" }
                            ]
                        }
                    }
                ],
                "events": [
                    {
                        "name": "TradeExecuted",
                        "discriminator": [1]
                    }
                ],
                "errors": [],
                "constants": []
            }"#,
        )
        .expect("test IDL should parse");

        lookup_event_field(&idl, "TradeExecuted", "amount")
            .expect("matching type definition should provide event fields");
    }

    #[test]
    fn test_lookup_event_field_with_suggestion() {
        use crate::parse::parse_idl_content;

        let idl = parse_idl_content(
            r#"{
                "name": "fake",
                "instructions": [],
                "accounts": [],
                "types": [
                    {
                        "name": "TradeExecuted",
                        "type": {
                            "kind": "struct",
                            "fields": [
                                { "name": "user", "type": "string" },
                                { "name": "amount", "type": "u64" }
                            ]
                        }
                    }
                ],
                "events": [
                    {
                        "name": "TradeExecuted",
                        "discriminator": [1]
                    }
                ],
                "errors": [],
                "constants": []
            }"#,
        )
        .expect("test IDL should parse");

        let error =
            lookup_event_field(&idl, "TradeExecuted", "ammount").expect_err("lookup should fail");
        match error {
            IdlSearchError::NotFound { suggestions, .. } => {
                assert_eq!(suggestions[0].candidate, "amount");
            }
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[test]
    fn test_lookup_account_success() {
        use crate::parse::parse_idl_file;
        use std::path::PathBuf;

        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pump.json");
        let idl = parse_idl_file(&path).expect("should parse");

        let account = lookup_account(&idl, "BondingCurve").expect("account should exist");
        assert_eq!(account.name, "BondingCurve");
    }

    #[test]
    fn test_lookup_instruction_case_insensitive() {
        use crate::parse::parse_idl_file;
        use std::path::PathBuf;

        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pump.json");
        let idl = parse_idl_file(&path).expect("should parse");

        // PascalCase SDK name matches snake_case IDL name
        let instruction = lookup_instruction(&idl, "Buy").expect("should match case-insensitively");
        assert_eq!(instruction.name, "buy");
    }

    #[test]
    fn test_lookup_account_case_insensitive() {
        use crate::parse::parse_idl_file;
        use std::path::PathBuf;

        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pump.json");
        let idl = parse_idl_file(&path).expect("should parse");

        let account =
            lookup_account(&idl, "bondingCurve").expect("should match case-insensitively");
        assert_eq!(account.name, "BondingCurve");
    }
}