chainindex-aptos 0.2.0

Aptos indexer for ChainIndex — block tracking, Move event parsing, and resource monitoring
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! Aptos indexer for ChainIndex.
//!
//! Aptos uses Move-based events and resources. This module maps Aptos blocks
//! to [`BlockSummary`] and Move events to [`DecodedEvent`].
//!
//! # Key Types
//!
//! - [`AptosBlock`] — Aptos block with version range and epoch
//! - [`AptosEvent`] — Move event with type tag and data
//! - [`AptosRpcClient`] — Trait abstracting Aptos REST API calls
//! - [`AptosIndexerBuilder`] — Fluent builder for Aptos indexer configs

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use chainindex_core::error::IndexerError;
use chainindex_core::handler::DecodedEvent;
use chainindex_core::indexer::IndexerConfig;
use chainindex_core::types::{BlockSummary, EventFilter};

// ---------------------------------------------------------------------------
// Block type
// ---------------------------------------------------------------------------

/// An Aptos block with chain-specific metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AptosBlock {
    /// Block height.
    pub height: u64,
    /// Block hash.
    pub hash: String,
    /// Timestamp in unix seconds.
    pub timestamp: i64,
    /// First transaction version in this block.
    pub first_version: u64,
    /// Last transaction version in this block.
    pub last_version: u64,
    /// Number of transactions.
    pub tx_count: u32,
    /// Current epoch.
    pub epoch: u64,
    /// Round within the epoch.
    pub round: u64,
}

impl AptosBlock {
    pub fn to_block_summary(&self) -> BlockSummary {
        BlockSummary {
            number: self.height,
            hash: self.hash.clone(),
            parent_hash: format!("version:{}", self.first_version),
            timestamp: self.timestamp,
            tx_count: self.tx_count,
        }
    }
}

// ---------------------------------------------------------------------------
// Event type
// ---------------------------------------------------------------------------

/// An Aptos Move event.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AptosEvent {
    /// Move type tag (e.g., "0x1::coin::DepositEvent").
    pub type_tag: String,
    /// Event sequence number.
    pub sequence_number: u64,
    /// Decoded event data as JSON.
    pub data: serde_json::Value,
    /// Transaction version.
    pub version: u64,
    /// Block height.
    pub height: u64,
    /// Transaction hash.
    pub tx_hash: String,
    /// Account address that emitted the event.
    pub account_address: String,
    /// Creation number (identifies the event handle).
    pub creation_number: u64,
}

impl AptosEvent {
    /// Extract the module name from the type tag.
    ///
    /// For `0x1::coin::DepositEvent`, returns `coin`.
    pub fn module_name(&self) -> &str {
        self.type_tag
            .split("::")
            .nth(1)
            .unwrap_or("unknown")
    }

    /// Extract the event name from the type tag.
    ///
    /// For `0x1::coin::DepositEvent`, returns `DepositEvent`.
    pub fn event_name(&self) -> &str {
        self.type_tag
            .split("::")
            .nth(2)
            .unwrap_or("unknown")
    }

    /// Extract the address from the type tag.
    ///
    /// For `0x1::coin::DepositEvent`, returns `0x1`.
    pub fn type_address(&self) -> &str {
        self.type_tag
            .split("::")
            .next()
            .unwrap_or("0x0")
    }

    pub fn to_decoded_event(&self, chain: &str) -> DecodedEvent {
        let schema = format!("{}::{}", self.module_name(), self.event_name());

        DecodedEvent {
            chain: chain.to_string(),
            schema,
            address: self.account_address.clone(),
            tx_hash: self.tx_hash.clone(),
            block_number: self.height,
            log_index: self.sequence_number as u32,
            fields_json: self.data.clone(),
        }
    }
}

// ---------------------------------------------------------------------------
// RPC client trait
// ---------------------------------------------------------------------------

#[async_trait]
pub trait AptosRpcClient: Send + Sync {
    /// Get current ledger info (latest block height).
    async fn get_ledger_info(&self) -> Result<u64, IndexerError>;

    /// Get block by height.
    async fn get_block_by_height(
        &self,
        height: u64,
    ) -> Result<Option<AptosBlock>, IndexerError>;

    /// Get events for a given event handle.
    async fn get_events(
        &self,
        account: &str,
        event_handle: &str,
        field_name: &str,
        start: u64,
        limit: u64,
    ) -> Result<Vec<AptosEvent>, IndexerError>;

