ic-query 0.45.4

Internet Computer query library for CloudEngine, NNS, SNS, ICRC, system canisters, and public network metadata
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
use super::*;
use crate::{
    QueryProgress,
    cache::{CacheRefreshAttemptStatus, CacheValidationStatus},
    icrc::{
        IcrcAccountTransactionCacheRequest, IcrcAccountTransactionCollectionData,
        IcrcAccountTransactionCollectionSource, IcrcAccountTransactionError,
        IcrcAccountTransactionListRequest, IcrcAccountTransactionRefreshRequest,
        IcrcAccountTransactionRow, IcrcAccountTransactionSort,
    },
    test_support::temp_dir,
};
use candid::Principal;
use serde_json::json;
use std::{
    fs,
    path::Path,
    sync::atomic::{AtomicUsize, Ordering},
};

const LEDGER_CANISTER_ID: &str = "ryjl3-tyaaa-aaaaa-aaaba-cai";
const INDEX_CANISTER_ID: &str = "qhbym-qaaaa-aaaaa-aaafq-cai";
const ACCOUNT_OWNER: &str = "aaaaa-aa";

#[test]
fn cache_entity_changes_with_collection_identity_and_normalizes_subaccounts() {
    let first = IcrcAccountTransactionCacheRequest::new(
        "/tmp/ic-query-cache",
        "https://icp-api.io",
        "ryjl3-tyaaa-aaaaa-aaaba-cai",
        "aaaaa-aa",
    );
    let same = first.clone();
    let different_endpoint = IcrcAccountTransactionCacheRequest {
        source_endpoint: "https://example.com".to_string(),
        ..first.clone()
    };

    assert_eq!(storage::cache_entity(&first), storage::cache_entity(&same));
    assert_ne!(
        storage::cache_entity(&first),
        storage::cache_entity(&different_endpoint)
    );

    let lowercase = first.clone().with_subaccount_hex("ab".repeat(32));
    let uppercase = first.with_subaccount_hex("AB".repeat(32));
    assert_eq!(
        icrc_account_transaction_cache_path(&lowercase).expect("lowercase cache path"),
        icrc_account_transaction_cache_path(&uppercase).expect("uppercase cache path")
    );
}

#[test]
fn complete_refresh_publishes_canonical_cache_and_cache_only_views() {
    let root = temp_dir("ic-query-icrc-account-refresh");
    let cache = cache_request(&root);
    let request = refresh_request(cache.clone(), 1_700_000_000);
    let source = SuccessSource::new(vec![row("12"), row("10"), row("2")]);

    let refresh = refresh_icrc_account_transaction_cache_with_source(&request, &source)
        .expect("refresh complete cache");
    let cached = load_cached_icrc_account_transactions(&cache).expect("load complete cache");
    let oldest = build_icrc_account_transaction_list_report(
        &IcrcAccountTransactionListRequest::new(cache.clone(), 2)
            .with_sort(IcrcAccountTransactionSort::Oldest),
    )
    .expect("list cache oldest first");
    let status =
        build_icrc_account_transaction_cache_status_report(&cache).expect("cache status report");

    assert!(!refresh.point_in_time_guaranteed);
    assert_eq!(refresh.transaction_count, 3);
    assert_eq!(cached.snapshot.completeness.status, "api_exhausted");
    assert_eq!(cached.snapshot.completeness.row_count, 3);
    assert_eq!(
        oldest
            .transactions
            .iter()
            .map(|transaction| transaction.id.as_str())
            .collect::<Vec<_>>(),
        vec!["2", "10"]
    );
    assert_eq!(oldest.total_transaction_count, 3);
    assert_eq!(
        status.cache.as_ref().expect("cache summary").cache_status,
        CacheValidationStatus::Valid
    );
    assert_eq!(
        status
            .latest_attempt
            .as_ref()
            .expect("refresh attempt")
            .status,
        CacheRefreshAttemptStatus::Complete
    );
    assert_eq!(source.calls.load(Ordering::Relaxed), 1);

    let _ = fs::remove_dir_all(root);
}

