fuel-core 0.48.0

Fuel client library is aggregation of all fuels service. It contains the all business logic of the fuel protocol.
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use fuel_core_storage::StorageAsMut;

use fuel_core_types::{
    entities::{
        Message,
        coins::coin::Coin,
    },
    fuel_tx::AssetId,
    services::executor::Event,
};

use crate::graphql_api::{
    ports::worker::OffChainDatabaseTransaction,
    storage::coins::{
        CoinsToSpendIndex,
        CoinsToSpendIndexKey,
    },
};

use super::error::IndexationError;

// Indicates that a message is retryable.
pub(crate) const RETRYABLE_BYTE: [u8; 1] = [0x00];

// Indicates that a message is non-retryable (also, all coins use this byte).
pub(crate) const NON_RETRYABLE_BYTE: [u8; 1] = [0x01];

fn add_coin<T>(block_st_transaction: &mut T, coin: &Coin) -> Result<(), IndexationError>
where
    T: OffChainDatabaseTransaction,
{
    let key = CoinsToSpendIndexKey::from_coin(coin);
    let storage = block_st_transaction.storage::<CoinsToSpendIndex>();
    let maybe_old_value = storage.replace(&key, &())?;
    if maybe_old_value.is_some() {
        return Err(IndexationError::CoinToSpendAlreadyIndexed {
            owner: coin.owner,
            asset_id: coin.asset_id,
            amount: coin.amount,
            utxo_id: coin.utxo_id,
        });
    }
    Ok(())
}

fn remove_coin<T>(
    block_st_transaction: &mut T,
    coin: &Coin,
) -> Result<(), IndexationError>
where
    T: OffChainDatabaseTransaction,
{
    let key = CoinsToSpendIndexKey::from_coin(coin);
    let storage = block_st_transaction.storage::<CoinsToSpendIndex>();
    let maybe_old_value = storage.take(&key)?;
    if maybe_old_value.is_none() {
        return Err(IndexationError::CoinToSpendNotFound {
            owner: coin.owner,
            asset_id: coin.asset_id,
            amount: coin.amount,
            utxo_id: coin.utxo_id,
        });
    }
    Ok(())
}

fn add_message<T>(
    block_st_transaction: &mut T,
    message: &Message,
    base_asset_id: &AssetId,
) -> Result<(), IndexationError>
where
    T: OffChainDatabaseTransaction,
{
    let key = CoinsToSpendIndexKey::from_message(message, base_asset_id);
    let storage = block_st_transaction.storage::<CoinsToSpendIndex>();
    let maybe_old_value = storage.replace(&key, &())?;
    if maybe_old_value.is_some() {
        return Err(IndexationError::MessageToSpendAlreadyIndexed {
            owner: *message.recipient(),
            amount: message.amount(),
            nonce: *message.nonce(),
        });
    }
    Ok(())
}

fn remove_message<T>(
    block_st_transaction: &mut T,
    message: &Message,
    base_asset_id: &AssetId,
) -> Result<(), IndexationError>
where
    T: OffChainDatabaseTransaction,
{
    let key = CoinsToSpendIndexKey::from_message(message, base_asset_id);
    let storage = block_st_transaction.storage::<CoinsToSpendIndex>();
    let maybe_old_value = storage.take(&key)?;
    if maybe_old_value.is_none() {
        return Err(IndexationError::MessageToSpendNotFound {
            owner: *message.recipient(),
            amount: message.amount(),
            nonce: *message.nonce(),
        });
    }
    Ok(())
}