    /// Get events emitted in a transaction.
    async fn get_transaction_events(
        &self,
        version: u64,
    ) -> Result<Vec<AptosEvent>, IndexerError>;
}

// ---------------------------------------------------------------------------
// Event filter
// ---------------------------------------------------------------------------

/// Aptos-specific event filter.
#[derive(Debug, Clone, Default)]
pub struct AptosEventFilter {
    /// Filter by Move type tag prefix (e.g., "0x1::coin").
    pub type_prefixes: Vec<String>,
    /// Filter by module name.
    pub modules: Vec<String>,
    /// Filter by account address.
    pub accounts: Vec<String>,
}

impl AptosEventFilter {
    pub fn matches(&self, event: &AptosEvent) -> bool {
        if !self.type_prefixes.is_empty()
            && !self.type_prefixes.iter().any(|p| event.type_tag.starts_with(p))
        {
            return false;
        }

        if !self.modules.is_empty()
            && !self.modules.iter().any(|m| m == event.module_name())
        {
            return false;
        }

        if !self.accounts.is_empty()
            && !self.accounts.iter().any(|a| a == &event.account_address)
        {
            return false;
        }

        true
    }
}

// ---------------------------------------------------------------------------
// Parsers
// ---------------------------------------------------------------------------

/// Parses Aptos REST API JSON responses.
pub struct AptosResponseParser;

impl AptosResponseParser {
    /// Parse a block from Aptos REST API `GET /v1/blocks/by_height/{h}`.
    pub fn parse_block(json: &serde_json::Value) -> Option<AptosBlock> {
        let height_str = json["block_height"].as_str()?;
        let height = height_str.parse::<u64>().ok()?;

        let hash = json["block_hash"].as_str().unwrap_or_default().to_string();
        let timestamp_us = json["block_timestamp"]
            .as_str()
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(0);
        let timestamp = (timestamp_us / 1_000_000) as i64;

        let first_version = json["first_version"]
            .as_str()
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);
        let last_version = json["last_version"]
            .as_str()
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let tx_count = json["transactions"]
            .as_array()
            .map(|a| a.len() as u32)
            .unwrap_or_else(|| {
                if last_version >= first_version {
                    (last_version - first_version + 1) as u32
                } else {
                    0
                }
            });