#[test]
fn failed_auto_discovered_refresh_preserves_cache_and_resolved_index_evidence() {
    let root = temp_dir("ic-query-icrc-account-refresh-failure");
    let cache = cache_request(&root);
    let first_request = refresh_request(cache.clone(), 1_700_000_000);
    refresh_icrc_account_transaction_cache_with_source(
        &first_request,
        &SuccessSource::new(vec![row("7")]),
    )
    .expect("seed complete cache");
    let path = icrc_account_transaction_cache_path(&cache).expect("cache path");
    let before = fs::read(&path).expect("read seeded cache");
    let failed_request = refresh_request(cache.clone(), 1_700_000_001);

    let error =
        refresh_icrc_account_transaction_cache_with_source(&failed_request, &IncompleteSource)
            .expect_err("incomplete refresh must fail");
    let after = fs::read(&path).expect("read preserved cache");
    let status =
        build_icrc_account_transaction_cache_status_report(&cache).expect("cache status report");

    assert!(matches!(
        error,
        IcrcAccountTransactionError::IncompleteCollection {
            index_canister_id,
            pages_fetched: 2,
            rows_fetched: 100,
            ..
        } if index_canister_id.as_deref() == Some(INDEX_CANISTER_ID)
    ));
    assert_eq!(after, before);
    assert_eq!(
        status.cache.as_ref().expect("preserved cache").cache_status,
        CacheValidationStatus::Valid
    );
    let attempt = status.latest_attempt.expect("failed attempt");
    assert_eq!(attempt.status, CacheRefreshAttemptStatus::Failed);
    assert_eq!(attempt.pages_fetched, 2);
    assert_eq!(attempt.rows_fetched, 100);
    assert_eq!(attempt.last_cursor.as_deref(), Some("50"));
    assert_eq!(
        attempt.index_canister_id.as_deref(),
        Some(INDEX_CANISTER_ID)
    );

    let _ = fs::remove_dir_all(root);
}

#[test]
fn invalid_source_rows_preserve_the_snapshot_and_failure_evidence() {
    let root = temp_dir("ic-query-icrc-account-source-row-validation");
    let cache = cache_request(&root);
    let request = refresh_request(cache.clone(), 1_700_000_000);
    refresh_icrc_account_transaction_cache_with_source(
        &request,
        &SuccessSource::new(vec![row("7")]),
    )
    .unwrap();
    let path = icrc_account_transaction_cache_path(&cache).unwrap();
    let before = fs::read(&path).unwrap();
    for ids in [
        vec!["7", "7"],
        vec!["1", "2"],
        vec!["00042"],
        vec!["18446744073709551616", "18446744073709551616"],
    ] {
        let source = SuccessSource::new(ids.iter().map(|id| row(id)).collect());
        let error = refresh_icrc_account_transaction_cache_with_source(&request, &source)
            .expect_err("invalid custom-source rows must not publish");
        assert!(matches!(
            error,
            IcrcAccountTransactionError::IncompleteCollection {
                index_canister_id, pages_fetched: 1, rows_fetched, last_cursor, ..
            } if index_canister_id.as_deref() == Some(INDEX_CANISTER_ID)
                && rows_fetched == ids.len() && last_cursor.as_deref() == ids.last().copied()
        ));
        assert_eq!(fs::read(&path).unwrap(), before);
        let status = build_icrc_account_transaction_cache_status_report(&cache).unwrap();
        assert_eq!(
            status.cache.unwrap().cache_status,
            CacheValidationStatus::Valid
        );
        let attempt = status.latest_attempt.unwrap();
        assert_eq!(attempt.status, CacheRefreshAttemptStatus::Failed);
        assert_eq!(attempt.pages_fetched, 1);
        assert_eq!(attempt.rows_fetched, ids.len());
        assert_eq!(attempt.last_cursor.as_deref(), ids.last().copied());
    }
    fs::remove_dir_all(root).unwrap();
}