pub(crate) fn update<T>(
    event: &Event,
    block_st_transaction: &mut T,
    enabled: bool,
    base_asset_id: &AssetId,
) -> Result<(), IndexationError>
where
    T: OffChainDatabaseTransaction,
{
    if !enabled {
        return Ok(());
    }

    match event {
        Event::MessageImported(message) => {
            add_message(block_st_transaction, message, base_asset_id)
        }
        Event::MessageConsumed(message) => {
            remove_message(block_st_transaction, message, base_asset_id)
        }
        Event::CoinCreated(coin) => add_coin(block_st_transaction, coin),
        Event::CoinConsumed(coin) => remove_coin(block_st_transaction, coin),
        Event::ForcedTransactionFailed { .. } => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use fuel_core_storage::{
        StorageAsMut,
        iter::IterDirection,
        transactional::WriteTransaction,
    };
    use fuel_core_types::{
        fuel_tx::{
            Address,
            AssetId,
        },
        services::executor::Event,
    };
    use rand::seq::SliceRandom;

    use itertools::Itertools;
    use proptest::{
        collection::vec,
        prelude::*,
    };

    use crate::{
        database::{
            Database,
            database_description::off_chain::OffChain,
        },
        graphql_api::{
            indexation::{
                coins_to_spend::{
                    RETRYABLE_BYTE,
                    update,
                },
                error::IndexationError,
                test_utils::{
                    make_coin,
                    make_nonretryable_message,
                    make_retryable_message,
                },
            },
            storage::coins::{
                CoinsToSpendIndex,
                CoinsToSpendIndexKey,
            },
        },
        state::rocks_db::DatabaseConfig,
    };

    use super::NON_RETRYABLE_BYTE;

    fn assert_index_entries(
        db: &Database<OffChain>,
        expected_entries: &[(Address, AssetId, [u8; 1], u64)],
    ) {
        let actual_entries: Vec<_> = db
            .entries::<CoinsToSpendIndex>(None, IterDirection::Forward)
            .map(|entry| entry.expect("should read entries"))
            .map(|entry| {
                (
                    *entry.key.owner(),
                    *entry.key.asset_id(),
                    [entry.key.retryable_flag()],
                    entry.key.amount(),
                )
            })
            .collect();

        assert_eq!(expected_entries, actual_entries.as_slice());
    }

    #[test]
    fn coins_to_spend_indexation_enabled_flag_is_respected() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_DISABLED: bool = false;
        let base_asset_id = AssetId::from([0; 32]);

        let owner_1 = Address::from([1; 32]);
        let owner_2 = Address::from([2; 32]);

        let asset_id_1 = AssetId::from([11; 32]);
        let asset_id_2 = AssetId::from([12; 32]);

        let coin_1 = make_coin(&owner_1, &asset_id_1, 100);
        let coin_2 = make_coin(&owner_1, &asset_id_2, 200);
        let message_1 = make_retryable_message(&owner_1, 300);
        let message_2 = make_nonretryable_message(&owner_2, 400);

        // Initial set of coins
        let events: Vec<Event> = vec![
            Event::CoinCreated(coin_1),
            Event::CoinConsumed(coin_2),
            Event::MessageImported(message_1.clone()),
            Event::MessageConsumed(message_2.clone()),
        ];

        // When
        events.iter().for_each(|event| {
            update(
                event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_DISABLED,
                &base_asset_id,
            )
            .expect("should process balance");
        });

        // Then
        let key = CoinsToSpendIndexKey::from_coin(&coin_1);
        let coin = tx
            .storage::<CoinsToSpendIndex>()
            .get(&key)
            .expect("should correctly query db");
        assert!(coin.is_none());

        let key = CoinsToSpendIndexKey::from_coin(&coin_2);
        let coin = tx
            .storage::<CoinsToSpendIndex>()
            .get(&key)
            .expect("should correctly query db");
        assert!(coin.is_none());

        let key = CoinsToSpendIndexKey::from_message(&message_1, &base_asset_id);
        let message = tx
            .storage::<CoinsToSpendIndex>()
            .get(&key)
            .expect("should correctly query db");
        assert!(message.is_none());

        let key = CoinsToSpendIndexKey::from_message(&message_2, &base_asset_id);
        let message = tx
            .storage::<CoinsToSpendIndex>()
            .get(&key)
            .expect("should correctly query db");
        assert!(message.is_none());
    }

    #[test]
    fn coin_owner_and_asset_id_is_respected() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);

        let owner_1 = Address::from([1; 32]);
        let owner_2 = Address::from([2; 32]);

        let asset_id_1 = AssetId::from([11; 32]);
        let asset_id_2 = AssetId::from([12; 32]);

        // Initial set of coins of the same asset id - mind the random order of amounts
        let mut events: Vec<Event> = vec![
            Event::CoinCreated(make_coin(&owner_1, &asset_id_1, 100)),
            Event::CoinCreated(make_coin(&owner_1, &asset_id_1, 300)),
            Event::CoinCreated(make_coin(&owner_1, &asset_id_1, 200)),
        ];

        // Add more coins, some of them for the new asset id - mind the random order of amounts
        events.extend([
            Event::CoinCreated(make_coin(&owner_1, &asset_id_2, 10)),
            Event::CoinCreated(make_coin(&owner_1, &asset_id_2, 12)),
            Event::CoinCreated(make_coin(&owner_1, &asset_id_2, 11)),
            Event::CoinCreated(make_coin(&owner_1, &asset_id_1, 150)),
        ]);

        // Add another owner into the mix
        events.extend([
            Event::CoinCreated(make_coin(&owner_2, &asset_id_1, 1000)),
            Event::CoinCreated(make_coin(&owner_2, &asset_id_1, 2000)),
            Event::CoinCreated(make_coin(&owner_2, &asset_id_1, 200000)),
            Event::CoinCreated(make_coin(&owner_2, &asset_id_1, 1500)),
            Event::CoinCreated(make_coin(&owner_2, &asset_id_2, 900)),
            Event::CoinCreated(make_coin(&owner_2, &asset_id_2, 800)),
            Event::CoinCreated(make_coin(&owner_2, &asset_id_2, 700)),
        ]);

        // Consume some coins
        events.extend([
            Event::CoinConsumed(make_coin(&owner_1, &asset_id_1, 300)),
            Event::CoinConsumed(make_coin(&owner_2, &asset_id_1, 200000)),
        ]);

        // When

        // Process all events
        events.iter().for_each(|event| {
            update(
                event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_ENABLED,
                &base_asset_id,
            )
            .expect("should process coins to spend");
        });
        tx.commit().expect("should commit transaction");

        // Then

        // Mind the sorted amounts
        let expected_index_entries = &[
            (owner_1, asset_id_1, NON_RETRYABLE_BYTE, 100),
            (owner_1, asset_id_1, NON_RETRYABLE_BYTE, 150),
            (owner_1, asset_id_1, NON_RETRYABLE_BYTE, 200),
            (owner_1, asset_id_2, NON_RETRYABLE_BYTE, 10),
            (owner_1, asset_id_2, NON_RETRYABLE_BYTE, 11),
            (owner_1, asset_id_2, NON_RETRYABLE_BYTE, 12),
            (owner_2, asset_id_1, NON_RETRYABLE_BYTE, 1000),
            (owner_2, asset_id_1, NON_RETRYABLE_BYTE, 1500),
            (owner_2, asset_id_1, NON_RETRYABLE_BYTE, 2000),
            (owner_2, asset_id_2, NON_RETRYABLE_BYTE, 700),
            (owner_2, asset_id_2, NON_RETRYABLE_BYTE, 800),
            (owner_2, asset_id_2, NON_RETRYABLE_BYTE, 900),
        ];

        assert_index_entries(&db, expected_index_entries);
    }

    #[test]
    fn message_owner_is_respected() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);

        let owner_1 = Address::from([1; 32]);
        let owner_2 = Address::from([2; 32]);

        // Initial set of coins of the same asset id - mind the random order of amounts
        let mut events: Vec<Event> = vec![
            Event::MessageImported(make_nonretryable_message(&owner_1, 100)),
            Event::MessageImported(make_nonretryable_message(&owner_1, 300)),
            Event::MessageImported(make_nonretryable_message(&owner_1, 200)),
        ];

        // Add another owner into the mix
        events.extend([
            Event::MessageImported(make_nonretryable_message(&owner_2, 1000)),
            Event::MessageImported(make_nonretryable_message(&owner_2, 2000)),
            Event::MessageImported(make_nonretryable_message(&owner_2, 200000)),
            Event::MessageImported(make_nonretryable_message(&owner_2, 800)),
            Event::MessageImported(make_nonretryable_message(&owner_2, 700)),
        ]);

        // Consume some coins
        events.extend([
            Event::MessageConsumed(make_nonretryable_message(&owner_1, 300)),
            Event::MessageConsumed(make_nonretryable_message(&owner_2, 200000)),
        ]);

        // When

        // Process all events
        events.iter().for_each(|event| {
            update(
                event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_ENABLED,
                &base_asset_id,
            )
            .expect("should process coins to spend");
        });
        tx.commit().expect("should commit transaction");

        // Then

        // Mind the sorted amounts
        let expected_index_entries = &[
            (owner_1, base_asset_id, NON_RETRYABLE_BYTE, 100),
            (owner_1, base_asset_id, NON_RETRYABLE_BYTE, 200),
            (owner_2, base_asset_id, NON_RETRYABLE_BYTE, 700),
            (owner_2, base_asset_id, NON_RETRYABLE_BYTE, 800),
            (owner_2, base_asset_id, NON_RETRYABLE_BYTE, 1000),
            (owner_2, base_asset_id, NON_RETRYABLE_BYTE, 2000),
        ];

        assert_index_entries(&db, expected_index_entries);
    }

    #[test]
    fn coins_with_retryable_and_non_retryable_messages_are_not_mixed() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);
        let owner = Address::from([1; 32]);
        let asset_id = AssetId::from([11; 32]);

        let mut events = vec![
            Event::CoinCreated(make_coin(&owner, &asset_id, 101)),
            Event::CoinCreated(make_coin(&owner, &asset_id, 100)),
            Event::CoinCreated(make_coin(&owner, &base_asset_id, 200000)),
            Event::CoinCreated(make_coin(&owner, &base_asset_id, 201)),
            Event::CoinCreated(make_coin(&owner, &base_asset_id, 200)),
            Event::MessageImported(make_retryable_message(&owner, 301)),
            Event::MessageImported(make_retryable_message(&owner, 200000)),
            Event::MessageImported(make_retryable_message(&owner, 300)),
            Event::MessageImported(make_nonretryable_message(&owner, 401)),
            Event::MessageImported(make_nonretryable_message(&owner, 200000)),
            Event::MessageImported(make_nonretryable_message(&owner, 400)),
        ];
        events.shuffle(&mut rand::thread_rng());

        // Delete the "big" coins
        events.extend([
            Event::CoinConsumed(make_coin(&owner, &base_asset_id, 200000)),
            Event::MessageConsumed(make_retryable_message(&owner, 200000)),
            Event::MessageConsumed(make_nonretryable_message(&owner, 200000)),
        ]);

        // When

        // Process all events
        events.iter().for_each(|event| {
            update(
                event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_ENABLED,
                &base_asset_id,
            )
            .expect("should process coins to spend");
        });
        tx.commit().expect("should commit transaction");

        // Then

        // Mind the amounts are always correctly sorted
        let expected_index_entries = &[
            (owner, base_asset_id, RETRYABLE_BYTE, 300),
            (owner, base_asset_id, RETRYABLE_BYTE, 301),
            (owner, base_asset_id, NON_RETRYABLE_BYTE, 200),
            (owner, base_asset_id, NON_RETRYABLE_BYTE, 201),
            (owner, base_asset_id, NON_RETRYABLE_BYTE, 400),
            (owner, base_asset_id, NON_RETRYABLE_BYTE, 401),
            (owner, asset_id, NON_RETRYABLE_BYTE, 100),
            (owner, asset_id, NON_RETRYABLE_BYTE, 101),
        ];

        assert_index_entries(&db, expected_index_entries);
    }

    #[test]
    fn double_insertion_of_message_causes_error() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);
        let owner = Address::from([1; 32]);

        let message = make_nonretryable_message(&owner, 400);
        let message_event = Event::MessageImported(message.clone());
        assert!(
            update(
                &message_event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_ENABLED,
                &base_asset_id,
            )
            .is_ok()
        );

        // When
        let result = update(
            &message_event,
            &mut tx,
            COINS_TO_SPEND_INDEX_IS_ENABLED,
            &base_asset_id,
        );

        // Then
        assert_eq!(
            result.unwrap_err().to_string(),
            IndexationError::MessageToSpendAlreadyIndexed {
                owner,
                amount: 400,
                nonce: *message.nonce(),
            }
            .to_string()
        );
    }

    #[test]
    fn double_insertion_of_coin_causes_error() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);
        let owner = Address::from([1; 32]);
        let asset_id = AssetId::from([11; 32]);

        let coin = make_coin(&owner, &asset_id, 100);
        let coin_event = Event::CoinCreated(coin);

        assert!(
            update(
                &coin_event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_ENABLED,
                &base_asset_id,
            )
            .is_ok()
        );

        // When
        let result = update(
            &coin_event,
            &mut tx,
            COINS_TO_SPEND_INDEX_IS_ENABLED,
            &base_asset_id,
        );

        // Then
        assert_eq!(
            result.unwrap_err().to_string(),
            IndexationError::CoinToSpendAlreadyIndexed {
                owner,
                asset_id,
                amount: 100,
                utxo_id: coin.utxo_id,
            }
            .to_string()
        );
    }

    #[test]
    fn removal_of_non_existing_coin_causes_error() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);
        let owner = Address::from([1; 32]);
        let asset_id = AssetId::from([11; 32]);

        let coin = make_coin(&owner, &asset_id, 100);
        let coin_event = Event::CoinConsumed(coin);

        // When
        let result = update(
            &coin_event,
            &mut tx,
            COINS_TO_SPEND_INDEX_IS_ENABLED,
            &base_asset_id,
        );

        // Then
        assert_eq!(
            result.unwrap_err().to_string(),
            IndexationError::CoinToSpendNotFound {
                owner,
                asset_id,
                amount: 100,
                utxo_id: coin.utxo_id,
            }
            .to_string()
        );

        let message = make_nonretryable_message(&owner, 400);
        let message_event = Event::MessageConsumed(message.clone());
        assert_eq!(
            update(
                &message_event,
                &mut tx,
                COINS_TO_SPEND_INDEX_IS_ENABLED,
                &base_asset_id,
            )
            .unwrap_err()
            .to_string(),
            IndexationError::MessageToSpendNotFound {
                owner,
                amount: 400,
                nonce: *message.nonce(),
            }
            .to_string()
        );
    }

    #[test]
    fn removal_of_non_existing_message_causes_error() {
        use tempfile::TempDir;
        let tmp_dir = TempDir::new().unwrap();
        let mut db: Database<OffChain> = Database::open_rocksdb(
            tmp_dir.path(),
            Default::default(),
            DatabaseConfig::config_for_tests(),
        )
        .unwrap();
        let mut tx = db.write_transaction();

        // Given
        const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;
        let base_asset_id = AssetId::from([0; 32]);
        let owner = Address::from([1; 32]);

        let message = make_nonretryable_message(&owner, 400);
        let message_event = Event::MessageConsumed(message.clone());

        // When
        let result = update(
            &message_event,
            &mut tx,
            COINS_TO_SPEND_INDEX_IS_ENABLED,
            &base_asset_id,
        );

        // Then
        assert_eq!(
            result.unwrap_err().to_string(),
            IndexationError::MessageToSpendNotFound {
                owner,
                amount: 400,
                nonce: *message.nonce(),
            }
            .to_string()
        );
    }

    proptest! {
        #[test]
        fn test_coin_index_is_sorted(
            amounts in vec(any::<u64>(), 1..100),
        ) {
            use tempfile::TempDir;
            let tmp_dir = TempDir::new().unwrap();
            let mut db: Database<OffChain> = Database::open_rocksdb(
                tmp_dir.path(),
                Default::default(),
                DatabaseConfig::config_for_tests(),
            )
            .unwrap();
            let mut tx = db.write_transaction();
            let base_asset_id = AssetId::from([0; 32]);

            const COINS_TO_SPEND_INDEX_IS_ENABLED: bool = true;

            let events: Vec<_> = amounts.iter()
                // Given
                .map(|&amount| Event::CoinCreated(make_coin(&Address::from([1; 32]), &AssetId::from([11; 32]), amount)))
                .collect();

                // When
                events.iter().for_each(|event| {
                    update(
                        event,
                        &mut tx,
                        COINS_TO_SPEND_INDEX_IS_ENABLED,
                        &base_asset_id,
                    )
                    .expect("should process coins to spend");
                });
                tx.commit().expect("should commit transaction");

                // Then
                let actual_amounts: Vec<_> = db
                    .entries::<CoinsToSpendIndex>(None, IterDirection::Forward)
                    .map(|entry| entry.expect("should read entries"))
                    .map(|entry|
                            entry.key.amount(),
                    )
                    .collect();

                let sorted_amounts = amounts.iter().copied().sorted().collect::<Vec<_>>();

                prop_assert_eq!(sorted_amounts, actual_amounts);
        }
    }
}