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
use super::storage::{
    assets::AssetDetails,
    balances::TotalBalanceAmount,
};
use crate::fuel_core_graphql_api::storage::coins::CoinsToSpendIndexKey;
use async_trait::async_trait;
use fuel_core_services::stream::BoxStream;
use fuel_core_storage::{
    Error as StorageError,
    Result as StorageResult,
    StorageInspect,
    StorageRead,
    iter::{
        BoxedIter,
        IterDirection,
    },
    tables::{
        BlobData,
        Coins,
        ContractsAssets,
        ContractsRawCode,
        Messages,
        StateTransitionBytecodeVersions,
        UploadedBytecodes,
    },
};
use fuel_core_tx_status_manager::TxStatusMessage;
use fuel_core_txpool::TxPoolStats;
use fuel_core_types::{
    blockchain::{
        block::CompressedBlock,
        consensus::Consensus,
        header::{
            ConsensusParametersVersion,
            StateTransitionBytecodeVersion,
        },
        primitives::{
            BlockId,
            DaBlockHeight,
        },
    },
    entities::relayer::{
        message::{
            MerkleProof,
            Message,
        },
        transaction::RelayedTransactionStatus,
    },
    fuel_tx::{
        Bytes32,
        ConsensusParameters,
        Salt,
        Transaction,
        TxId,
        TxPointer,
        UtxoId,
    },
    fuel_types::{
        Address,
        AssetId,
        BlockHeight,
        ContractId,
        Nonce,
    },
    fuel_vm::interpreter::Memory,
    services::{
        executor::{
            DryRunResult,
            StorageReadReplayEvent,
        },
        graphql_api::ContractBalance,
        p2p::PeerInfo,
        transaction_status::{
            self,
            TransactionStatus,
        },
    },
    tai64::Tai64,
};
use std::sync::Arc;

pub struct CoinsToSpendIndexIter<'a> {
    pub big_coins_iter: BoxedIter<'a, Result<CoinsToSpendIndexKey, StorageError>>,
    pub dust_coins_iter: BoxedIter<'a, Result<CoinsToSpendIndexKey, StorageError>>,
}

pub trait OffChainDatabase: Send + Sync {
    fn block_height(&self, block_id: &BlockId) -> StorageResult<BlockHeight>;

    fn tx_status(
        &self,
        tx_id: &TxId,
    ) -> StorageResult<transaction_status::TransactionExecutionStatus>;

    fn balance(
        &self,
        owner: &Address,
        asset_id: &AssetId,
        base_asset_id: &AssetId,
    ) -> StorageResult<TotalBalanceAmount>;