#[test]
fn cache_only_reads_validate_rows_even_when_extrema_and_counts_match() {
    let root = temp_dir("ic-query-icrc-account-persisted-row-validation");
    let cache = cache_request(&root);
    refresh_icrc_account_transaction_cache_with_source(
        &refresh_request(cache.clone(), 1_700_000_000),
        &SuccessSource::new(vec![row("12"), row("10"), row("2")]),
    )
    .unwrap();
    let path = icrc_account_transaction_cache_path(&cache).unwrap();
    let original: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
    for ids in [["12", "12", "2"], ["12", "1", "2"], ["12", "010", "2"]] {
        let mut invalid = original.clone();
        for (transaction, id) in invalid["transactions"]
            .as_array_mut()
            .unwrap()
            .iter_mut()
            .zip(ids)
        {
            transaction["id"] = json!(id);
        }
        fs::write(&path, serde_json::to_vec(&invalid).unwrap()).unwrap();
        assert!(matches!(
            load_cached_icrc_account_transactions(&cache),
            Err(IcrcAccountTransactionError::InvalidCache { .. })
        ));
        let status = build_icrc_account_transaction_cache_status_report(&cache).unwrap();
        assert_eq!(
            status.cache.unwrap().cache_status,
            CacheValidationStatus::Invalid
        );
    }
    fs::remove_dir_all(root).unwrap();
}

#[test]
fn source_claiming_completion_with_wrong_final_cursor_is_not_published() {
    let root = temp_dir("ic-query-icrc-account-invalid-completion");
    let cache = cache_request(&root);
    let request = refresh_request(cache.clone(), 1_700_000_000);

    let error = refresh_icrc_account_transaction_cache_with_source(&request, &WrongCursorSource)
        .expect_err("invalid completion evidence must fail");

    assert!(matches!(
        error,
        IcrcAccountTransactionError::IncompleteCollection {
            index_canister_id,
            pages_fetched: 1,
            rows_fetched: 1,
            last_cursor,
            reason,
        } if index_canister_id.as_deref() == Some(INDEX_CANISTER_ID)
            && last_cursor.as_deref() == Some("6")
            && reason.contains("final cursor")
    ));
    assert!(
        !icrc_account_transaction_cache_path(&cache)
            .expect("cache path")
            .exists()
    );

    let _ = fs::remove_dir_all(root);
}

#[test]
fn custom_source_must_return_the_explicitly_requested_index() {
    let root = temp_dir("ic-query-icrc-account-index-mismatch");
    let cache = cache_request(&root);
    let request = refresh_request(cache.clone(), 1_700_000_000)
        .with_index_canister_id(Principal::management_canister().to_text());

    let error = refresh_icrc_account_transaction_cache_with_source(
        &request,
        &SuccessSource::new(vec![row("7")]),
    )
    .expect_err("source index must match explicit request");

    assert!(matches!(
        error,
        IcrcAccountTransactionError::CollectionIndexMismatch {
            expected_index_canister_id,
            actual_index_canister_id,
        } if expected_index_canister_id == Principal::management_canister().to_text()
            && actual_index_canister_id == INDEX_CANISTER_ID
    ));
    assert!(
        !icrc_account_transaction_cache_path(&cache)
            .expect("cache path")
            .exists()
    );

    let _ = fs::remove_dir_all(root);
}

#[test]
fn missing_and_stale_refresh_policies_do_not_masquerade_as_each_other() {
    let root = temp_dir("ic-query-icrc-account-refresh-policy");
    let cache = cache_request(&root);
    let source = SuccessSource::new(vec![row("1")]);
    let request = refresh_request(cache.clone(), 1_700_000_000);

    load_or_refresh_missing_icrc_account_transactions_with_source(&request, &source)
        .expect("refresh missing cache");
    load_or_refresh_missing_icrc_account_transactions_with_source(&request, &source)
        .expect("reuse present cache");
    assert_eq!(source.calls.load(Ordering::Relaxed), 1);

    let stale_request = refresh_request(cache, 2_000_000_000);
    let started = std::time::Instant::now();
    let refreshed =
        load_or_refresh_stale_icrc_account_transactions_with_source(&stale_request, 60, &source)
            .expect("refresh stale cache");
    assert_eq!(source.calls.load(Ordering::Relaxed), 2);
    let completed = crate::subnet_catalog::parse_utc_timestamp_secs(
        &refreshed.snapshot.collection_completed_at,
    )
    .unwrap();
    assert_eq!(
        crate::subnet_catalog::parse_utc_timestamp_secs(&refreshed.snapshot.collection_started_at),
        Some(stale_request.now_unix_secs)
    );
    assert!(completed >= stale_request.now_unix_secs);
    assert!(completed <= stale_request.now_unix_secs + started.elapsed().as_secs());

    let _ = fs::remove_dir_all(root);
}