        Some(AptosBlock {
            height,
            hash,
            timestamp,
            first_version,
            last_version,
            tx_count,
            epoch: json["epoch"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0),
            round: json["round"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0),
        })
    }

    /// Parse events from an Aptos REST API events response.
    pub fn parse_events(
        json: &serde_json::Value,
        height: u64,
    ) -> Vec<AptosEvent> {
        let events_array = json.as_array();
        let Some(events) = events_array else {
            return Vec::new();
        };

        events
            .iter()
            .filter_map(|ev| {
                let type_tag = ev["type"].as_str()?.to_string();
                let sequence_number = ev["sequence_number"]
                    .as_str()
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(0);
                let data = ev.get("data").cloned().unwrap_or(serde_json::Value::Null);
                let version = ev["version"]
                    .as_str()
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(0);

                Some(AptosEvent {
                    type_tag,
                    sequence_number,
                    data,
                    version,
                    height,
                    tx_hash: ev["transaction_hash"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                    account_address: ev["guid"]["account_address"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                    creation_number: ev["guid"]["creation_number"]
                        .as_str()
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(0),
                })
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

pub struct AptosIndexerBuilder {
    from_height: u64,
    to_height: Option<u64>,
    type_prefixes: Vec<String>,
    modules: Vec<String>,
    accounts: Vec<String>,
    batch_size: u64,
    poll_interval_ms: u64,
    checkpoint_interval: u64,
    confirmation_depth: u64,
    id: String,
    chain: String,
}

impl AptosIndexerBuilder {
    pub fn new() -> Self {
        Self {
            from_height: 0,
            to_height: None,
            type_prefixes: Vec::new(),
            modules: Vec::new(),
            accounts: Vec::new(),
            batch_size: 100,
            poll_interval_ms: 4000, // ~4s block time
            checkpoint_interval: 100,
            confirmation_depth: 1, // BFT instant finality
            id: "aptos-indexer".into(),
            chain: "aptos".into(),
        }
    }

    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = id.into();
        self
    }

    pub fn chain(mut self, chain: impl Into<String>) -> Self {
        self.chain = chain.into();
        self
    }

    pub fn from_height(mut self, height: u64) -> Self {
        self.from_height = height;
        self
    }

    pub fn to_height(mut self, height: u64) -> Self {
        self.to_height = Some(height);
        self
    }

    pub fn type_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.type_prefixes.push(prefix.into());
        self
    }

    pub fn module(mut self, module: impl Into<String>) -> Self {
        self.modules.push(module.into());
        self
    }

    pub fn account(mut self, account: impl Into<String>) -> Self {
        self.accounts.push(account.into());
        self
    }

    pub fn batch_size(mut self, size: u64) -> Self {
        self.batch_size = size;
        self
    }

    pub fn poll_interval_ms(mut self, ms: u64) -> Self {
        self.poll_interval_ms = ms;
        self
    }

    pub fn build_config(&self) -> IndexerConfig {
        IndexerConfig {
            id: self.id.clone(),
            chain: self.chain.clone(),
            from_block: self.from_height,
            to_block: self.to_height,
            confirmation_depth: self.confirmation_depth,
            batch_size: self.batch_size,
            checkpoint_interval: self.checkpoint_interval,
            poll_interval_ms: self.poll_interval_ms,
            filter: EventFilter {
                addresses: self.accounts.clone(),
                topic0_values: self.type_prefixes.clone(),
                from_block: Some(self.from_height),
                to_block: self.to_height,
            },
        }
    }

    pub fn build_filter(&self) -> AptosEventFilter {
        AptosEventFilter {
            type_prefixes: self.type_prefixes.clone(),
            modules: self.modules.clone(),
            accounts: self.accounts.clone(),
        }
    }
}

impl Default for AptosIndexerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn block_to_summary() {
        let block = AptosBlock {
            height: 150_000_000,
            hash: "0xabc".into(),
            timestamp: 1700000000,
            first_version: 500_000_000,
            last_version: 500_000_050,
            tx_count: 51,
            epoch: 100,
            round: 5,
        };
        let summary = block.to_block_summary();
        assert_eq!(summary.number, 150_000_000);
        assert_eq!(summary.hash, "0xabc");
        assert_eq!(summary.tx_count, 51);
        assert_eq!(summary.parent_hash, "version:500000000");
    }

    #[test]
    fn event_type_parsing() {
        let event = AptosEvent {
            type_tag: "0x1::coin::DepositEvent".into(),
            sequence_number: 42,
            data: serde_json::json!({"amount": "1000"}),
            version: 500_000_000,
            height: 150_000_000,
            tx_hash: "tx_hash_abc".into(),
            account_address: "0xaccount".into(),
            creation_number: 1,
        };
        assert_eq!(event.module_name(), "coin");
        assert_eq!(event.event_name(), "DepositEvent");
        assert_eq!(event.type_address(), "0x1");
    }

    #[test]
    fn event_to_decoded() {
        let event = AptosEvent {
            type_tag: "0x1::coin::DepositEvent".into(),
            sequence_number: 42,
            data: serde_json::json!({"amount": "1000"}),
            version: 500_000_000,
            height: 150_000_000,
            tx_hash: "tx_hash_abc".into(),
            account_address: "0xaccount".into(),
            creation_number: 1,
        };
        let decoded = event.to_decoded_event("aptos");
        assert_eq!(decoded.chain, "aptos");
        assert_eq!(decoded.schema, "coin::DepositEvent");
        assert_eq!(decoded.address, "0xaccount");
        assert_eq!(decoded.tx_hash, "tx_hash_abc");
        assert_eq!(decoded.log_index, 42);
        assert_eq!(decoded.fields_json["amount"], "1000");
    }

    #[test]
    fn filter_type_prefix() {
        let filter = AptosEventFilter {
            type_prefixes: vec!["0x1::coin".into()],
            ..Default::default()
        };
        let event = AptosEvent {
            type_tag: "0x1::coin::DepositEvent".into(),
            sequence_number: 0,
            data: serde_json::Value::Null,
            version: 0,
            height: 0,
            tx_hash: "".into(),
            account_address: "".into(),
            creation_number: 0,
        };
        assert!(filter.matches(&event));

        let other = AptosEvent {
            type_tag: "0x1::staking::StakeEvent".into(),
            sequence_number: 0,
            data: serde_json::Value::Null,
            version: 0,
            height: 0,
            tx_hash: "".into(),
            account_address: "".into(),
            creation_number: 0,
        };
        assert!(!filter.matches(&other));
    }

    #[test]
    fn filter_module() {
        let filter = AptosEventFilter {
            modules: vec!["coin".into()],
            ..Default::default()
        };
        let event = AptosEvent {
            type_tag: "0x1::coin::DepositEvent".into(),
            sequence_number: 0,
            data: serde_json::Value::Null,
            version: 0,
            height: 0,
            tx_hash: "".into(),
            account_address: "".into(),
            creation_number: 0,
        };
        assert!(filter.matches(&event));
    }

    #[test]
    fn filter_empty_matches_all() {
        let filter = AptosEventFilter::default();
        let event = AptosEvent {
            type_tag: "anything".into(),
            sequence_number: 0,
            data: serde_json::Value::Null,
            version: 0,
            height: 0,
            tx_hash: "".into(),
            account_address: "".into(),
            creation_number: 0,
        };
        assert!(filter.matches(&event));
    }

    #[test]
    fn parse_block_json() {
        let json = serde_json::json!({
            "block_height": "150000000",
            "block_hash": "0xblock_hash_abc",
            "block_timestamp": "1700000000000000",
            "first_version": "500000000",
            "last_version": "500000050",
            "epoch": "100",
            "round": "5",
            "transactions": [{"type": "user"}, {"type": "user"}]
        });
        let block = AptosResponseParser::parse_block(&json).unwrap();
        assert_eq!(block.height, 150_000_000);
        assert_eq!(block.hash, "0xblock_hash_abc");
        assert_eq!(block.timestamp, 1700000000);
        assert_eq!(block.first_version, 500_000_000);
        assert_eq!(block.last_version, 500_000_050);
        assert_eq!(block.tx_count, 2);
        assert_eq!(block.epoch, 100);
    }

    #[test]
    fn parse_events_json() {
        let json = serde_json::json!([
            {
                "type": "0x1::coin::DepositEvent",
                "sequence_number": "42",
                "data": { "amount": "1000" },
                "version": "500000000",
                "transaction_hash": "tx_abc",
                "guid": {
                    "account_address": "0xaccount",
                    "creation_number": "1"
                }
            }
        ]);
        let events = AptosResponseParser::parse_events(&json, 150_000_000);
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].type_tag, "0x1::coin::DepositEvent");
        assert_eq!(events[0].sequence_number, 42);
        assert_eq!(events[0].account_address, "0xaccount");
    }

    #[test]
    fn builder_defaults() {
        let config = AptosIndexerBuilder::new().build_config();
        assert_eq!(config.chain, "aptos");
        assert_eq!(config.confirmation_depth, 1);
        assert_eq!(config.poll_interval_ms, 4000);
    }

    #[test]
    fn builder_custom() {
        let builder = AptosIndexerBuilder::new()
            .id("apt-idx")
            .from_height(100_000_000)
            .to_height(200_000_000)
            .type_prefix("0x1::coin")
            .module("coin")
            .account("0xaccount1")
            .batch_size(50);

        let config = builder.build_config();
        assert_eq!(config.id, "apt-idx");
        assert_eq!(config.from_block, 100_000_000);
        assert_eq!(config.to_block, Some(200_000_000));

        let filter = builder.build_filter();
        assert_eq!(filter.type_prefixes, vec!["0x1::coin"]);
        assert_eq!(filter.modules, vec!["coin"]);
        assert_eq!(filter.accounts, vec!["0xaccount1"]);
    }

    #[test]
    fn block_serializable() {
        let block = AptosBlock {
            height: 100,
            hash: "h".into(),
            timestamp: 1000,
            first_version: 500,
            last_version: 550,
            tx_count: 51,
            epoch: 10,
            round: 3,
        };
        let json = serde_json::to_string(&block).unwrap();
        let back: AptosBlock = serde_json::from_str(&json).unwrap();
        assert_eq!(back.height, 100);
        assert_eq!(back.epoch, 10);
    }

    #[test]
    fn event_serializable() {
        let event = AptosEvent {
            type_tag: "0x1::coin::DepositEvent".into(),
            sequence_number: 0,
            data: serde_json::json!({}),
            version: 0,
            height: 0,
            tx_hash: "tx".into(),
            account_address: "0x1".into(),
            creation_number: 1,
        };
        let json = serde_json::to_string(&event).unwrap();
        let back: AptosEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(back.type_tag, "0x1::coin::DepositEvent");
    }
}