    fn balances<'a>(
        &'a self,
        owner: &Address,
        start: Option<AssetId>,
        base_asset_id: &'a AssetId,
        direction: IterDirection,
    ) -> BoxedIter<'a, StorageResult<(AssetId, TotalBalanceAmount)>>;

    fn owned_coins_ids(
        &self,
        owner: &Address,
        start_coin: Option<UtxoId>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<UtxoId>>;

    fn owned_message_ids(
        &self,
        owner: &Address,
        start_message_id: Option<Nonce>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<Nonce>>;

    fn owned_transactions_ids(
        &self,
        owner: Address,
        start: Option<TxPointer>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<(TxPointer, TxId)>>;

    fn coins_to_spend_index(
        &self,
        owner: &Address,
        asset_id: &AssetId,
    ) -> CoinsToSpendIndexIter<'_>;

    fn contract_salt(&self, contract_id: &ContractId) -> StorageResult<Salt>;

    fn old_block(&self, height: &BlockHeight) -> StorageResult<CompressedBlock>;

    fn old_blocks(
        &self,
        height: Option<BlockHeight>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<CompressedBlock>>;

    fn old_block_consensus(&self, height: &BlockHeight) -> StorageResult<Consensus>;

    fn old_transaction(&self, id: &TxId) -> StorageResult<Option<Transaction>>;

    fn relayed_tx_status(
        &self,
        id: Bytes32,
    ) -> StorageResult<Option<RelayedTransactionStatus>>;

    fn message_is_spent(&self, nonce: &Nonce) -> StorageResult<bool>;

    fn asset_info(&self, asset_id: &AssetId) -> StorageResult<Option<AssetDetails>>;
}

/// The on chain database port expected by GraphQL API service.
pub trait OnChainDatabase:
    Send
    + Sync
    + DatabaseBlocks
    + DatabaseMessages
    + StorageInspect<Coins, Error = StorageError>
    + StorageRead<BlobData, Error = StorageError>
    + StorageInspect<StateTransitionBytecodeVersions, Error = StorageError>
    + StorageInspect<UploadedBytecodes, Error = StorageError>
    + DatabaseContracts
    + DatabaseChain
    + DatabaseMessageProof
{
}

/// Trait that specifies all the getters required for blocks.
pub trait DatabaseBlocks {
    /// Get a transaction by its id.
    fn transaction(&self, tx_id: &TxId) -> StorageResult<Transaction>;

    /// Get a block by its height.
    fn block(&self, height: &BlockHeight) -> StorageResult<CompressedBlock>;

    fn blocks(
        &self,
        height: Option<BlockHeight>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<CompressedBlock>>;

    fn latest_height(&self) -> StorageResult<BlockHeight>;

    /// Get the consensus for a block.
    fn consensus(&self, id: &BlockHeight) -> StorageResult<Consensus>;
}

/// Trait that specifies all the getters required for DA compressed blocks.
pub trait DatabaseDaCompressedBlocks: Send + Sync {
    /// Get a DA compressed block by its height.
    fn da_compressed_block(&self, height: &BlockHeight) -> StorageResult<Vec<u8>>;
}

/// Trait that specifies all the getters required for messages.
pub trait DatabaseMessages: StorageInspect<Messages, Error = StorageError> {
    fn all_messages(
        &self,
        start_message_id: Option<Nonce>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<Message>>;

    fn message_exists(&self, nonce: &Nonce) -> StorageResult<bool>;
}

pub trait DatabaseRelayedTransactions {
    fn transaction_status(
        &self,
        id: Bytes32,
    ) -> StorageResult<Option<RelayedTransactionStatus>>;
}

/// Trait that specifies all the getters required for contract.
pub trait DatabaseContracts:
    StorageInspect<ContractsRawCode, Error = StorageError>
    + StorageInspect<ContractsAssets, Error = StorageError>
{
    fn contract_balances(
        &self,
        contract: ContractId,
        start_asset: Option<AssetId>,
        direction: IterDirection,
    ) -> BoxedIter<'_, StorageResult<ContractBalance>>;

    fn contract_storage_slots(
        &self,
        contract: ContractId,
    ) -> BoxedIter<'_, StorageResult<(Bytes32, Vec<u8>)>>;

    fn contract_storage_balances(
        &self,
        contract: ContractId,
    ) -> BoxedIter<'_, StorageResult<ContractBalance>>;
}

/// Trait that specifies all the getters required for chain metadata.
pub trait DatabaseChain {
    fn da_height(&self) -> StorageResult<DaBlockHeight>;
}

#[async_trait]
pub trait TxPoolPort: Send + Sync {
    async fn transaction(&self, id: TxId) -> anyhow::Result<Option<Transaction>>;

    async fn insert(&self, txs: Transaction) -> anyhow::Result<()>;

    fn latest_pool_stats(&self) -> TxPoolStats;
}

#[async_trait]
pub trait TxStatusManager: Send + Sync {
    async fn status(&self, tx_id: TxId) -> anyhow::Result<Option<TransactionStatus>>;

    async fn tx_update_subscribe(
        &self,
        tx_id: TxId,
    ) -> anyhow::Result<BoxStream<TxStatusMessage>>;

    fn subscribe_txs_updates(
        &self,
    ) -> anyhow::Result<BoxStream<anyhow::Result<(TxId, TransactionStatus)>>>;
}

#[async_trait]
pub trait BlockProducerPort: Send + Sync {
    async fn dry_run_txs(
        &self,
        transactions: Vec<Transaction>,
        height: Option<BlockHeight>,
        time: Option<Tai64>,
        utxo_validation: Option<bool>,
        gas_price: Option<u64>,
        record_storage_reads: bool,
    ) -> anyhow::Result<DryRunResult>;

    async fn storage_read_replay(
        &self,
        height: BlockHeight,
    ) -> anyhow::Result<Vec<StorageReadReplayEvent>>;
}

#[async_trait::async_trait]
pub trait ConsensusModulePort: Send + Sync {
    async fn manually_produce_blocks(
        &self,
        start_time: Option<Tai64>,
        number_of_blocks: u32,
    ) -> anyhow::Result<()>;
}

/// Trait that specifies queries supported by the database.
pub trait DatabaseMessageProof: Send + Sync {
    /// Gets the [`MerkleProof`] for the message block at `message_block_height` height
    /// relatively to the commit block where message block <= commit block.
    fn block_history_proof(
        &self,
        message_block_height: &BlockHeight,
        commit_block_height: &BlockHeight,
    ) -> StorageResult<MerkleProof>;
}

#[async_trait::async_trait]
pub trait P2pPort: Send + Sync {
    async fn all_peer_info(&self) -> anyhow::Result<Vec<PeerInfo>>;
}

/// Trait for defining how to estimate gas price for future blocks
pub trait GasPriceEstimate: Send + Sync {
    /// The worst case scenario for gas price at a given horizon
    fn worst_case_gas_price(&self, height: BlockHeight) -> Option<u64>;
}

/// Trait for getting VM memory.
#[async_trait::async_trait]
pub trait MemoryPool {
    type Memory: Memory + Send + Sync + 'static;

    /// Get the memory instance.
    async fn get_memory(&self) -> Self::Memory;
}

pub mod worker {
    use super::super::storage::blocks::FuelBlockIdsToHeights;
    use crate::{
        fuel_core_graphql_api::storage::{
            coins::OwnedCoins,
            contracts::ContractsInfo,
            messages::{
                OwnedMessageIds,
                SpentMessages,
            },
        },
        graphql_api::storage::{
            assets::AssetsInfo,
            balances::{
                CoinBalances,
                MessageBalances,
            },
            coins::CoinsToSpendIndex,
            old::{
                OldFuelBlockConsensus,
                OldFuelBlocks,
                OldTransactions,
            },
            relayed_transactions::RelayedTransactionStatuses,
        },
    };
    use derive_more::Display;
    use fuel_core_services::stream::BoxStream;
    use fuel_core_storage::{
        Error as StorageError,
        Result as StorageResult,
        StorageMutate,
    };
    use fuel_core_types::{
        fuel_tx::{
            Address,
            Bytes32,
        },
        fuel_types::BlockHeight,
        services::{
            block_importer::SharedImportResult,
            transaction_status::{
                self,
                TransactionStatus,
            },
        },
    };

    pub trait OnChainDatabase: Send + Sync {
        /// Returns the latest block height.
        fn latest_height(&self) -> StorageResult<Option<BlockHeight>>;
    }

    pub trait OffChainDatabase: Send + Sync {
        type Transaction<'a>: OffChainDatabaseTransaction
        where
            Self: 'a;

        /// Returns the latest block height.
        fn latest_height(&self) -> StorageResult<Option<BlockHeight>>;

        /// Creates a write database transaction.
        fn transaction(&mut self) -> Self::Transaction<'_>;

        /// Checks if Balances indexation functionality is available.
        fn balances_indexation_enabled(&self) -> StorageResult<bool>;

        /// Checks if CoinsToSpend indexation functionality is available.
        fn coins_to_spend_indexation_enabled(&self) -> StorageResult<bool>;

        /// Checks if AssetMetadata indexation functionality is available.
        fn asset_metadata_indexation_enabled(&self) -> StorageResult<bool>;
    }

    /// Represents either the Genesis Block or a block at a specific height
    #[derive(Copy, Clone, Debug, Display, PartialEq, Eq, Hash, Ord, PartialOrd)]
    pub enum BlockAt {
        /// Block at a specific height
        Specific(BlockHeight),
        /// Genesis block
        Genesis,
    }

    pub trait OffChainDatabaseTransaction:
        StorageMutate<OwnedMessageIds, Error = StorageError>
        + StorageMutate<OwnedCoins, Error = StorageError>
        + StorageMutate<FuelBlockIdsToHeights, Error = StorageError>
        + StorageMutate<ContractsInfo, Error = StorageError>
        + StorageMutate<OldFuelBlocks, Error = StorageError>
        + StorageMutate<OldFuelBlockConsensus, Error = StorageError>
        + StorageMutate<OldTransactions, Error = StorageError>
        + StorageMutate<SpentMessages, Error = StorageError>
        + StorageMutate<RelayedTransactionStatuses, Error = StorageError>
        + StorageMutate<CoinBalances, Error = StorageError>
        + StorageMutate<MessageBalances, Error = StorageError>
        + StorageMutate<CoinsToSpendIndex, Error = StorageError>
        + StorageMutate<AssetsInfo, Error = StorageError>
    {
        fn record_tx_id_owner(
            &mut self,
            owner: &Address,
            block_height: BlockHeight,
            tx_idx: u16,
            tx_id: &Bytes32,
        ) -> StorageResult<()>;

        fn update_tx_status(
            &mut self,
            id: &Bytes32,
            status: transaction_status::TransactionExecutionStatus,
        ) -> StorageResult<Option<transaction_status::TransactionExecutionStatus>>;

        /// Update metadata about the total number of transactions on the chain.
        /// Returns the total count after the update.
        fn increase_tx_count(&mut self, new_txs_count: u64) -> StorageResult<u64>;

        /// Gets the total number of transactions on the chain from metadata.
        fn get_tx_count(&self) -> StorageResult<u64>;

        /// Commits the underlying changes into the database.
        fn commit(self) -> StorageResult<()>;
    }

    pub trait BlockImporter: Send + Sync {
        /// Returns a stream of imported block.
        fn block_events(&self) -> BoxStream<SharedImportResult>;

        /// Return the import result at the given height.
        fn block_event_at_height(
            &self,
            height: BlockAt,
        ) -> anyhow::Result<SharedImportResult>;
    }

    pub trait TxStatusCompletion: Send + Sync {
        /// Sends the complete status of the transaction.
        fn send_complete(
            &self,
            id: Bytes32,
            block_height: &BlockHeight,
            status: TransactionStatus,
        );
    }
}

#[cfg_attr(feature = "test-helpers", mockall::automock)]
pub trait ChainStateProvider: Send + Sync {
    /// Returns current consensus parameters.
    fn current_consensus_params(&self) -> Arc<ConsensusParameters>;

    /// Returns current consensus parameters version.
    fn current_consensus_parameters_version(&self) -> ConsensusParametersVersion;

    /// Returns consensus parameters at a specific version.
    fn consensus_params_at_version(
        &self,
        version: &ConsensusParametersVersion,
    ) -> anyhow::Result<Arc<ConsensusParameters>>;

    /// Returns the current state transition bytecode version.
    fn current_stf_version(&self) -> StateTransitionBytecodeVersion;
}

pub trait OnChainDatabaseAt: Send + Sync {
    fn contract_slot_values(
        &self,
        contract_id: ContractId,
        storage_slots: Vec<Bytes32>,
    ) -> BoxedIter<'_, StorageResult<(Bytes32, Vec<u8>)>>;

    fn contract_balance_values(
        &self,
        contract_id: ContractId,
        assets: Vec<AssetId>,
    ) -> BoxedIter<'_, StorageResult<ContractBalance>>;
}

pub trait OffChainDatabaseAt: Send + Sync {}