#[test]
fn cached_collection_requires_canonical_ordered_timestamps_and_repairs_explicitly() {
    let root = temp_dir("ic-query-icrc-account-timestamp-interval");
    let cache = cache_request(&root);
    let source = SuccessSource::new(vec![row("6")]);
    let request = refresh_request(cache.clone(), 1_700_000_000);
    refresh_icrc_account_transaction_cache_with_source(&request, &source).unwrap();
    let path = icrc_account_transaction_cache_path(&cache).unwrap();
    let mut snapshot: serde_json::Value =
        serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
    for (start, end, valid) in [
        ("2026-10-01T00:00:00Z", "2026-10-01T00:00:00Z", true),
        ("2026-10-01T00:00:00Z", "2026-10-02T00:00:00Z", true),
        ("not-a-timestamp", "2026-10-02T00:00:00Z", false),
        ("2026-10-01T00:00:00Z", "not-a-timestamp", false),
        ("2026-10-02T00:00:00Z", "2026-10-01T00:00:00Z", false),
    ] {
        snapshot["collection_started_at"] = json!(start);
        snapshot["collection_completed_at"] = json!(end);
        fs::write(&path, serde_json::to_vec(&snapshot).unwrap()).unwrap();
        match load_cached_icrc_account_transactions(&cache) {
            Ok(_) => assert!(valid),
            Err(error) => {
                assert!(!valid);
                assert!(matches!(
                    error,
                    IcrcAccountTransactionError::InvalidCache { .. }
                ));
            }
        }
    }
    let status = build_icrc_account_transaction_cache_status_report(&cache).unwrap();
    assert_eq!(
        status.cache.unwrap().cache_status,
        CacheValidationStatus::Invalid
    );
    assert_eq!(
        source.calls.load(Ordering::Relaxed),
        1,
        "cache-only reads stay local"
    );
    load_or_refresh_missing_icrc_account_transactions_with_source(&request, &source)
        .expect("authorized read-through replaces reversed interval");
    assert_eq!(source.calls.load(Ordering::Relaxed), 2);
    fs::remove_dir_all(root).unwrap();
}

#[test]
fn unrepresentable_collection_clock_preserves_the_previous_snapshot() {
    let root = temp_dir("ic-query-icrc-account-invalid-clock");
    let cache = cache_request(&root);
    let source = SuccessSource::new(vec![row("6")]);
    refresh_icrc_account_transaction_cache_with_source(
        &refresh_request(cache.clone(), 1_700_000_000),
        &source,
    )
    .unwrap();
    let path = icrc_account_transaction_cache_path(&cache).unwrap();
    let before = fs::read(&path).unwrap();
    assert!(matches!(
        refresh_icrc_account_transaction_cache_with_source(
            &refresh_request(cache.clone(), u64::MAX),
            &source,
        ),
        Err(IcrcAccountTransactionError::InvalidCache { .. })
    ));
    assert_eq!(fs::read(&path).unwrap(), before);
    assert!(
        !icrc_account_transaction_refresh_lock_path(&cache)
            .unwrap()
            .exists()
    );
    let status = build_icrc_account_transaction_cache_status_report(&cache).unwrap();
    assert_eq!(
        status.cache.unwrap().cache_status,
        CacheValidationStatus::Valid
    );
    assert_eq!(
        status.latest_attempt.unwrap().status,
        CacheRefreshAttemptStatus::Failed
    );
    fs::remove_dir_all(root).unwrap();
}

#[test]
fn read_through_account_history_refreshes_invalid_cache_but_cache_only_remains_strict() {
    let root = temp_dir("ic-query-icrc-account-invalid-cache");
    let cache = cache_request(&root);
    refresh_icrc_account_transaction_cache_with_source(
        &refresh_request(cache.clone(), 1_700_000_000),
        &SuccessSource::new(vec![row("6")]),
    )
    .expect("seed complete cache");
    let path = icrc_account_transaction_cache_path(&cache).expect("cache path");
    let mut invalid =
        serde_json::from_slice::<serde_json::Value>(&fs::read(&path).expect("read cache"))
            .expect("parse cache");
    invalid["completeness"]["row_count"] = json!(2);
    let invalid_json = serde_json::to_vec_pretty(&invalid).expect("serialize invalid cache");
    fs::write(&path, &invalid_json).expect("write invalid cache");

    let error =
        load_cached_icrc_account_transactions(&cache).expect_err("cache-only load remains strict");
    assert!(matches!(
        error,
        IcrcAccountTransactionError::InvalidCache { .. }
    ));

    let source = SuccessSource::new(vec![row("7")]);
    let cached = load_or_refresh_missing_icrc_account_transactions_with_source(
        &refresh_request(cache, 1_700_000_000),
        &source,
    )
    .expect("invalid cache refreshes");

    assert_eq!(cached.snapshot.transactions.len(), 1);
    assert_eq!(source.calls.load(Ordering::Relaxed), 1);
    assert_ne!(fs::read(path).expect("refreshed cache"), invalid_json);
    let _ = fs::remove_dir_all(root);
}

fn cache_request(root: &Path) -> IcrcAccountTransactionCacheRequest {
    IcrcAccountTransactionCacheRequest::new(
        root,
        "https://icp-api.io",
        LEDGER_CANISTER_ID,
        ACCOUNT_OWNER,
    )
}

fn refresh_request(
    cache: IcrcAccountTransactionCacheRequest,
    now_unix_secs: u64,
) -> IcrcAccountTransactionRefreshRequest {
    IcrcAccountTransactionRefreshRequest::new(cache, now_unix_secs, 100, 1_800)
}

fn row(id: &str) -> IcrcAccountTransactionRow {
    IcrcAccountTransactionRow {
        id: id.to_string(),
        kind: "transfer".to_string(),
        timestamp_unix_nanos: None,
        amount_base_units: None,
        fee_base_units: None,
        from: None,
        to: None,
        spender: None,
        memo_hex: None,
        created_at_time_unix_nanos: None,
        expires_at_unix_nanos: None,
        expected_allowance_base_units: None,
        raw_transaction: json!({"kind": "transfer"}),
    }
}

struct SuccessSource {
    calls: AtomicUsize,
    transactions: Vec<IcrcAccountTransactionRow>,
}

impl SuccessSource {
    fn new(transactions: Vec<IcrcAccountTransactionRow>) -> Self {
        Self {
            calls: AtomicUsize::new(0),
            transactions,
        }
    }
}

impl IcrcAccountTransactionCollectionSource for SuccessSource {
    fn fetch_complete_account_transactions(
        &self,
        _request: &IcrcAccountTransactionRefreshRequest,
        _progress: &mut (dyn QueryProgress + Send),
    ) -> Result<IcrcAccountTransactionCollectionData, IcrcAccountTransactionError> {
        self.calls.fetch_add(1, Ordering::Relaxed);
        Ok(IcrcAccountTransactionCollectionData {
            index_canister_id: INDEX_CANISTER_ID.to_string(),
            balance: "42".to_string(),
            token_symbol: "ICP".to_string(),
            decimals: 8,
            transactions: self.transactions.clone(),
            page_count: 1,
            last_cursor: self
                .transactions
                .last()
                .map(|transaction| transaction.id.clone()),
        })
    }
}

struct IncompleteSource;

impl IcrcAccountTransactionCollectionSource for IncompleteSource {
    fn fetch_complete_account_transactions(
        &self,
        request: &IcrcAccountTransactionRefreshRequest,
        _progress: &mut (dyn QueryProgress + Send),
    ) -> Result<IcrcAccountTransactionCollectionData, IcrcAccountTransactionError> {
        assert!(request.index_canister_id.is_none());
        Err(IcrcAccountTransactionError::IncompleteCollection {
            index_canister_id: Some(INDEX_CANISTER_ID.to_string()),
            pages_fetched: 2,
            rows_fetched: 100,
            last_cursor: Some("50".to_string()),
            reason: "fixture stopped before API exhaustion".to_string(),
        })
    }
}

struct WrongCursorSource;

impl IcrcAccountTransactionCollectionSource for WrongCursorSource {
    fn fetch_complete_account_transactions(
        &self,
        _request: &IcrcAccountTransactionRefreshRequest,
        _progress: &mut (dyn QueryProgress + Send),
    ) -> Result<IcrcAccountTransactionCollectionData, IcrcAccountTransactionError> {
        Ok(IcrcAccountTransactionCollectionData {
            index_canister_id: INDEX_CANISTER_ID.to_string(),
            balance: "42".to_string(),
            token_symbol: "ICP".to_string(),
            decimals: 8,
            transactions: vec![row("7")],
            page_count: 1,
            last_cursor: Some("6".to_string()),
        })
    }
}